From aaa53d22b2f4d09fff19503c4f91992db1e7f1c0 Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Tue, 4 Apr 2023 09:18:04 -0400 Subject: [PATCH] FormattedExcinfo.get_source: Avoid a crash when source.lines == 0 pytest could crash given pathological AST position attributes, which shouldn't happen when testing real Python code, but could happen when testing AST produced by e.g. Hylang. --- changelog/10840.improvement.rst | 1 + src/_pytest/_code/code.py | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 changelog/10840.improvement.rst 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())