[3.12] gh-131277: allow EnvironmentVarGuard to unset more than one environment variable at once (GH-131280) (#131410)

(cherry picked from commit 3185e3115c)

---------

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
This commit is contained in:
Bénédikt Tran 2025-03-18 13:46:24 +01:00 committed by GitHub
parent 38ef8d78bb
commit 865bd6de99
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 25 additions and 32 deletions

View file

@ -676,9 +676,10 @@ else:
class EnvironmentVarGuard(collections.abc.MutableMapping):
"""Class to help protect the environment variable properly.
"""Class to help protect the environment variable properly. Can be used as
a context manager."""
Can be used as a context manager.
"""
def __init__(self):
self._environ = os.environ
@ -712,8 +713,10 @@ class EnvironmentVarGuard(collections.abc.MutableMapping):
def set(self, envvar, value):
self[envvar] = value
def unset(self, envvar):
del self[envvar]
def unset(self, envvar, /, *envvars):
"""Unset one or more environment variables."""
for ev in (envvar, *envvars):
del self[ev]
def copy(self):
# We do what os.environ.copy() does.

View file

@ -20,12 +20,13 @@ class Test_OSXSupport(unittest.TestCase):
self.prog_name = 'bogus_program_xxxx'
self.temp_path_dir = os.path.abspath(os.getcwd())
self.env = self.enterContext(os_helper.EnvironmentVarGuard())
for cv in ('CFLAGS', 'LDFLAGS', 'CPPFLAGS',
self.env.unset(
'CFLAGS', 'LDFLAGS', 'CPPFLAGS',
'BASECFLAGS', 'BLDSHARED', 'LDSHARED', 'CC',
'CXX', 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS',
'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS'):
if cv in self.env:
self.env.unset(cv)
'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS'
)
def add_expected_saved_initial_values(self, config_vars, expected_vars):
# Ensure that the initial values for all modified config vars

View file

@ -13,7 +13,6 @@ sentinel = object()
class GetoptTests(unittest.TestCase):
def setUp(self):
self.env = self.enterContext(EnvironmentVarGuard())
if "POSIXLY_CORRECT" in self.env:
del self.env["POSIXLY_CORRECT"]
def assertError(self, *args, **kwargs):

View file

@ -3111,7 +3111,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
p7 = P(f'~{fakename}/Documents')
with os_helper.EnvironmentVarGuard() as env:
env.pop('HOME', None)
env.unset('HOME')
self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
@ -3222,10 +3222,7 @@ class WindowsPathTest(_BasePathTest, unittest.TestCase):
def test_expanduser(self):
P = self.cls
with os_helper.EnvironmentVarGuard() as env:
env.pop('HOME', None)
env.pop('USERPROFILE', None)
env.pop('HOMEPATH', None)
env.pop('HOMEDRIVE', None)
env.unset('HOME', 'USERPROFILE', 'HOMEPATH', 'HOMEDRIVE')
env['USERNAME'] = 'alice'
# test that the path returns unchanged
@ -3263,8 +3260,7 @@ class WindowsPathTest(_BasePathTest, unittest.TestCase):
env['HOMEPATH'] = 'Users\\alice'
check()
env.pop('HOMEDRIVE', None)
env.pop('HOMEPATH', None)
env.unset('HOMEDRIVE', 'HOMEPATH')
env['USERPROFILE'] = 'C:\\Users\\alice'
check()

View file

@ -304,7 +304,6 @@ class PlatformTest(unittest.TestCase):
with support.swap_attr(platform, '_wmi_query', raises_oserror):
with os_helper.EnvironmentVarGuard() as environ:
try:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None

View file

@ -409,7 +409,6 @@ class ParseArgsTestCase(unittest.TestCase):
# which has an unclear API
with os_helper.EnvironmentVarGuard() as env:
# Ignore SOURCE_DATE_EPOCH env var if it's set
if 'SOURCE_DATE_EPOCH' in env:
del env['SOURCE_DATE_EPOCH']
regrtest = main.Regrtest(ns)

View file

@ -2377,7 +2377,7 @@ class TestWhich(BaseTest, unittest.TestCase):
def test_environ_path_missing(self):
with os_helper.EnvironmentVarGuard() as env:
env.pop('PATH', None)
del env['PATH']
# without confstr
with unittest.mock.patch('os.confstr', side_effect=ValueError, \
@ -2403,7 +2403,7 @@ class TestWhich(BaseTest, unittest.TestCase):
def test_empty_path_no_PATH(self):
with os_helper.EnvironmentVarGuard() as env:
env.pop('PATH', None)
del env['PATH']
rv = shutil.which(self.file)
self.assertIsNone(rv)
@ -3335,8 +3335,7 @@ class TestGetTerminalSize(unittest.TestCase):
expected = (int(size[1]), int(size[0])) # reversed order
with os_helper.EnvironmentVarGuard() as env:
del env['LINES']
del env['COLUMNS']
env.unset('LINES', 'COLUMNS')
actual = shutil.get_terminal_size()
self.assertEqual(expected, actual)
@ -3344,8 +3343,7 @@ class TestGetTerminalSize(unittest.TestCase):
@unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
def test_fallback(self):
with os_helper.EnvironmentVarGuard() as env:
del env['LINES']
del env['COLUMNS']
env.unset('LINES', 'COLUMNS')
# sys.__stdout__ has no fileno()
with support.swap_attr(sys, '__stdout__', None):

View file

@ -354,9 +354,7 @@ class HelperFunctionsTests(unittest.TestCase):
with EnvironmentVarGuard() as environ, \
mock.patch('os.path.expanduser', lambda path: path):
del environ['PYTHONUSERBASE']
del environ['APPDATA']
environ.unset('PYTHONUSERBASE', 'APPDATA')
user_base = site.getuserbase()
self.assertTrue(user_base.startswith('~' + os.sep),