diff options
author | Nikita Sobolev <mail@sobolevn.me> | 2023-09-21 07:39:36 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-09-21 07:39:36 (GMT) |
commit | 115c49ad5a5ccfb628fef3ae06a566f7a0197f97 (patch) | |
tree | ff301179b73f6523a6bbe2ca1c0bb37cda7e3fb8 /Lib/test/support | |
parent | 712cb173f8e1d02c625a40ae03bba57b0c1c032a (diff) | |
download | cpython-115c49ad5a5ccfb628fef3ae06a566f7a0197f97.zip cpython-115c49ad5a5ccfb628fef3ae06a566f7a0197f97.tar.gz cpython-115c49ad5a5ccfb628fef3ae06a566f7a0197f97.tar.bz2 |
gh-109625: Move _ready_to_import() from test_import to support.import_helper (#109626)
Diffstat (limited to 'Lib/test/support')
-rw-r--r-- | Lib/test/support/import_helper.py | 25 |
1 files changed, 24 insertions, 1 deletions
diff --git a/Lib/test/support/import_helper.py b/Lib/test/support/import_helper.py index 67f18e5..3d804f2 100644 --- a/Lib/test/support/import_helper.py +++ b/Lib/test/support/import_helper.py @@ -8,7 +8,7 @@ import sys import unittest import warnings -from .os_helper import unlink +from .os_helper import unlink, temp_dir @contextlib.contextmanager @@ -274,3 +274,26 @@ def mock_register_at_fork(func): # memory. from unittest import mock return mock.patch('os.register_at_fork', create=True)(func) + + +@contextlib.contextmanager +def ready_to_import(name=None, source=""): + from test.support import script_helper + + # 1. Sets up a temporary directory and removes it afterwards + # 2. Creates the module file + # 3. Temporarily clears the module from sys.modules (if any) + # 4. Reverts or removes the module when cleaning up + name = name or "spam" + with temp_dir() as tempdir: + path = script_helper.make_script(tempdir, name, source) + old_module = sys.modules.pop(name, None) + try: + sys.path.insert(0, tempdir) + yield name, path + sys.path.remove(tempdir) + finally: + if old_module is not None: + sys.modules[name] = old_module + else: + sys.modules.pop(name, None) |