Skip to content

Commit 8381516

Browse files
[8.0.x] terminalwriter: fix crash trying to highlight empty source (#11763)
Co-authored-by: Ran Benita <[email protected]>
1 parent 665e4e5 commit 8381516

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

changelog/11758.bugfix.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed ``IndexError: string index out of range`` crash in ``if highlighted[-1] == "\n" and source[-1] != "\n"``.
2+
This bug was introduced in pytest 8.0.0rc1.

src/_pytest/_io/terminalwriter.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,9 @@ def _highlight(
200200
"""Highlight the given source if we have markup support."""
201201
from _pytest.config.exceptions import UsageError
202202

203-
if not self.hasmarkup or not self.code_highlight:
203+
if not source or not self.hasmarkup or not self.code_highlight:
204204
return source
205+
205206
try:
206207
from pygments.formatters.terminal import TerminalFormatter
207208

testing/io/test_terminalwriter.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,17 @@ def test_code_highlight(has_markup, code_highlight, expected, color_mapping):
306306
match=re.escape("indents size (2) should have same size as lines (1)"),
307307
):
308308
tw._write_source(["assert 0"], [" ", " "])
309+
310+
311+
def test_highlight_empty_source() -> None:
312+
"""Don't crash trying to highlight empty source code.
313+
314+
Issue #11758.
315+
"""
316+
f = io.StringIO()
317+
tw = terminalwriter.TerminalWriter(f)
318+
tw.hasmarkup = True
319+
tw.code_highlight = True
320+
tw._write_source([])
321+
322+
assert f.getvalue() == ""

0 commit comments

Comments
 (0)