Files
Hermes_rocket.chat_Plugin/tests/test_f544_context_curator.py

207 lines
8.7 KiB
Python

"""
F544 — Archivar als Context-Curator im multiroom=false Szenario.
Verifiziert plugin/archivar/context_curator.py:
1. ContextCurator sammelt Raum-Kontext (Themen, aktive User, Keywords).
2. build_context_report erzeugt den ::context-Report für einen Raum.
3. Funktioniert auch OHNE Multi-Room-Komponenten (eigenständig, multiroom=false).
4. Leerer Raum → sinnvolle "Noch kein Kontext"-Meldung.
5. Thread-safety-Grundlage (Record + Report aus verschiedenen "Threads").
Kerneigenschaft F544: Der Context-Curator ist vom ARCHIVAR-Load in adapter.py
entkoppelt und läuft auch, wenn _MULTIROOM()=false (dort werden ConversationHistory,
MultiRoomContextRing und ArchivarMessageHandler auf None gesetzt). Dieses Modul
braucht keiner von ihnen.
@implements: [F-544]
"""
from __future__ import annotations
import threading
from pathlib import Path
import sys
import pytest
_ROOT = Path(__file__).resolve().parent.parent # tests/ -> Repo-Root
_PLUGIN_ARCHIVAR = _ROOT / "plugin" / "archivar"
if str(_PLUGIN_ARCHIVAR) not in sys.path:
sys.path.insert(0, str(_PLUGIN_ARCHIVAR))
from context_curator import ContextCurator # noqa: E402
def _make_cc() -> ContextCurator:
return ContextCurator(max_topics_per_room=8, max_keywords_per_room=12)
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Kontext-Sammlung (Themen, User, Keywords)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_collects_room_context():
cc = _make_cc()
room = "R-123"
cc.record(room, "#Entwicklung", "bernd", "Deployment status ist grün und stabil")
cc.record(room, "#Entwicklung", "andreas", "Firewall-Regel aktualisiert")
cc.record(room, "#Entwicklung", "bernd", "Firewall grün")
ctx = cc.room_context(room)
assert ctx is not None
assert len(ctx.topics) == 3 # drei verschiedene Topics
# Aktive User: bernd 2x, andreas 1x
assert ctx.users["bernd"].message_count == 2
assert ctx.users["andreas"].message_count == 1
# Keyword 'firewall' sollte >1 sein (2x vorgekommen)
assert ctx.keywords["firewall"] >= 2
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: ::context-Report
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_context_report_build():
cc = _make_cc()
room = "R-1"
cc.record(room, "#Dev", "bernd", "Deployment ist grün")
cc.record(room, "#Dev", "bernd", "Firewall konfiguriert")
report = cc.build_context_report(room)
assert "Kontext-Raum" in report
assert "#Dev" in report
assert "Aktive User" in report
assert "bernd" in report
assert "Letzte Themen" in report
def test_f544_context_report_empty_room():
cc = _make_cc()
report = cc.build_context_report("unbekannt")
assert "Noch kein Kontext" in report
assert "unbekannt" in report
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: Eigenständigkeit bei multiroom=false (kein Abhängigkeits-Import)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_does_not_require_multiroom_deps():
"""Stellt sicher, dass context_curator NUR Standard-Lib/typing importiert.
Es darf nicht von ConversationHistory / MultiRoomContextRing /
adapter.py abhängen — denn diese existieren im multiroom=false-Runtime
nicht (werden auf None gesetzt).
"""
import inspect
import context_curator as mod
# Prüfe NUR die Import-Anweisungen (top-level), nicht Docstrings/Kommentare.
src = inspect.getsource(mod)
import_lines = []
in_docstring = False
for line in src.splitlines():
stripped = line.strip()
if stripped.startswith('"""') or stripped.startswith("'''"):
in_docstring = not in_docstring
continue
if in_docstring:
continue
if stripped.startswith("import ") or stripped.startswith("from "):
import_lines.append(line)
import_block = "\n".join(import_lines)
for forbidden in (
"ConversationHistory",
"MultiRoomContextRing",
"ArchivarMessageHandler",
"from adapter",
"import adapter",
"from .conversation_history",
"from .multiroom_context",
"from .adapter_integration",
):
assert forbidden not in import_block, (
f"F544 context_curator darf NICHT von '{forbidden}' abhängen"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: Stoppwort-Filter & Thread-Safety (Paralleles Record + Report)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_stopword_filter():
cc = _make_cc()
cc.record("R", "#Dev", "bernd", "der und die das ist mit Firewall grün")
ctx = cc.room_context("R")
# Kein einziges Stoppwort darf als Keyword gezählt werden
assert "der" not in ctx.keywords
assert "und" not in ctx.keywords
assert "ist" not in ctx.keywords
assert "firewall" in ctx.keywords
def test_f544_thread_safe_record_report():
cc = _make_cc()
room = "R-T"
def writer():
for i in range(50):
cc.record(room, "#Thread", "alice", f"Nachricht Nummer {i} firewall")
threads = [threading.Thread(target=writer) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
report = cc.build_context_report(room)
assert "firewall" in report
assert cc.known_rooms() >= 1
# ═══════════════════════════════════════════════════════════════════════════
# Test 5: Clear / Reset
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_clear():
cc = _make_cc()
cc.record("R", "#Dev", "bernd", "Deployment grün")
assert cc.known_rooms() == 1
cc.clear()
assert cc.known_rooms() == 0
# ═══════════════════════════════════════════════════════════════════════════
# Test 6: Verdrahtung in adapter.py (kein toter Code — P-084)
# ═══════════════════════════════════════════════════════════════════════════
def test_f544_wired_in_adapter():
"""Stellt sicher, dass ::context in adapter.py registriert UND verdrahtet ist.
- ContextCurator wird in adapter.py instanziiert (_context_curator).
- record() wird im Nachrichten-Eingangspfad aufgerufen.
- 'context' ist in der Inline-Command-Registry registriert.
- _cmd_context-Handler existiert.
"""
adapter_src = (_ROOT / "plugin" / "adapter.py").read_text()
# 1. Instantiation (in jedem Modus, nicht nur _MULTIROOM())
assert "self._context_curator = ContextCurator()" in adapter_src
assert "from archivar.context_curator import ContextCurator" in adapter_src
# 2. record()-Verdrahtung im Eingangspfad
assert "cc.record(room_id, room_name, username, display_text)" in adapter_src
# 3. Registry-Registrierung
assert '"context", self._cmd_context' in adapter_src
# 4. Handler existiert
assert "async def _cmd_context(self, room_id: str, args: str) -> str:" in adapter_src