Skip to content

Make code.FormattedExcinfo.get_source more defensive #8227

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

Merged
merged 2 commits into from
Apr 25, 2021
Merged
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
6 changes: 3 additions & 3 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,11 +721,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 not None and line_index < 0:
line_index += len(source.lines)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is insufficient still -- for example if len(source.lines) is 4 and line_index is -900 -- you could use % but it would probably be a good idea to figure out why these are negative at all (or refuse to produce source when the number is negative)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's why there's line_index < 0 in the next condition :)
I'll try to investigate why this happens in the setuptools tests.

if source is None or line_index >= len(source.lines) or line_index < 0:
source = Source("???")
line_index = 0
if line_index < 0:
line_index += len(source)
space_prefix = " "
if short:
lines.append(space_prefix + source.lines[line_index].strip())
Expand Down
23 changes: 23 additions & 0 deletions testing/code/test_excinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,29 @@ def test(tmp_path):
result.stderr.no_fnmatch_line("*INTERNALERROR*")


def test_regression_nagative_line_index(pytester: Pytester) -> None:
"""
With Python 3.10 alphas, there was an INTERNALERROR reported in
https://github.com/pytest-dev/pytest/pull/8227
This test ensures it does not regress.
"""
pytester.makepyfile(
"""
import ast
import pytest


def test_literal_eval():
with pytest.raises(ValueError, match="^$"):
ast.literal_eval("pytest")
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 1 failed in *"])
result.stdout.no_fnmatch_line("*INTERNALERROR*")
result.stderr.no_fnmatch_line("*INTERNALERROR*")


@pytest.mark.usefixtures("limited_recursion_depth")
def test_exception_repr_extraction_error_on_recursion():
"""
Expand Down