gh-109625: Move _ready_to_import() from test_import to support.import_helper (#109626)

This commit is contained in:
Nikita Sobolev 2023-09-21 10:39:36 +03:00 committed by GitHub
parent 712cb173f8
commit 115c49ad5a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 34 deletions

View file

@ -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)