]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-116307: Proper fix for 'mod' leaking across importlib tests (#116680)
authorJason R. Coombs <jaraco@jaraco.com>
Tue, 12 Mar 2024 21:36:21 +0000 (17:36 -0400)
committerGitHub <noreply@github.com>
Tue, 12 Mar 2024 21:36:21 +0000 (21:36 +0000)
gh-116307: Create a new import helper 'isolated modules' and use that instead of 'Clean Import' to ensure that tests from importlib_resources don't leave modules in sys.modules.

Lib/test/support/import_helper.py
Lib/test/test_importlib/resources/test_files.py
Misc/NEWS.d/next/Tests/2024-03-06-11-00-36.gh-issue-116307.Uij0t_.rst [new file with mode: 0644]

index 3d804f2b590108ac0a76cd40bd504b50f85dd8ab..29c6f535b40342539adf229d66aceeeee45d1c98 100644 (file)
@@ -268,6 +268,18 @@ def modules_cleanup(oldmodules):
     sys.modules.update(oldmodules)
 
 
+@contextlib.contextmanager
+def isolated_modules():
+    """
+    Save modules on entry and cleanup on exit.
+    """
+    (saved,) = modules_setup()
+    try:
+        yield
+    finally:
+        modules_cleanup(saved)
+
+
 def mock_register_at_fork(func):
     # bpo-30599: Mock os.register_at_fork() when importing the random module,
     # since this function doesn't allow to unregister callbacks and would leak
index 1450cfb310926aa3f3497afbdb4762abc058ea60..26c8b04e44c3b9b3ef34116419ff4c3ea59d6c00 100644 (file)
@@ -70,7 +70,7 @@ class SiteDir:
         self.addCleanup(self.fixtures.close)
         self.site_dir = self.fixtures.enter_context(os_helper.temp_dir())
         self.fixtures.enter_context(import_helper.DirsOnSysPath(self.site_dir))
-        self.fixtures.enter_context(import_helper.CleanImport())
+        self.fixtures.enter_context(import_helper.isolated_modules())
 
 
 class ModulesFilesTests(SiteDir, unittest.TestCase):
diff --git a/Misc/NEWS.d/next/Tests/2024-03-06-11-00-36.gh-issue-116307.Uij0t_.rst b/Misc/NEWS.d/next/Tests/2024-03-06-11-00-36.gh-issue-116307.Uij0t_.rst
new file mode 100644 (file)
index 0000000..0bc4be9
--- /dev/null
@@ -0,0 +1,3 @@
+Added import helper ``isolated_modules`` as ``CleanImport`` does not remove
+modules imported during the context. Use it in importlib.resources tests to
+avoid leaving ``mod`` around to impede importlib.metadata tests.