|
8 | 8 | import unittest |
9 | 9 | import warnings |
10 | 10 |
|
11 | | -from .os_helper import unlink |
| 11 | +from .os_helper import unlink, temp_dir |
12 | 12 |
|
13 | 13 |
|
14 | 14 | @contextlib.contextmanager |
@@ -58,8 +58,8 @@ def make_legacy_pyc(source): |
58 | 58 | :return: The file system path to the legacy pyc file. |
59 | 59 | """ |
60 | 60 | pyc_file = importlib.util.cache_from_source(source) |
61 | | - up_one = os.path.dirname(os.path.abspath(source)) |
62 | | - legacy_pyc = os.path.join(up_one, source + 'c') |
| 61 | + assert source.endswith('.py') |
| 62 | + legacy_pyc = source + 'c' |
63 | 63 | shutil.move(pyc_file, legacy_pyc) |
64 | 64 | return legacy_pyc |
65 | 65 |
|
@@ -114,7 +114,7 @@ def multi_interp_extensions_check(enabled=True): |
114 | 114 | This only applies to modules that haven't been imported yet. |
115 | 115 | It overrides the PyInterpreterConfig.check_multi_interp_extensions |
116 | 116 | setting (see support.run_in_subinterp_with_config() and |
117 | | - _xxsubinterpreters.create()). |
| 117 | + _interpreters.create()). |
118 | 118 |
|
119 | 119 | Also see importlib.utils.allowing_all_extensions(). |
120 | 120 | """ |
@@ -268,9 +268,44 @@ def modules_cleanup(oldmodules): |
268 | 268 | sys.modules.update(oldmodules) |
269 | 269 |
|
270 | 270 |
|
| 271 | +@contextlib.contextmanager |
| 272 | +def isolated_modules(): |
| 273 | + """ |
| 274 | + Save modules on entry and cleanup on exit. |
| 275 | + """ |
| 276 | + (saved,) = modules_setup() |
| 277 | + try: |
| 278 | + yield |
| 279 | + finally: |
| 280 | + modules_cleanup(saved) |
| 281 | + |
| 282 | + |
271 | 283 | def mock_register_at_fork(func): |
272 | 284 | # bpo-30599: Mock os.register_at_fork() when importing the random module, |
273 | 285 | # since this function doesn't allow to unregister callbacks and would leak |
274 | 286 | # memory. |
275 | 287 | from unittest import mock |
276 | 288 | return mock.patch('os.register_at_fork', create=True)(func) |
| 289 | + |
| 290 | + |
| 291 | +@contextlib.contextmanager |
| 292 | +def ready_to_import(name=None, source=""): |
| 293 | + from test.support import script_helper |
| 294 | + |
| 295 | + # 1. Sets up a temporary directory and removes it afterwards |
| 296 | + # 2. Creates the module file |
| 297 | + # 3. Temporarily clears the module from sys.modules (if any) |
| 298 | + # 4. Reverts or removes the module when cleaning up |
| 299 | + name = name or "spam" |
| 300 | + with temp_dir() as tempdir: |
| 301 | + path = script_helper.make_script(tempdir, name, source) |
| 302 | + old_module = sys.modules.pop(name, None) |
| 303 | + try: |
| 304 | + sys.path.insert(0, tempdir) |
| 305 | + yield name, path |
| 306 | + sys.path.remove(tempdir) |
| 307 | + finally: |
| 308 | + if old_module is not None: |
| 309 | + sys.modules[name] = old_module |
| 310 | + else: |
| 311 | + sys.modules.pop(name, None) |
0 commit comments