gh-116307: Proper fix for 'mod' leaking across importlib tests (GH-116680)
(cherry picked from commit
a2548077614f81f25a2c3465dabb7a0a3885c40c)
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.
Co-authored-by: Jason R. Coombs <jaraco@jaraco.com>
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
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):
--- /dev/null
+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.