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

imp(terminal): replace non-color escape sequences in output #509

Open
wants to merge 1 commit into
base: my-master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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