Temporarily create each named module with an attribute (named 'attr') that contains the name passed into the context manager that caused the creation of the module. All files are created in a temporary directory returned by tempfile.mkdtemp(). This directory is inserted at the begin
(*names)
| 332 | |
| 333 | @contextlib.contextmanager |
| 334 | def create_modules(*names): |
| 335 | """Temporarily create each named module with an attribute (named 'attr') |
| 336 | that contains the name passed into the context manager that caused the |
| 337 | creation of the module. |
| 338 | |
| 339 | All files are created in a temporary directory returned by |
| 340 | tempfile.mkdtemp(). This directory is inserted at the beginning of |
| 341 | sys.path. When the context manager exits all created files (source and |
| 342 | bytecode) are explicitly deleted. |
| 343 | |
| 344 | No magic is performed when creating packages! This means that if you create |
| 345 | a module within a package you must also create the package's __init__ as |
| 346 | well. |
| 347 | |
| 348 | """ |
| 349 | source = 'attr = {0!r}' |
| 350 | created_paths = [] |
| 351 | mapping = {} |
| 352 | state_manager = None |
| 353 | uncache_manager = None |
| 354 | try: |
| 355 | temp_dir = tempfile.mkdtemp() |
| 356 | mapping['.root'] = temp_dir |
| 357 | import_names = set() |
| 358 | for name in names: |
| 359 | if not name.endswith('__init__'): |
| 360 | import_name = name |
| 361 | else: |
| 362 | import_name = name[:-len('.__init__')] |
| 363 | import_names.add(import_name) |
| 364 | if import_name in sys.modules: |
| 365 | del sys.modules[import_name] |
| 366 | name_parts = name.split('.') |
| 367 | file_path = temp_dir |
| 368 | for directory in name_parts[:-1]: |
| 369 | file_path = os.path.join(file_path, directory) |
| 370 | if not os.path.exists(file_path): |
| 371 | os.mkdir(file_path) |
| 372 | created_paths.append(file_path) |
| 373 | file_path = os.path.join(file_path, name_parts[-1] + '.py') |
| 374 | with open(file_path, 'w', encoding='utf-8') as file: |
| 375 | file.write(source.format(name)) |
| 376 | created_paths.append(file_path) |
| 377 | mapping[name] = file_path |
| 378 | uncache_manager = uncache(*import_names) |
| 379 | uncache_manager.__enter__() |
| 380 | state_manager = import_state(path=[temp_dir]) |
| 381 | state_manager.__enter__() |
| 382 | yield mapping |
| 383 | finally: |
| 384 | if state_manager is not None: |
| 385 | state_manager.__exit__(None, None, None) |
| 386 | if uncache_manager is not None: |
| 387 | uncache_manager.__exit__(None, None, None) |
| 388 | os_helper.rmtree(temp_dir) |
| 389 | |
| 390 | |
| 391 | def mock_path_hook(*entries, importer): |
nothing calls this directly
no test coverage detected
searching dependent graphs…