Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,21 +482,19 @@ def get_lines_from_file(
if has_data_collection_enabled(client_options):
context_lines = client_options["data_collection"]["frame_context_lines"]

source = None
if loader is not None and hasattr(loader, "get_source"):
try:
source = linecache.getlines(filename)
except (OSError, IOError):
source = []

if not source and loader is not None and hasattr(loader, "get_source"):
try:
source_str: "Optional[str]" = loader.get_source(module)
except (ImportError, IOError):
source_str = None
if source_str is not None:
source = source_str.splitlines()

if source is None:
try:
source = linecache.getlines(filename)
except (OSError, IOError):
return [], None, []

if not source:
return [], None, []

Expand Down
41 changes: 41 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,47 @@ def fake_getlines(filename):
assert result == expected_result


def test_get_lines_from_file_prefers_linecache(tmp_path):
filename = tmp_path / "source.py"
filename.write_text("before\ntarget\nafter\n")
calls = []

class Loader:
def get_source(self, module):
calls.append(module)
return "loader source\n"

result = get_lines_from_file(
str(filename), 1, loader=Loader(), module="source_module"
)

assert result == (["before"], "target", ["after"])
assert calls == []


def test_get_lines_from_file_falls_back_to_loader(tmp_path):
filename = tmp_path / "missing.py"
calls = []

class Loader:
def get_source(self, module):
calls.append(module)
return "before\none\ntarget\nafter\n"

result = get_lines_from_file(
str(filename), 2, loader=Loader(), module="fallback_module"
)

assert result == (["before", "one"], "target", ["after"])
assert calls == ["fallback_module"]


def test_get_lines_from_file_without_source(tmp_path):
result = get_lines_from_file(str(tmp_path / "missing.py"), 0)

assert result == ([], None, [])


@pytest.mark.parametrize(
"options,expected_context_lines",
[
Expand Down