kuri-tool-guard/tests/test_dispatcher.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

203 lines
7.6 KiB
Python

"""Tests for kuri-tool-guard — dispatcher and manifest metadata."""
from __future__ import annotations
import subprocess
import sys
import tempfile
import tomllib
import unittest
import yaml
from tests._support import PLUGIN_DIR, load_mod, patch_alice_identity, submodule
class TestDispatcher(unittest.TestCase):
"""Test the _on_pre_tool_call dispatcher."""
def setUp(self):
self.mod = load_mod()
self._restore = patch_alice_identity(self.mod)
def tearDown(self):
self._restore()
def test_unguarded_tool_passes(self):
"""Tools not in _GUARDED_TOOLS are None."""
result = self.mod._on_pre_tool_call(
tool_name="read_file",
args={"path": "/home/alice"},
)
self.assertIsNone(result)
def test_search_home_root_blocks(self):
result = self.mod._on_pre_tool_call(
tool_name="search_files",
args={"path": "~"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
def test_search_subpath_passes(self):
result = self.mod._on_pre_tool_call(
tool_name="search_files",
args={"path": "/home/alice/projects"},
)
self.assertIsNone(result)
def test_terminal_banned_blocks(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "cat /etc/hostname"},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
def test_terminal_safe_passes(self):
result = self.mod._on_pre_tool_call(
tool_name="terminal",
args={"command": "ls -la"},
)
self.assertIsNone(result)
def test_write_file_blocks_via_dispatcher(self):
with tempfile.NamedTemporaryFile(delete=True, suffix=".txt") as f:
result = self.mod._on_pre_tool_call(
tool_name="write_file",
args={"path": f.name},
)
self.assertIsNotNone(result)
self.assertEqual(result["action"], "block")
def test_unknown_tool_returns_none(self):
result = self.mod._on_pre_tool_call(
tool_name="nonexistent_tool",
args={"path": "~"},
)
self.assertIsNone(result)
def test_non_dict_args_returns_none(self):
result = self.mod._on_pre_tool_call(
tool_name="search_files",
args=None,
)
self.assertIsNone(result)
class TestManifestMetadata(unittest.TestCase):
"""Keep parsed plugin metadata aligned with the canonical manifest version."""
def test_manifest_declares_pre_tool_call_hook(self):
with (PLUGIN_DIR / "plugin.yaml").open(encoding="utf-8") as manifest_file:
manifest = yaml.safe_load(manifest_file)
self.assertEqual(manifest["name"], "kuri-tool-guard")
self.assertEqual(manifest["provides_hooks"], ["pre_tool_call"])
self.assertNotIn("hooks", manifest)
def test_pyproject_version_matches_canonical_manifest(self):
with (PLUGIN_DIR / "plugin.yaml").open(encoding="utf-8") as manifest_file:
manifest = yaml.safe_load(manifest_file)
with (PLUGIN_DIR / "pyproject.toml").open("rb") as pyproject_file:
pyproject = tomllib.load(pyproject_file)
self.assertEqual(pyproject["project"]["version"], manifest["version"])
class TestLoaderIntegration(unittest.TestCase):
"""Verify the plugin loads correctly under Hermes-like conditions."""
def test_double_load_isolation(self):
"""load_mod() returns fresh package + 4 submodules on each call."""
mod1 = load_mod()
s1_guards = submodule(mod1, "_guards")
s1_state = submodule(mod1, "_state")
s1_predicates = submodule(mod1, "_predicates")
s1_parser = submodule(mod1, "_parser")
mod2 = load_mod()
s2_guards = submodule(mod2, "_guards")
s2_state = submodule(mod2, "_state")
s2_predicates = submodule(mod2, "_predicates")
s2_parser = submodule(mod2, "_parser")
self.assertIsNot(mod1, mod2, "package must be a new object on second load")
self.assertIsNot(s1_guards, s2_guards, "_guards must be a new object")
self.assertIsNot(s1_state, s2_state, "_state must be a new object")
self.assertIsNot(s1_predicates, s2_predicates, "_predicates must be a new object")
self.assertIsNot(s1_parser, s2_parser, "_parser must be a new object")
def test_hermes_loader_contract(self):
"""Test that plugin loads correctly in a subprocess without cwd/sys.path."""
plugin_dir = str(PLUGIN_DIR)
code = (
"import os, sys, importlib.util, types\n"
"\n"
"plugin_dir = sys.argv[1]\n"
"cwd = os.getcwd()\n"
"assert cwd != plugin_dir, f'cwd ({cwd}) must differ from plugin dir'\n"
"assert plugin_dir not in sys.path, f'{plugin_dir} should not be in sys.path'\n"
"\n"
"# Remove cwd from sys.path (simulate startup from arbitrary directory)\n"
'sys.path = [p for p in sys.path if p not in ("", ".")]\n'
"\n"
'_NS_PARENT = "hermes_plugins"\n'
'_MOD = f"{_NS_PARENT}.kuri_tool_guard"\n'
"\n"
"# Create namespace parent\n"
"if _NS_PARENT not in sys.modules:\n"
" pkg = types.ModuleType(_NS_PARENT)\n"
" pkg.__path__ = []\n"
" pkg.__package__ = _NS_PARENT\n"
" sys.modules[_NS_PARENT] = pkg\n"
"\n"
"# Load as Hermes does\n"
"spec = importlib.util.spec_from_file_location(\n"
" _MOD,\n"
' plugin_dir + "/__init__.py",\n'
" submodule_search_locations=[plugin_dir],\n"
")\n"
"mod = importlib.util.module_from_spec(spec)\n"
"sys.modules[_MOD] = mod\n"
"spec.loader.exec_module(mod)\n"
"\n"
"# Verify register and dispatcher\n"
'assert hasattr(mod, "register"), "register() missing"\n'
'assert hasattr(mod, "_on_pre_tool_call"), "_on_pre_tool_call() missing"\n'
"\n"
"# Verify submodule names in sys.modules\n"
'chk = lambda n: f"{_MOD}.{n}"\n'
'assert chk("_guards") in sys.modules, f"{_MOD}._guards not loaded"\n'
'assert chk("_state") in sys.modules, f"{_MOD}._state not loaded"\n'
'assert chk("_predicates") in sys.modules, f"{_MOD}._predicates not loaded"\n'
'assert chk("_parser") in sys.modules, f"{_MOD}._parser not loaded"\n'
"\n"
"# Verify NO top-level pollution\n"
'for bad in ("_guards", "_parser", "_predicates", "_state"):\n'
' assert bad not in sys.modules, f"top-level {bad} leaked into sys.modules"\n'
"\n"
"# Verify register(callback) works\n"
"import unittest.mock\n"
"ctx = unittest.mock.MagicMock()\n"
"mod.register(ctx)\n"
'ctx.register_hook.assert_called_once_with("pre_tool_call", mod._on_pre_tool_call)\n'
"\n"
'print("ALL CONTRACT CHECKS PASSED")\n'
)
with tempfile.TemporaryDirectory() as tmpdir:
result = subprocess.run(
[sys.executable, "-c", code, plugin_dir],
capture_output=True,
text=True,
timeout=15,
check=False,
cwd=tmpdir,
)
if result.returncode != 0:
raise AssertionError(
f"Loader contract test failed:\nstdout: {result.stdout}\nstderr: {result.stderr}"
)