mirror of
https://github.com/python/cpython.git
synced 2025-08-30 21:48:47 +00:00
gh-109625: Move _ready_to_import() from test_import to support.import_helper (#109626)
This commit is contained in:
parent
712cb173f8
commit
115c49ad5a
3 changed files with 35 additions and 34 deletions
|
@ -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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue