]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-131277: allow `EnvironmentVarGuard` to unset more than one environment variable...
authorBénédikt Tran <10796600+picnixz@users.noreply.github.com>
Sun, 16 Mar 2025 13:09:33 +0000 (14:09 +0100)
committerGitHub <noreply@github.com>
Sun, 16 Mar 2025 13:09:33 +0000 (14:09 +0100)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
15 files changed:
Doc/library/test.rst
Lib/test/support/__init__.py
Lib/test/support/os_helper.py
Lib/test/test__colorize.py
Lib/test/test__osx_support.py
Lib/test/test_builtin.py
Lib/test/test_getopt.py
Lib/test/test_io.py
Lib/test/test_locale.py
Lib/test/test_pathlib/test_pathlib.py
Lib/test/test_platform.py
Lib/test/test_regrtest.py
Lib/test/test_shutil.py
Lib/test/test_site.py
Misc/NEWS.d/next/Tests/2025-03-15-12-44-54.gh-issue-131277.JaMlVa.rst [new file with mode: 0644]

index def22f8bb8ab2d95aa67725727a4a860ae188de7..46f8975687714b8b84561f979db93d175ebbec11 100644 (file)
@@ -1435,9 +1435,12 @@ The :mod:`test.support.os_helper` module provides support for os tests.
    ``value``.
 
 
-.. method:: EnvironmentVarGuard.unset(envvar)
+.. method:: EnvironmentVarGuard.unset(envvar, *others)
 
-   Temporarily unset the environment variable ``envvar``.
+   Temporarily unset one or more environment variables.
+
+   .. versionchanged:: next
+      More than one environment variable can be unset.
 
 
 .. function:: can_symlink()
index b9ccf7bb4c67de9defb0fc4ee167fe52cc3512eb..b35ce1b22851715ccad7db4d9a71389493cfbcf2 100644 (file)
@@ -2855,8 +2855,7 @@ def no_color():
         swap_attr(_colorize, "can_colorize", lambda file=None: False),
         EnvironmentVarGuard() as env,
     ):
-        for var in {"FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS"}:
-            env.unset(var)
+        env.unset("FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS")
         env.set("NO_COLOR", "1")
         yield
 
index 15dcdc9b1fddfb754db583b772d59fc74154d715..4e39b5a835aac841b595553faa4c408ffb48e897 100644 (file)
@@ -720,9 +720,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
@@ -756,8 +757,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.
index 42ee7b50a2a3ef58d6985ce8153799da14e2883c..b2f0bb1386fe5b486368119c3437f9900fdbda76 100644 (file)
@@ -10,8 +10,7 @@ from test.support.os_helper import EnvironmentVarGuard
 @contextlib.contextmanager
 def clear_env():
     with EnvironmentVarGuard() as mock_env:
-        for var in "FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS", "TERM":
-            mock_env.unset(var)
+        mock_env.unset("FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS", "TERM")
         yield mock_env
 
 
