Skip to content

Commit b351248

Browse files
authored
bpo-12383: Refactor subprocess test_empty_env (#1874)
Bugfix: This test wasn't being run because it was skipping based on the presence of Py_ENABLE_SHARED rather than its value. It is always present on POSIX systems but defaults to 0. Refactoring: Move the environment variables that can be ignored into a function. Parse the list from the child process and filter out the ones to exclude in the parent before checking that the rest is empty. Feature: Adds always present environment variables to ignore when running in a Gentoo sandbox so that the test can pass there.
1 parent 9c972b5 commit b351248

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

Lib/test/test_subprocess.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -630,21 +630,29 @@ def test_env(self):
630630
# Python
631631
@unittest.skipIf(sys.platform == 'win32',
632632
'cannot test an empty env on Windows')
633-
@unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
634-
'the python library cannot be loaded '
635-
'with an empty environment')
633+
@unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
634+
'The Python shared library cannot be loaded '
635+
'with an empty environment.')
636636
def test_empty_env(self):
637+
"""Verify that env={} is as empty as possible."""
638+
639+
def is_env_var_to_ignore(var_name):
640+
"""Determine if an environment variable is under our control."""
641+
# This excludes some __CF_* and VERSIONER_* keys MacOS insists
642+
# on adding even when the environment in exec is empty.
643+
# Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
644+
return ('VERSIONER' in k or '__CF' in k or # MacOS
645+
k == 'LD_PRELOAD' or k.startswith('SANDBOX')) # Gentoo
646+
637647
with subprocess.Popen([sys.executable, "-c",
638-
'import os; '
639-
'print(list(os.environ.keys()))'],
640-
stdout=subprocess.PIPE,
641-
env={}) as p:
648+
'import os; print(list(os.environ.keys()))'],
649+
stdout=subprocess.PIPE, env={}) as p:
642650
stdout, stderr = p.communicate()
643-
self.assertIn(stdout.strip(),
644-
(b"[]",
645-
# Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
646-
# environment
647-
b"['__CF_USER_TEXT_ENCODING']"))
651+
child_env_names = eval(stdout.strip())
652+
self.assertIsInstance(child_env_names, list)
653+
child_env_names = [k for k in child_env_names
654+
if not is_env_var_to_ignore(k)]
655+
self.assertEqual(child_env_names, [])
648656

649657
def test_communicate_stdin(self):
650658
p = subprocess.Popen([sys.executable, "-c",

0 commit comments

Comments
 (0)