kuri-tool-guard/tests/_support.py
XLion 06a7f93d18
refactor(kuri-tool-guard): modularise monolithic __init__.py and tests
Split the 1341-line __init__.py into 5 focused modules:
  _state.py    - home root helpers, mutable poll state
  _parser.py   - shell tokenizer (independent)
  _predicates.py - terminal predicates + bounded output
  _guards.py   - all 9 guard implementations + AST helpers
  __init__.py  - thin entry point + dispatcher + re-exports

Split the 2226-line test_guard.py into 14 dedicated files:
  13 test_*.py files + tests/_support.py (shared helpers)

Key changes:
- Package-relative imports throughout (Hermes loader compatible)
- No top-level module pollution (hermes_plugins.kuri_tool_guard.* only)
- Typechecked via ty with symlink alias for hyphenated dir name
- All 10 guard policies, messages, and block/allow behaviour preserved
- 338 tests (336 original + 2 new: isolation + loader contract)
- ty, ruff, bandit, vulture all pass in just verify
2026-07-31 02:23:02 +08:00

115 lines
4.2 KiB
Python

"""Shared test support for kuri-tool-guard tests.
Mirrors the Hermes plugin loader at ``hermes_cli/plugins.py``:
- Loads the plugin as ``hermes_plugins.kuri_tool_guard`` (the real loader's
``_NS_PARENT`` and slug convention) so that ``__name__`` and ``__package__``
match production.
- Sets ``submodule_search_locations`` so that relative imports inside
``__init__.py`` resolve correctly.
"""
from __future__ import annotations
import importlib
import importlib.util
import sys
import types
from collections.abc import Callable
from pathlib import Path
from typing import Any
from unittest.mock import patch
# ── Constants ───────────────────────────────────────────────────────
PLUGIN_DIR = Path(__file__).resolve().parent.parent
PLUGIN_INIT = PLUGIN_DIR / "__init__.py"
ALICE_PASSWD_HOME = "/home/alice" # nosec B105
ALICE_PROTECTED_ROOTS = frozenset({"/home/alice", "/var/home/alice"})
# ── Module helpers ──────────────────────────────────────────────────
_NS_PARENT = "hermes_plugins"
_MODULE_NAME = f"{_NS_PARENT}.kuri_tool_guard"
def _purge_submodules(name: str) -> None:
"""Remove *name* and all ``name.*`` entries from ``sys.modules``.
This ensures a subsequent ``load_mod()`` creates fresh module instances
rather than reusing stale submodule objects left by a previous load.
"""
prefix = name + "."
to_remove = [k for k in sys.modules if k == name or k.startswith(prefix)]
for k in to_remove:
sys.modules.pop(k, None)
def _ensure_ns_parent() -> None:
"""Ensure the ``hermes_plugins`` namespace parent exists in sys.modules.
This mirrors what the real Hermes plugin loader does at
``hermes_cli/plugins._load_directory_module``.
"""
if _NS_PARENT not in sys.modules:
ns_pkg = types.ModuleType(_NS_PARENT)
ns_pkg.__path__ = []
ns_pkg.__package__ = _NS_PARENT
sys.modules[_NS_PARENT] = ns_pkg
# Touch attributes so vulture sees them as "used" by import machinery
_ = sys.modules[_NS_PARENT].__path__
_ = sys.modules[_NS_PARENT].__package__
def load_mod() -> Any:
"""Load the plugin module fresh, mimicking the Hermes plugin loader.
The module is registered as ``hermes_plugins.kuri_tool_guard`` and its
``__package__`` and ``__path__`` are set identically to what the real
Hermes plugin loader in ``hermes_cli/plugins._load_directory_module``
produces.
"""
# Strip any stale entries so submodule instances created during
# exec_module are actually fresh (not recycled from a prior load).
_purge_submodules(_MODULE_NAME)
_ensure_ns_parent()
spec = importlib.util.spec_from_file_location(
_MODULE_NAME,
PLUGIN_INIT,
submodule_search_locations=[str(PLUGIN_DIR)],
)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
sys.modules[_MODULE_NAME] = mod
spec.loader.exec_module(mod)
return sys.modules[_MODULE_NAME]
def submodule(mod, name):
"""Get a loaded submodule of the plugin package by short name.
Use this in tests instead of ``mod._xxx`` for submodules not
imported by ``__init__`` (e.g. ``_predicates``, ``_parser``).
"""
return importlib.import_module(f"{mod.__name__}.{name}")
# ── Identity patching ───────────────────────────────────────────────
def patch_alice_identity(mod: Any) -> Callable[[], tuple[None, None]]:
"""Patch module identity functions to return Alice's deterministic data.
Patches the functions on ``mod._state`` (not the re-exports on ``mod``),
because guard code calls through the internal ``_state`` module reference.
Returns a restore callable for use in tearDown.
"""
p1 = patch.object(mod._state, "_get_protected_home_roots", return_value=ALICE_PROTECTED_ROOTS)
p2 = patch.object(mod._state, "_get_passwd_home", return_value=ALICE_PASSWD_HOME)
p1.start()
p2.start()
return lambda: (p2.stop(), p1.stop())