From 9f13d41d7bf773d9a64ff84f7c26fec7fbd431cf Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Sat, 17 Feb 2024 12:13:57 +0200 Subject: [PATCH] code: fix `IndexError` crash in `getstatementrange_ast` Fix #11953. --- changelog/11953.bugfix.rst | 1 + src/_pytest/_code/source.py | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 changelog/11953.bugfix.rst diff --git a/changelog/11953.bugfix.rst b/changelog/11953.bugfix.rst new file mode 100644 index 000000000..5aff5f7fd --- /dev/null +++ b/changelog/11953.bugfix.rst @@ -0,0 +1 @@ +Fix an ``IndexError`` crash raising from ``getstatementrange_ast``. diff --git a/src/_pytest/_code/source.py b/src/_pytest/_code/source.py index 69f580e20..dac3c3867 100644 --- a/src/_pytest/_code/source.py +++ b/src/_pytest/_code/source.py @@ -197,7 +197,9 @@ def getstatementrange_ast( # by using the BlockFinder helper used which inspect.getsource() uses itself. block_finder = inspect.BlockFinder() # If we start with an indented line, put blockfinder to "started" mode. - block_finder.started = source.lines[start][0].isspace() + block_finder.started = ( + bool(source.lines[start]) and source.lines[start][0].isspace() + ) it = ((x + "\n") for x in source.lines[start:end]) try: for tok in tokenize.generate_tokens(lambda: next(it)):