index 4a14cb352138efe10244ca68e2a994bb848e3d6b..53aa26620a6475ec01f865682b3b573b92aadc40 100644 (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',
-                            '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)
+
+        self.env.unset(
+            'CFLAGS', 'LDFLAGS', 'CPPFLAGS',
+            'BASECFLAGS', 'BLDSHARED', 'LDSHARED', 'CC',
+            'CXX', 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS',
+            '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
index a0bb6855c8fa3c2511501befb6c1909b03823d8a..90998ffce6d4e112c9a854fab06e7b3e2f2c49e7 100644 (file)
@@ -1568,8 +1568,7 @@ class BuiltinTest(ComplexesAreIdenticalMixin, unittest.TestCase):
             # try to get a user preferred encoding different than the current
             # locale encoding to check that open() uses the current locale
             # encoding and not the user preferred encoding
-            for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
-                env.unset(key)
+            env.unset('LC_ALL', 'LANG', 'LC_CTYPE')
 
             self.write_testfile()
             current_locale_encoding = locale.getencoding()
index ed967ad27619ae349a161d7a547530e684286070..8d0d5084abbb597fbaf636e8f9188a6668ec090b 100644 (file)
@@ -13,8 +13,7 @@ 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"]
+        del self.env["POSIXLY_CORRECT"]
 
     def assertError(self, *args, **kwargs):
         self.assertRaises(getopt.GetoptError, *args, **kwargs)
index 23eb3b32b512f7bd970c88d7dc453ab2dd1c28af..455a87b9ab09019082447c3689a8722ecf15fd55 100644 (file)
@@ -2896,8 +2896,7 @@ class TextIOWrapperTest(unittest.TestCase):
             # try to get a user preferred encoding different than the current
             # locale encoding to check that TextIOWrapper() uses the current
             # locale encoding and not the user preferred encoding
-            for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
-                env.unset(key)
+            env.unset('LC_ALL', 'LANG', 'LC_CTYPE')
 
             current_locale_encoding = locale.getencoding()
             b = self.BytesIO()
index dc1ba258e0b81b7dd237eab82c8ae27203859856..798c6ad62cddd167c7a2dd4ac0e52698ee137ddc 100644 (file)
@@ -500,9 +500,7 @@ class TestMiscellaneous(unittest.TestCase):
 
         try:
             with os_helper.EnvironmentVarGuard() as env:
-                for key in ('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE'):
-                    env.unset(key)
-
+                env.unset('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')
                 env.set('LC_CTYPE', 'UTF-8')
 
                 with check_warnings(('', DeprecationWarning)):
index 36fb62e53e14ed0a150726e06f403b655a90e5de..bda94f51968cb271715f9cd8b19b2184cc927ad3 100644 (file)
@@ -3232,7 +3232,7 @@ class PathTest(PurePathTest):
         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')
@@ -3345,10 +3345,7 @@ class PathTest(PurePathTest):
     def test_expanduser_windows(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
@@ -3386,8 +3383,7 @@ class PathTest(PurePathTest):
             env['HOMEPATH'] = 'Users\\alice'
             check()
 
-            env.pop('HOMEDRIVE', None)
-            env.pop('HOMEPATH', None)
+            env.unset('HOMEDRIVE', 'HOMEPATH')
             env['USERPROFILE'] = 'C:\\Users\\alice'
             check()
 
index e04ad142061ad30e9129f6374c3718a6a47ceb04..ca73b043d31b7fec208c41cda60d2f69d0d00538 100644 (file)
@@ -368,8 +368,7 @@ 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']
+                    del environ['PROCESSOR_ARCHITEW6432']
                     environ['PROCESSOR_ARCHITECTURE'] = 'foo'
                     platform._uname_cache = None
                     system, node, release, version, machine, processor = platform.uname()
index 38a0d3f6779786509f4e09d158407eef48443eb1..510c8f69631bacdf56681deff0653eff0ce9f331 100644 (file)
@@ -422,8 +422,7 @@ 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']
+            del env['SOURCE_DATE_EPOCH']
 
             regrtest = main.Regrtest(ns)
 
index 86bdc302ea76fda80aea59719f9443008da9adc3..ed01163074a507c32aa60a4031230be3f29c4633 100644 (file)
@@ -2458,7 +2458,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, \
@@ -2484,7 +2484,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)
 
@@ -3446,8 +3446,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)
@@ -3455,8 +3454,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):
index 035913cdd05f3432827350374b84f46b7cb827cb..16cf25798a73a32901906d22e2697e9955d05b53 100644 (file)
@@ -355,9 +355,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),
diff --git a/Misc/NEWS.d/next/Tests/2025-03-15-12-44-54.gh-issue-131277.JaMlVa.rst b/Misc/NEWS.d/next/Tests/2025-03-15-12-44-54.gh-issue-131277.JaMlVa.rst
new file mode 100644 (file)
index 0000000..0ea2423
--- /dev/null
@@ -0,0 +1,3 @@
+Allow to unset one or more environment variables at once via
+:meth:`EnvironmentVarGuard.unset()
+<test.support.os_helper.EnvironmentVarGuard.unset>`. Patch by Bénédikt Tran.