Spaces:
Paused
Paused
File size: 1,966 Bytes
c0e9d84 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | """Shared pytest helpers for the SarahUB suite.
Deliberately minimal: a repo-root ``sys.path`` bootstrap plus generic
``sys.modules`` namespace-isolation helpers. The plugin-load harness
(``tests/test_plugin_load.py``) uses the bootstrap; the isolation helper is
available to any future test that imports ``pyUltroid`` modules without
starting the production bootstrap (the same pattern
``tests/test_core_architecture.py`` hand-rolls today).
"""
from __future__ import annotations
import sys
from contextlib import contextmanager
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
# ``sys.path`` bootstrap: make the repo root importable no matter which
# directory pytest was invoked from.
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
@pytest.fixture(scope="session")
def repo_root() -> Path:
"""Absolute path of the repository checkout under test."""
return ROOT
@contextmanager
def isolated_sys_modules(*prefixes: str):
"""Snapshot then restore ``sys.modules`` entries matching *prefixes*.
A prefix matches itself exactly and any dotted child, so
``"pyUltroid"`` also covers ``"pyUltroid.universal.tl"``. Modules added
inside the context are removed on exit; pre-existing entries are
restored untouched. Yields the dict of saved modules.
"""
def _matches(name: str) -> bool:
return any(
name == prefix or name.startswith(prefix + ".") for prefix in prefixes
)
saved = {name: module for name, module in sys.modules.items() if _matches(name)}
for name in saved:
sys.modules.pop(name, None)
try:
yield saved
finally:
for name in list(sys.modules):
if _matches(name):
sys.modules.pop(name, None)
sys.modules.update(saved)
@pytest.fixture
def module_isolation():
"""Function-scoped accessor for :func:`isolated_sys_modules`."""
return isolated_sys_modules
|