Skip to content

Commit

Permalink
imp(terminal): replace non-color escape sequences in output
Browse files Browse the repository at this point in the history
  • Loading branch information
blueyed committed Oct 12, 2021
1 parent 06712d4 commit 5aed15d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/_pytest/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import linecache
import os
import platform
import re
import sys
import time
import warnings
Expand Down Expand Up @@ -50,6 +51,7 @@
from _pytest._code.code import _TracebackStyle

REPORT_COLLECTING_RESOLUTION = 0.5
RE_ESCAPE_NONCOLOR = re.compile(r'\x1b(?!\[[\d;]+m)')

KNOWN_TYPES = (
"failed",
Expand All @@ -65,6 +67,10 @@
_REPORTCHARS_DEFAULT = "fE"


def replace_non_color_escapes(s: str) -> str:
return RE_ESCAPE_NONCOLOR.sub('^[', s)


def _getdimensions() -> Tuple[int, int]:
# Improved version of shutil.get_terminal_size that looks at stdin,
# stderr, stdout. Ref: https://bugs.python.org/issue14841.
Expand Down Expand Up @@ -1176,6 +1182,7 @@ def _outrep_summary(self, rep):
self.section(secname, "-")
if content[-1:] == "\n":
content = content[:-1]
content = replace_non_color_escapes(content)
self._tw.line(content)

def summary_stats(self) -> None:
Expand Down
18 changes: 18 additions & 0 deletions testing/test_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from _pytest.terminal import _get_pos
from _pytest.terminal import _plugin_nameversions
from _pytest.terminal import getreportopt
from _pytest.terminal import replace_non_color_escapes
from _pytest.terminal import TerminalReporter

try:
Expand Down Expand Up @@ -361,6 +362,23 @@ def test_rewrite(self, testdir, monkeypatch):
assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ")


class TestTerminalUnit:
def test_replace_non_color_escapes(self) -> None:
f = replace_non_color_escapes

# without any escapes.
assert f("foo") == "foo"

# color escapes.
assert f('\x1b[32mINFO') == '\x1b[32mINFO'
assert f('\x1b[38;2;0;0;0m') == '\x1b[38;2;0;0;0m'

# non-color escapes.
# clears screen.
assert f('\033[2J\033[1;1H') == '^[[2J^[[1;1H'
assert f('\033') == '^['


class TestCollectonly:
def test_collectonly_basic(self, testdir):
testdir.makepyfile(
Expand Down

0 comments on commit 5aed15d

Please sign in to comment.