diff --git a/changelog/10840.improvement.rst b/changelog/10840.improvement.rst new file mode 100644 index 000000000..485f46cec --- /dev/null +++ b/changelog/10840.improvement.rst @@ -0,0 +1 @@ +pytest should no longer crash on AST with pathological position attributes. diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index e375fb70c..032b83beb 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -743,11 +743,13 @@ 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 not None and line_index < 0: + line_index += len(source) + if source is None or line_index >= len(source.lines) or line_index < 0: + # `line_index` could still be outside `range(len(source.lines))` if + # we're processing AST with pathological position attributes. 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())