From 838151638e42578a91e947b1f3939f963b64637f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 3 Jan 2024 08:04:57 -0300 Subject: [PATCH] [8.0.x] terminalwriter: fix crash trying to highlight empty source (#11763) Co-authored-by: Ran Benita --- changelog/11758.bugfix.rst | 2 ++ src/_pytest/_io/terminalwriter.py | 3 ++- testing/io/test_terminalwriter.py | 14 ++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 changelog/11758.bugfix.rst diff --git a/changelog/11758.bugfix.rst b/changelog/11758.bugfix.rst new file mode 100644 index 000000000..af8a3f351 --- /dev/null +++ b/changelog/11758.bugfix.rst @@ -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. diff --git a/src/_pytest/_io/terminalwriter.py b/src/_pytest/_io/terminalwriter.py index bf9b76651..56107d566 100644 --- a/src/_pytest/_io/terminalwriter.py +++ b/src/_pytest/_io/terminalwriter.py @@ -200,8 +200,9 @@ class TerminalWriter: """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 diff --git a/testing/io/test_terminalwriter.py b/testing/io/test_terminalwriter.py index 96e7366e5..c7e63c672 100644 --- a/testing/io/test_terminalwriter.py +++ b/testing/io/test_terminalwriter.py @@ -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() == ""