314 lines
12 KiB
Python
314 lines
12 KiB
Python
"""F070 — Vertrags-Test-Framework Plugin ↔ Hermes-Core.
|
|
|
|
Stellt sicher, dass das Rocket.Chat-Plugin die Core-API korrekt nutzt.
|
|
Testet den VERTRAG zwischen Plugin und Hermes-Core:
|
|
|
|
1. Plugin lädt korrekt (importierbar, register(ctx) vorhanden)
|
|
2. Plugin registriert die Plattform via ctx.register_platform
|
|
3. Alle vom Plugin beanspruchten Hooks sind in Core-VALID_HOOKS registriert
|
|
(Kontrakt: kein toter Hook — P-032/P-064-Klasse)
|
|
4. Core-API-Aufrufe (send_message, get_room_info, register_command) sind
|
|
über die Adapter-/Core-Schnittstelle erreichbar
|
|
5. Commands sind per InlineCommandRegistry registriert
|
|
|
|
Zwei Einstiegspunkte:
|
|
- pytest: python3 -m pytest tests/contract/test_contract_framework.py
|
|
- Runner: python3 tests/contract/test_contract_framework.py (Standalone-CLI)
|
|
|
|
Der Kern ist run_contract_checks() → {"checked", "passed", "failed": [...]}.
|
|
Der CLI-Runner scripts/run_contract_tests.sh ruft pytest auf diesem Modul auf.
|
|
|
|
@implements: [F-070]
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ast
|
|
import importlib
|
|
import inspect
|
|
import logging
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional
|
|
|
|
import pytest
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ── Pfade ──────────────────────────────────────────────────────────────────
|
|
|
|
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent # tests/contract/ -> Repo-Root
|
|
_PLUGIN_DIR = _REPO_ROOT / "plugin"
|
|
|
|
|
|
def _ensure_plugin_importable() -> None:
|
|
"""Plugin-Paket importierbar machen.
|
|
|
|
Das Plugin ist ein Python-Package unter <repo>/plugin. Um `import plugin`
|
|
zu ermöglichen, muss der PARENT (Repos-Root) auf sys.path, nicht der
|
|
Plugin-Ordner selbst (sonst sucht Python <repo>/plugin/plugin). Analog
|
|
zur conftest.py-Konvention.
|
|
"""
|
|
parent = _PLUGIN_DIR.parent
|
|
if _PLUGIN_DIR.is_dir() and str(parent) not in sys.path:
|
|
sys.path.insert(0, str(parent))
|
|
# Zusätzlich den Plugin-Ordner für Flat-Imports (P-022-Kompatibilität)
|
|
if _PLUGIN_DIR.is_dir() and str(_PLUGIN_DIR) not in sys.path:
|
|
sys.path.insert(0, str(_PLUGIN_DIR))
|
|
|
|
|
|
# ── Vertrags-Beschreibung ────────────────────────────────────────────────
|
|
|
|
# Kernel-Methoden/Attribute, die der RocketChatAdapter exponiert —
|
|
# Abkürzung des Core-API-Vertrags des Plugins:
|
|
# send_message → RocketChatREST.post_message (REST chat.postMessage)
|
|
# get_room_info → Adapter._room_info (Raum-Metadaten-Dict)
|
|
# register_command → Adapter._register_inline_commands (InlineCommandRegistry)
|
|
EXPECTED_ADAPTER_KERNEL_METHODS = {
|
|
"register_command": "_register_inline_commands",
|
|
"get_room_info": "_room_info",
|
|
"send_message": "post_message",
|
|
}
|
|
|
|
# Der Plugin-Entrypoint muss diese Top-Level-Funktionen exportieren
|
|
# (Hermes-Plugin-Basisvertrag).
|
|
EXPECTED_MODULE_FUNCTIONS = {
|
|
"register",
|
|
"check_requirements",
|
|
"validate_config",
|
|
"is_connected",
|
|
}
|
|
|
|
|
|
def _collect_plugin_hooks(plugin_mod) -> List[str]:
|
|
"""Extrahiert die vom Plugin beanspruchten Hook-Namen.
|
|
|
|
Scannt den Plugin-Quelltext auf `ctx.register_hook("...")`.
|
|
Liefert zusätzlich die bekannten Presence-Hooks (aus dem Quelltext).
|
|
"""
|
|
# Fallback-Menge (documented Presence-Hooks des Plugins)
|
|
known = {
|
|
"pre_gateway_dispatch", "post_llm_call", "subagent_start",
|
|
"subagent_stop", "on_session_start", "on_session_end",
|
|
"on_session_finalize", "on_session_reset",
|
|
"pre_tool_call", "post_tool_call",
|
|
"on_kanban_worker_spawned", "on_kanban_worker_exited",
|
|
"on_kanban_worker_stale_claim",
|
|
}
|
|
try:
|
|
src_path = Path(inspect.getfile(plugin_mod)).resolve()
|
|
src = src_path.read_text(encoding="utf-8")
|
|
found = set(re.findall(r'register_hook\(\s*["\']([a-z_]+)["\']', src))
|
|
return sorted(known | found)
|
|
except (OSError, TypeError):
|
|
return sorted(known)
|
|
|
|
|
|
def _get_valid_hooks_from_core() -> Optional[set]:
|
|
"""Liest Core-VALID_HOOKS. None wenn Core nicht importierbar."""
|
|
try:
|
|
import hermes_cli.plugins as core_plugins
|
|
hooks = getattr(core_plugins, "VALID_HOOKS", None)
|
|
return set(hooks) if hooks else None
|
|
except ImportError:
|
|
return None
|
|
|
|
|
|
def _collect_registered_commands() -> List[str]:
|
|
"""Sammelt die via InlineCommandRegistry registrierten ::-Befehle."""
|
|
try:
|
|
from plugin.adapter import RocketChatAdapter
|
|
from plugin.archivar.inline_commands import InlineCommandRegistry
|
|
# Adapter ohne vollständige Initialisierung: nur Registry + Register
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
adapter._inline_commands = InlineCommandRegistry()
|
|
adapter._register_inline_commands()
|
|
return sorted(adapter._inline_commands.get_commands().keys())
|
|
except Exception as e: # noqa: BLE001 - defensiv, Vertrags-Test
|
|
logger.warning("[f070] Command-Sammlung fehlgeschlagen: %s", e)
|
|
return []
|
|
|
|
|
|
def _module_entrypoint_names(plugin_mod) -> set:
|
|
"""Namen der Top-Level-Funktionen im Plugin-__init__.py."""
|
|
try:
|
|
src = Path(inspect.getfile(plugin_mod)).resolve()
|
|
if src.name != "__init__.py":
|
|
src = src.parent / "__init__.py"
|
|
tree = ast.parse(src.read_text(encoding="utf-8")) if src.exists() else None
|
|
if tree:
|
|
return {n.name for n in ast.walk(tree)
|
|
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
|
except (OSError, SyntaxError):
|
|
pass
|
|
return {n for n in dir(plugin_mod) if callable(getattr(plugin_mod, n, None))}
|
|
|
|
|
|
def run_contract_checks(
|
|
valid_hooks: Optional[set] = None,
|
|
) -> Dict[str, object]:
|
|
"""Führt die Vertrags-Prüfungen aus und liefert eine Zusammenfassung.
|
|
|
|
Args:
|
|
valid_hooks: Optional ein set gültiger Hook-Namen (Default: aus
|
|
hermes_cli.plugins.VALID_HOOKS, falls Core importierbar).
|
|
|
|
Returns:
|
|
{"checked": int, "passed": int, "failed": [str,...]}
|
|
"""
|
|
checked = 0
|
|
passed = 0
|
|
failed: List[str] = []
|
|
|
|
def _ok() -> None:
|
|
nonlocal checked, passed
|
|
checked += 1
|
|
passed += 1
|
|
|
|
def _fail(desc: str) -> None:
|
|
nonlocal checked
|
|
checked += 1
|
|
failed.append(desc)
|
|
|
|
_ensure_plugin_importable()
|
|
try:
|
|
plugin_mod = importlib.import_module("plugin")
|
|
except ImportError as e:
|
|
_fail(f"Plugin-Modul 'plugin' NICHT importierbar: {e}")
|
|
return {"checked": checked, "passed": passed, "failed": failed}
|
|
|
|
# ── 1. Basisvertrag: Entrypoint-Funktionen ──────────────────────────
|
|
names = _module_entrypoint_names(plugin_mod)
|
|
for fn in EXPECTED_MODULE_FUNCTIONS:
|
|
has_fn = fn in names or (hasattr(plugin_mod, fn) and callable(getattr(plugin_mod, fn)))
|
|
_ok() if has_fn else _fail(f"Plugin fehlt Entrypoint-Funktion '{fn}()'")
|
|
|
|
# ── 2. Adapter-Kern-API (send_message, get_room_info, register_command) ──
|
|
try:
|
|
from plugin.adapter import RocketChatAdapter
|
|
src_path = Path(inspect.getfile(RocketChatAdapter)).resolve()
|
|
src = src_path.read_text(encoding="utf-8")
|
|
for logical, impl in EXPECTED_ADAPTER_KERNEL_METHODS.items():
|
|
if impl in src or impl in names:
|
|
_ok()
|
|
else:
|
|
_fail(f"Adapter-API '{logical}' nicht gefunden (erwartet '{impl}')")
|
|
except ImportError as e:
|
|
_fail(f"Adapter importierbar: {e}")
|
|
|
|
# ── 3. Hook-Kontrakt (kein toter Hook) ──────────────────────────────
|
|
hooks = _collect_plugin_hooks(plugin_mod)
|
|
core_hooks = valid_hooks if valid_hooks is not None else _get_valid_hooks_from_core()
|
|
if core_hooks is None:
|
|
for h in hooks:
|
|
_ok() # Hook bekannt (Quelltext), Core-Kontrast nicht prüfbar
|
|
logger.info("[f070] Core-VALID_HOOKS nicht lesbar — Hook-Kontrast übersprungen")
|
|
else:
|
|
for h in sorted(hooks):
|
|
if h in core_hooks:
|
|
_ok()
|
|
else:
|
|
_fail(f"Hook '{h}' NICHT in Core-VALID_HOOKS (toter Hook — P-032/P-064)")
|
|
|
|
# ── 4. Command-Registrierung ─────────────────────────────────────────
|
|
cmds = _collect_registered_commands()
|
|
_ok() if cmds else _fail("Keine ::-Befehle per InlineCommandRegistry registriert")
|
|
|
|
return {"checked": checked, "passed": passed, "failed": failed}
|
|
|
|
|
|
def build_report(result: Dict[str, object]) -> str:
|
|
"""Baut den Mensch-lesbaren Vertrags-Bericht."""
|
|
checked = result["checked"]
|
|
passed = result["passed"]
|
|
failed = result["failed"]
|
|
lines = [
|
|
"## 🤝 Contract-Test Plugin ↔ Core (F070)",
|
|
"",
|
|
f"**Geprüft:** {checked} | **Bestanden:** {passed} | "
|
|
f"**Fehlgeschlagen:** {len(failed)}",
|
|
"",
|
|
]
|
|
if failed:
|
|
lines.append("**Fehlgeschlagene Prüfungen:**")
|
|
for f in failed:
|
|
lines.append(f"- ⚠️ {f}")
|
|
lines.append("")
|
|
lines.append("**Ergebnis:** 🔴 NICHT kontrakt-konform")
|
|
else:
|
|
lines.append("**Ergebnis:** 🟢 Plugin ↔ Core-Vertrag erfüllt.")
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Pytest-Tests des Frameworks selbst
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
|
|
def _has_real_plugin() -> bool:
|
|
return (_REPO_ROOT / "plugin").is_dir()
|
|
|
|
|
|
def test_framework_implements_marker():
|
|
content = Path(__file__).read_text(encoding="utf-8")
|
|
assert "@implements: [F-070]" in content, \
|
|
"test_contract_framework.py fehlt @implements: [F-070] (Bindestrich Pflicht)"
|
|
|
|
|
|
def test_contract_checks_return_shape():
|
|
res = run_contract_checks()
|
|
assert set(res) == {"checked", "passed", "failed"}
|
|
assert isinstance(res["checked"], int)
|
|
assert isinstance(res["passed"], int)
|
|
assert isinstance(res["failed"], list)
|
|
assert res["checked"] >= 4, "Mindestens Basisvertrag + Kern-API + Commands"
|
|
|
|
|
|
def test_collect_plugin_hooks_returns_list():
|
|
if _has_real_plugin():
|
|
import plugin # noqa: F401
|
|
hooks = _collect_plugin_hooks(importlib.import_module("plugin"))
|
|
assert isinstance(hooks, list)
|
|
assert len(hooks) > 0, "Plugin muss Presence-Hooks beanspruchen"
|
|
|
|
|
|
@pytest.mark.skipif(not _has_real_plugin(), reason="Echtes Plugin nicht im Repo-Kontext")
|
|
def test_real_plugin_contract_passes():
|
|
"""Gegen das echte Plugin im Repo: Vertrag muss (weitgehend) erfüllt sein."""
|
|
_ensure_plugin_importable()
|
|
import plugin # noqa: F401
|
|
res = run_contract_checks()
|
|
assert res["checked"] > 0, "Vertrags-Checks müssen laufen"
|
|
assert res["passed"] >= 4, \
|
|
f"Basisvertrag + Kern-API + Commands müssen bestehen: {res['failed']}"
|
|
# Kein Adapter-API-Fehler (send_message / get_room_info / register_command)
|
|
for f in res["failed"]:
|
|
assert "Adapter-API" not in f, f"Adapter-Kern-API muss vorhanden sein: {f}"
|
|
|
|
|
|
def test_build_report_formats():
|
|
ok = {"checked": 6, "passed": 6, "failed": []}
|
|
r = build_report(ok)
|
|
assert "Geprüft:" in r and "Bestanden:" in r
|
|
assert "🟢" in r
|
|
|
|
bad = {"checked": 6, "passed": 3, "failed": ["Hook 'ghost' fehlt"]}
|
|
r2 = build_report(bad)
|
|
assert "🔴" in r2
|
|
assert "ghost" in r2
|
|
|
|
|
|
def test_runner_standalone_executable():
|
|
src = Path(__file__).read_text(encoding="utf-8")
|
|
assert 'if __name__ == "__main__":' in src
|
|
assert "sys.exit(" in src
|
|
|
|
|
|
if __name__ == "__main__":
|
|
logging.basicConfig(level=logging.INFO)
|
|
run_contract_checks()
|
|
res = run_contract_checks()
|
|
print(build_report(res))
|
|
sys.exit(1 if res["failed"] else 0)
|