Skip to content

Commit dd7c94b

Browse files
Anthony Sottilemgorny
authored andcommitted
Merge pull request pytest-dev#8227 from encukou/defensive-get_source
Make code.FormattedExcinfo.get_source more defensive (cherry picked from commit 67af623) (Michał Górny: removed type hints for 6.2.x)
1 parent 15a4538 commit dd7c94b

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/_pytest/_code/code.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -717,11 +717,11 @@ def get_source(
717717
) -> List[str]:
718718
"""Return formatted and marked up source lines."""
719719
lines = []
720-
if source is None or line_index >= len(source.lines):
720+
if source is not None and line_index < 0:
721+
line_index += len(source.lines)
722+
if source is None or line_index >= len(source.lines) or line_index < 0:
721723
source = Source("???")
722724
line_index = 0
723-
if line_index < 0:
724-
line_index += len(source)
725725
space_prefix = " "
726726
if short:
727727
lines.append(space_prefix + source.lines[line_index].strip())

testing/code/test_excinfo.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,6 +1389,29 @@ def test(tmpdir):
13891389
result.stderr.no_fnmatch_line("*INTERNALERROR*")
13901390

13911391

1392+
def test_regression_nagative_line_index(pytester):
1393+
"""
1394+
With Python 3.10 alphas, there was an INTERNALERROR reported in
1395+
https://github.com/pytest-dev/pytest/pull/8227
1396+
This test ensures it does not regress.
1397+
"""
1398+
pytester.makepyfile(
1399+
"""
1400+
import ast
1401+
import pytest
1402+
1403+
1404+
def test_literal_eval():
1405+
with pytest.raises(ValueError, match="^$"):
1406+
ast.literal_eval("pytest")
1407+
"""
1408+
)
1409+
result = pytester.runpytest()
1410+
result.stdout.fnmatch_lines(["* 1 failed in *"])
1411+
result.stdout.no_fnmatch_line("*INTERNALERROR*")
1412+
result.stderr.no_fnmatch_line("*INTERNALERROR*")
1413+
1414+
13921415
@pytest.mark.usefixtures("limited_recursion_depth")
13931416
def test_exception_repr_extraction_error_on_recursion():
13941417
"""

0 commit comments

Comments
 (0)