diff --git a/AUTHORS b/AUTHORS index 058236461..1aa5265e6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -163,6 +163,7 @@ Ionuț Turturică Itxaso Aizpurua Iwan Briquemont Jaap Broekhuizen +Jake VanderPlas Jakob van Santen Jakub Mitoraj James Bourbeau diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index e375fb70c..9ec926620 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -743,7 +743,7 @@ class FormattedExcinfo: ) -> 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: diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 3607501a8..918c97276 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -461,6 +461,24 @@ class TestFormattedExcinfo: 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: