Skip to content

Commit 21a259e

Browse files
authored
[3.11] gh-116307: Proper fix for 'mod' leaking across importlib tests… (#116694)
[3.11] gh-116307: Proper fix for 'mod' leaking across importlib tests (GH-116680) (cherry picked from commit a254807) 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.
1 parent a01621a commit 21a259e

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

Lib/test/support/import_helper.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,26 @@ def modules_cleanup(oldmodules):
248248
sys.modules.update(oldmodules)
249249

250250

251+
@contextlib.contextmanager
252+
def isolated_modules():
253+
"""
254+
Save modules on entry and cleanup on exit.
255+
"""
256+
(saved,) = modules_setup()
257+
try:
258+
yield
259+
finally:
260+
modules_cleanup(saved)
261+
262+
263+
def mock_register_at_fork(func):
264+
# bpo-30599: Mock os.register_at_fork() when importing the random module,
265+
# since this function doesn't allow to unregister callbacks and would leak
266+
# memory.
267+
from unittest import mock
268+
return mock.patch('os.register_at_fork', create=True)(func)
269+
270+
251271
@contextlib.contextmanager
252272
def ready_to_import(name=None, source=""):
253273
from test.support import script_helper
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Added import helper ``isolated_modules`` as ``CleanImport`` does not remove
2+
modules imported during the context.

0 commit comments

Comments
 (0)