Skip to content

Commit 4ad090d

Browse files
committed
Add test class helper to force no terminal colour
1 parent 95352dc commit 4ad090d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Lib/test/support/__init__.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
"skip_on_s390x",
6161
"without_optimizer",
6262
"force_not_colorized",
63+
"force_not_colorized_test_class",
6364
"BrokenIter",
6465
"in_systemd_nspawn_sync_suppressed",
6566
"run_no_yield_async_fn", "run_yielding_async_fn", "async_yield",
@@ -2856,6 +2857,44 @@ def wrapper(*args, **kwargs):
28562857
return wrapper
28572858

28582859

2860+
2861+
def force_not_colorized_test_class(cls):
2862+
"""Force the terminal not to be colorized."""
2863+
original_setup = cls.setUp
2864+
original_teardown = cls.tearDown
2865+
2866+
@functools.wraps(cls.setUp)
2867+
def setUp_wrapper(self, *args, **kwargs):
2868+
import _colorize
2869+
2870+
self._original_fn = _colorize.can_colorize
2871+
self._variables: dict[str, str | None] = {
2872+
"PYTHON_COLORS": None,
2873+
"FORCE_COLOR": None,
2874+
"NO_COLOR": None,
2875+
}
2876+
for key in self._variables:
2877+
self._variables[key] = os.environ.pop(key, None)
2878+
os.environ["NO_COLOR"] = "1"
2879+
_colorize.can_colorize = lambda: False
2880+
return original_setup(self, *args, **kwargs)
2881+
2882+
@functools.wraps(cls.tearDown)
2883+
def tearDown_wrapper(self, *args, **kwargs):
2884+
import _colorize
2885+
2886+
_colorize.can_colorize = self._original_fn
2887+
del os.environ["NO_COLOR"]
2888+
for key, value in self._variables.items():
2889+
if value is not None:
2890+
os.environ[key] = value
2891+
return original_teardown(self, *args, **kwargs)
2892+
2893+
cls.setUp = setUp_wrapper
2894+
cls.tearDown = tearDown_wrapper
2895+
return cls
2896+
2897+
28592898
def initialized_with_pyrepl():
28602899
"""Detect whether PyREPL was used during Python initialization."""
28612900
# If the main module has a __file__ attribute it's a Python module, which means PyREPL.

0 commit comments

Comments
 (0)