Coverage for tests/helpers.py: 62.50%
14 statements
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
1"""Helpers for tests."""
3from __future__ import annotations
5import os
6import sys
7from tempfile import gettempdir
9from _griffe.tests import _TMPDIR_PREFIX
12def clear_sys_modules(name: str | None = None) -> None:
13 """Clear `sys.modules` of a module and its submodules.
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.
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: 23 ↛ 28line 23 didn't jump to line 28 because the condition on line 23 was always true
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) # noqa: PTH118
29 for module_name, module in tuple(sys.modules.items()):
30 if (
31 (file := getattr(module, "__file__", ""))
32 and file.startswith(prefix)
33 or (paths := getattr(module, "__path__", ()))
34 and any(path.startswith(prefix) for path in paths)
35 ):
36 sys.modules.pop(module_name, None)