Skip to content
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

terminalwriter: fix crash trying to highlight empty source #11760

Merged
merged 1 commit into from
Jan 3, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog/11758.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed ``IndexError: string index out of range`` crash in ``if highlighted[-1] == "\n" and source[-1] != "\n"``.
This bug was introduced in pytest 8.0.0rc1.
3 changes: 2 additions & 1 deletion src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,9 @@ def _highlight(
"""Highlight the given source if we have markup support."""
from _pytest.config.exceptions import UsageError

if not self.hasmarkup or not self.code_highlight:
if not source or not self.hasmarkup or not self.code_highlight:
return source

try:
from pygments.formatters.terminal import TerminalFormatter

Expand Down
14 changes: 14 additions & 0 deletions testing/io/test_terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,3 +306,17 @@ def test_code_highlight(has_markup, code_highlight, expected, color_mapping):
match=re.escape("indents size (2) should have same size as lines (1)"),
):
tw._write_source(["assert 0"], [" ", " "])


def test_highlight_empty_source() -> None:
"""Don't crash trying to highlight empty source code.

Issue #11758.
"""
f = io.StringIO()
tw = terminalwriter.TerminalWriter(f)
tw.hasmarkup = True
tw.code_highlight = True
tw._write_source([])

assert f.getvalue() == ""