| 1 |
"""Helpers for tests.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import sys |
| 7 |
from tempfile import gettempdir |
| 8 |
|
| 9 |
from griffe._internal.helpers import _TMPDIR_PREFIX |
| 10 |
|
| 11 |
|
| 12 |
def clear_sys_modules(name: str | None = None) -> None: |
| 13 |
"""Clear `sys.modules` of a module and its submodules. |
| 14 |
|
| 15 |
Use this function after having used `temporary_pypackage` and `inspect` together. |
| 16 |
Better yet, use `temporary_inspected_package` and `temporary_inspected_module` |
| 17 |
which will automatically clear `sys.modules` when exiting. |
| 18 |
|
| 19 |
Parameters: |
| 20 |
name: A top-level module name. If None, clear all temporary inspected modules |
| 21 |
(located in the OS' default temporary directory). |
| 22 |
""" |
| 23 |
if name: |
| 24 |
for module_name in tuple(sys.modules.keys()): |
| 25 |
if module_name == name or module_name.startswith(f"{name}."): |
| 26 |
sys.modules.pop(module_name, None) |
| 27 |
else: |
| 28 |
prefix = os.path.join(gettempdir(), _TMPDIR_PREFIX) |
| 29 |
for module_name, module in tuple(sys.modules.items()): |
| 30 |
if ((file := getattr(module, "__file__", "")) and file.startswith(prefix)) or ( |
| 31 |
(paths := getattr(module, "__path__", ())) and any(path.startswith(prefix) for path in paths) |
| 32 |
): |
| 33 |
sys.modules.pop(module_name, None) |