Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fail gracefully when line number is out-of-bounds and negative #10868

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ Ionuț Turturică
Itxaso Aizpurua
Iwan Briquemont
Jaap Broekhuizen
Jake VanderPlas
Jakob van Santen
Jakub Mitoraj
James Bourbeau
Expand Down
6 changes: 5 additions & 1 deletion src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,11 @@ def get_source(
) -> List[str]:
"""Return formatted and marked up source lines."""
lines = []
if source is None or line_index >= len(source.lines):
if (
source is None
or line_index >= len(source.lines)
or line_index < -len(source.lines)
):
source = Source("???")
line_index = 0
if line_index < 0:
Expand Down
18 changes: 18 additions & 0 deletions testing/code/test_excinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,24 @@ def f(x):
assert lines[0] == "| def f(x):"
assert lines[1] == " pass"

def test_repr_source_out_of_bounds(self):
pr = FormattedExcinfo()
source = _pytest._code.Source(
"""\
def f(x):
pass
"""
).strip()
pr.flow_marker = "|" # type: ignore[misc]

lines = pr.get_source(source, 100)
assert len(lines) == 1
assert lines[0] == "| ???"

lines = pr.get_source(source, -100)
assert len(lines) == 1
assert lines[0] == "| ???"

def test_repr_source_excinfo(self) -> None:
"""Check if indentation is right."""
try:
Expand Down