Skip to content

Commit 67af623

Browse files
authored
Merge pull request #8227 from encukou/defensive-get_source
Make code.FormattedExcinfo.get_source more defensive
2 parents aead41e + 0a75c8e commit 67af623

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
@@ -734,11 +734,11 @@ def get_source(
734734
) -> List[str]:
735735
"""Return formatted and marked up source lines."""
736736
lines = []
737-
if source is None or line_index >= len(source.lines):
737+
if source is not None and line_index < 0:
738+
line_index += len(source.lines)
739+
if source is None or line_index >= len(source.lines) or line_index < 0:
738740
source = Source("???")
739741
line_index = 0
740-
if line_index < 0:
741-
line_index += len(source)
742742
space_prefix = " "
743743
if short:
744744
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
@@ -1397,6 +1397,29 @@ def test(tmp_path):
13971397
result.stderr.no_fnmatch_line("*INTERNALERROR*")
13981398

13991399

1400+
def test_regression_nagative_line_index(pytester: Pytester) -> None:
1401+
"""
1402+
With Python 3.10 alphas, there was an INTERNALERROR reported in
1403+
https://github.com/pytest-dev/pytest/pull/8227
1404+
This test ensures it does not regress.
1405+
"""
1406+
pytester.makepyfile(
1407+
"""
1408+
import ast
1409+
import pytest
1410+
1411+
1412+
def test_literal_eval():
1413+
with pytest.raises(ValueError, match="^$"):
1414+
ast.literal_eval("pytest")
1415+
"""
1416+
)
1417+
result = pytester.runpytest()
1418+
result.stdout.fnmatch_lines(["* 1 failed in *"])
1419+
result.stdout.no_fnmatch_line("*INTERNALERROR*")
1420+
result.stderr.no_fnmatch_line("*INTERNALERROR*")
1421+
1422+
14001423
@pytest.mark.usefixtures("limited_recursion_depth")
14011424
def test_exception_repr_extraction_error_on_recursion():
14021425
"""

0 commit comments

Comments
 (0)