Skip to content

Commit 05d12ee

Browse files
authored
gh-127873: Only check sys.flags.ignore_environment for PYTHON* env vars (#127877)
1 parent 13475e0 commit 05d12ee

22 files changed

+94
-65
lines changed

.github/CODEOWNERS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,7 @@ Lib/test/test_configparser.py @jaraco
304304
Doc/reference/ @willingc @AA-Turner
305305

306306
**/*weakref* @kumaraditya303
307+
308+
# Colorize
309+
Lib/_colorize.py @hugovk
310+
Lib/test/test__colorize.py @hugovk

Lib/_colorize.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,14 @@ def can_colorize(*, file=None) -> bool:
4242
return False
4343
if os.environ.get("PYTHON_COLORS") == "1":
4444
return True
45-
if "NO_COLOR" in os.environ:
46-
return False
45+
if "NO_COLOR" in os.environ:
46+
return False
4747
if not COLORIZE:
4848
return False
49-
if not sys.flags.ignore_environment:
50-
if "FORCE_COLOR" in os.environ:
51-
return True
52-
if os.environ.get("TERM") == "dumb":
53-
return False
49+
if "FORCE_COLOR" in os.environ:
50+
return True
51+
if os.environ.get("TERM") == "dumb":
52+
return False
5453

5554
if not hasattr(file, "fileno"):
5655
return False

Lib/test/support/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"without_optimizer",
6262
"force_not_colorized",
6363
"force_not_colorized_test_class",
64+
"make_clean_env",
6465
"BrokenIter",
6566
"in_systemd_nspawn_sync_suppressed",
6667
"run_no_yield_async_fn", "run_yielding_async_fn", "async_yield",
@@ -2871,6 +2872,16 @@ def new_setUpClass(cls):
28712872
return cls
28722873

28732874

2875+
def make_clean_env() -> dict[str, str]:
2876+
clean_env = os.environ.copy()
2877+
for k in clean_env.copy():
2878+
if k.startswith("PYTHON"):
2879+
clean_env.pop(k)
2880+
clean_env.pop("FORCE_COLOR", None)
2881+
clean_env.pop("NO_COLOR", None)
2882+
return clean_env
2883+
2884+
28742885
def initialized_with_pyrepl():
28752886
"""Detect whether PyREPL was used during Python initialization."""
28762887
# If the main module has a __file__ attribute it's a Python module, which means PyREPL.

Lib/test/test__colorize.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import unittest
44
import unittest.mock
55
import _colorize
6-
from test.support import force_not_colorized
6+
from test.support import force_not_colorized, make_clean_env
77

88
ORIGINAL_CAN_COLORIZE = _colorize.can_colorize
99

@@ -17,6 +17,14 @@ def tearDownModule():
1717

1818

1919
class TestColorizeFunction(unittest.TestCase):
20+
def setUp(self):
21+
# Remove PYTHON* environment variables to isolate from local user
22+
# settings and simulate running with `-E`. Such variables should be
23+
# added to test methods later to patched os.environ.
24+
patcher = unittest.mock.patch("os.environ", new=make_clean_env())
25+
self.addCleanup(patcher.stop)
26+
patcher.start()
27+
2028
@force_not_colorized
2129
def test_colorized_detection_checks_for_environment_variables(self):
2230
flags = unittest.mock.MagicMock(ignore_environment=False)

Lib/test/test_capi/test_misc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,11 @@ class InstanceMethod:
7575
id = _testcapi.instancemethod(id)
7676
testfunction = _testcapi.instancemethod(testfunction)
7777

78+
7879
CURRENT_THREAD_REGEX = r'Current thread.*:\n' if not support.Py_GIL_DISABLED else r'Stack .*:\n'
7980

81+
82+
@support.force_not_colorized_test_class
8083
class CAPITest(unittest.TestCase):
8184

8285
def test_instancemethod(self):

Lib/test/test_cmd_line_script.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
8888
importlib.invalidate_caches()
8989
return to_return
9090

91+
92+
@support.force_not_colorized_test_class
9193
class CmdLineTest(unittest.TestCase):
9294
def _check_output(self, script_name, exit_code, data,
9395
expected_file, expected_argv0,

Lib/test/test_compileall.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,7 @@ def test_d_compile_error(self):
766766
rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
767767
self.assertRegex(out, b'File "dinsdale')
768768

769+
@support.force_not_colorized
769770
def test_d_runtime_error(self):
770771
bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
771772
self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)

Lib/test/test_eof.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import sys
44
from codecs import BOM_UTF8
5-
from test import support
5+
from test.support import force_not_colorized
66
from test.support import os_helper
77
from test.support import script_helper
88
from test.support import warnings_helper
@@ -44,6 +44,7 @@ def test_EOFS(self):
4444
self.assertEqual(cm.exception.text, "ä = '''thîs is ")
4545
self.assertEqual(cm.exception.offset, 5)
4646

47+
@force_not_colorized
4748
def test_EOFS_with_file(self):
4849
expect = ("(<string>, line 1)")
4950
with os_helper.temp_dir() as temp_dir:
@@ -123,6 +124,7 @@ def test_line_continuation_EOF(self):
123124
self.assertEqual(str(cm.exception), expect)
124125

125126
@unittest.skipIf(not sys.executable, "sys.executable required")
127+
@force_not_colorized
126128
def test_line_continuation_EOF_from_file_bpo2180(self):
127129
"""Ensure tok_nextc() does not add too many ending newlines."""
128130
with os_helper.temp_dir() as temp_dir:

Lib/test/test_exceptions.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,6 +1465,7 @@ def gen():
14651465

14661466
@cpython_only
14671467
@unittest.skipIf(_testcapi is None, "requires _testcapi")
1468+
@force_not_colorized
14681469
def test_recursion_normalizing_infinite_exception(self):
14691470
# Issue #30697. Test that a RecursionError is raised when
14701471
# maximum recursion depth has been exceeded when creating
@@ -2180,6 +2181,7 @@ def test_multiline_not_highlighted(self):
21802181
self.assertEqual(result[-len(expected):], expected)
21812182

21822183

2184+
@support.force_not_colorized_test_class
21832185
class SyntaxErrorTests(unittest.TestCase):
21842186
maxDiff = None
21852187

Lib/test/test_import/__init__.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,21 @@
2929

3030
from test.support import os_helper
3131
from test.support import (
32-
STDLIB_DIR, swap_attr, swap_item, cpython_only, is_apple_mobile, is_emscripten,
33-
is_wasi, run_in_subinterp, run_in_subinterp_with_config, Py_TRACE_REFS,
34-
requires_gil_enabled, Py_GIL_DISABLED, no_rerun)
32+
STDLIB_DIR,
33+
swap_attr,
34+
swap_item,
35+
cpython_only,
36+
is_apple_mobile,
37+
is_emscripten,
38+
is_wasi,
39+
run_in_subinterp,
40+
run_in_subinterp_with_config,
41+
Py_TRACE_REFS,
42+
requires_gil_enabled,
43+
Py_GIL_DISABLED,
44+
no_rerun,
45+
force_not_colorized_test_class,
46+
)
3547
from test.support.import_helper import (
3648
forget, make_legacy_pyc, unlink, unload, ready_to_import,
3749
DirsOnSysPath, CleanImport, import_module)
@@ -333,6 +345,7 @@ def _from_subinterp(cls, name, interpid, pipe, script_kwargs):
333345
return cls.parse(text.decode())
334346

335347

348+
@force_not_colorized_test_class
336349
class ImportTests(unittest.TestCase):
337350

338351
def setUp(self):

0 commit comments

Comments
 (0)