Files
Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_v8_4_5.py
T

406 lines
15 KiB
Python

"""
V8.4.5: room-map.json Router-Instanz + Telemetrie-Logging + Kontext-Keyword Butler.
Tests:
1. RoomMap wird vom Router korrekt geladen (nicht leer, nicht falsch)
2. Telemetrie wird geloggt (logger.info mit [TELEMETRY] Präfix)
3. Kontext-Keyword 'sony' → Butler fragt (nicht STAY)
4. Keyword-Match funktioniert mit wiederhergestellter room-map.json
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import sys
import tempfile
from pathlib import Path
from typing import Optional
from unittest.mock import patch
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
from plugin.archivar.room_map import RoomMap, RoomEntry
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
from plugin.archivar.archivar_state import ArchivarState
from plugin.archivar.routing_telemetry import RoutingTelemetry, routing_telemetry
from plugin.archivar.routing_counter import routing_counter
# ── Helpers ────────────────────────────────────────────────────────────────
class MockEmbeddingClient(EmbeddingClient):
"""Mock embedding client that returns fixed vectors."""
def get_embedding(self, text: str) -> Optional[list]:
return [0.1] * 768
def _make_room_map_with_sony() -> RoomMap:
"""Build a RoomMap with 2 non-catch-all rooms + 1 catch-all (DM with sony keyword)."""
tmp = tempfile.TemporaryDirectory()
map_path = Path(tmp.name) / "room-map.json"
test_data = {
"version": 5,
"rooms": {
"room_rc_plugin": {
"name": "#RC-Plugin",
"theme": "Rocket.Chat Plugin Entwicklung",
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
"keywords_100": ["plugin", "rocketchat"],
"keywords_context": ["adapter", "gateway"],
"catch_all": False,
},
"room_lan_doku": {
"name": "#LAN-Doku",
"theme": "LAN Dokumentation",
"description": "Dokumentation des LAN-Netzwerks",
"keywords_100": ["dokumentation", "doku"],
"keywords_context": ["netzwerk", "lan"],
"catch_all": False,
},
"room_dm_andreas": {
"name": "DM mit Andreas",
"theme": "Direktnachrichten — Strategie, Meta-Entscheidungen",
"description": "Catch-All für alle Themen ohne eigenen Raum",
"keywords_100": ["strategie", "entscheidung"],
"keywords_context": ["meta", "roadmap", "sony"],
"catch_all": True,
},
},
}
with open(map_path, "w") as f:
json.dump(test_data, f)
return RoomMap.load(map_path)
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
"""Build a BidirectionalRouter with mock classifier and state."""
classifier = IntentClassifier(
embedding_client=MockEmbeddingClient(),
llm_client=None,
)
if mock_llm_fn is not None:
classifier._llm_raw = mock_llm_fn
state = ArchivarState(":memory:")
state.load()
router = BidirectionalRouter(room_map, classifier, state)
router.set_subscribed_room_ids(list(room_map.rooms.keys()))
return router
# ── Fix 1: RoomMap wird vom Router korrekt geladen ─────────────────────────
class TestRoomMapRouterIntegration:
"""RoomMap wird korrekt an den Router übergeben und ist nicht leer."""
def test_router_has_room_map_with_rooms(self):
"""Router._room_map enthält alle Räume aus der Map."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
assert router._room_map is room_map, (
"Router should hold the same RoomMap instance"
)
assert len(router._room_map.rooms) == 3, (
f"Expected 3 rooms, got {len(router._room_map.rooms)}"
)
assert router._room_map.catch_all_room is not None, (
"RoomMap should have a catch-all room"
)
assert router._room_map.catch_all_room.name == "DM mit Andreas", (
f"Expected 'DM mit Andreas', got {router._room_map.catch_all_room.name}"
)
def test_router_room_map_not_empty(self):
"""Router._room_map.rooms ist nicht leer (kein leerer Dict)."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
assert len(router._room_map.rooms) > 0, (
"Router room_map should not be empty"
)
# Verify each room has keywords
for rid, room in router._room_map.rooms.items():
assert room.name, f"Room {rid} should have a name"
assert isinstance(room.keywords_100, list), (
f"Room {rid} keywords_100 should be a list"
)
assert isinstance(room.keywords_context, list), (
f"Room {rid} keywords_context should be a list"
)
def test_room_map_has_expected_rooms(self):
"""RoomMap enthält die erwarteten Räume mit korrekten Namen."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
room_names = {r.name for r in router._room_map.rooms.values()}
assert "#RC-Plugin" in room_names
assert "#LAN-Doku" in room_names
assert "DM mit Andreas" in room_names
# ── Fix 2: Telemetrie-Logging ──────────────────────────────────────────────
class TestTelemetryLogging:
"""Telemetrie wird korrekt geloggt (logger.info mit [TELEMETRY] Präfix)."""
def test_telemetry_logger_has_handler(self):
"""routing_telemetry logger hat einen StreamHandler."""
from plugin.archivar.routing_telemetry import logger as telemetry_logger
assert len(telemetry_logger.handlers) > 0, (
"Telemetry logger should have at least one handler"
)
assert telemetry_logger.level <= logging.INFO, (
f"Telemetry logger level should be <= INFO, got {telemetry_logger.level}"
)
def test_telemetry_flush_logs_info(self, caplog):
"""flush() loggt [TELEMETRY] Zeilen via logger.info."""
# Temporarily enable propagation so caplog can capture
from plugin.archivar.routing_telemetry import logger as telemetry_logger
telemetry_logger.propagate = True
caplog.set_level(logging.INFO)
try:
telemetry = RoutingTelemetry()
telemetry._enabled = True
telemetry.record(
stage="keyword_100", score=1.0, decision="route",
target="room-abc", origin="room-xyz", duration_ms=2.3,
)
telemetry.flush()
assert any(
"[TELEMETRY]" in r.message
for r in caplog.records
), f"Expected [TELEMETRY] in log records, got: {[r.message for r in caplog.records]}"
finally:
telemetry_logger.propagate = False
def test_telemetry_disabled_does_not_log(self, caplog):
"""Wenn disabled, wird kein [TELEMETRY] geloggt."""
caplog.set_level(logging.INFO, logger="plugin.archivar.routing_telemetry")
telemetry = RoutingTelemetry()
telemetry._enabled = False
telemetry.record(
stage="keyword_100", score=1.0, decision="route",
target="room-abc", origin="room-xyz", duration_ms=2.3,
)
telemetry.flush()
telemetry_records = [
r for r in caplog.records
if r.name == "plugin.archivar.routing_telemetry"
]
assert len(telemetry_records) == 0, (
"No telemetry records should be logged when disabled"
)
def test_telemetry_record_and_flush_in_router(self, caplog):
"""Router.route() produziert Telemetrie-Logs bei Keyword-Match."""
# Temporarily enable propagation so caplog can capture
from plugin.archivar.routing_telemetry import logger as telemetry_logger
telemetry_logger.propagate = True
caplog.set_level(logging.INFO)
try:
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
# Enable telemetry
routing_telemetry._enabled = True
routing_telemetry.clear()
# Message with 100% keyword match for #RC-Plugin
decision = asyncio.run(router.route(
"Das Plugin hat einen Bug",
origin_room_id="room_lan_doku",
))
# Flush telemetry (normally done by adapter)
routing_telemetry.flush()
assert any(
"[TELEMETRY]" in r.message
for r in caplog.records
), f"Expected [TELEMETRY] in log records, got: {[r.message for r in caplog.records]}"
finally:
telemetry_logger.propagate = False
# ── Fix 3: Kontext-Keyword 'sony' → Butler ─────────────────────────────────
class TestSonyContextKeyword:
"""Kontext-Keyword 'sony' im DM-Raum löst Butler aus (nicht STAY)."""
def test_sony_context_keyword_triggers_butler(self):
"""'Sony Vollformat Kamera' matched 'sony' → Butler fragt (V8.4.6)."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
# 'sony' is a context keyword for DM mit Andreas (catch-all)
# V8.4.6: Catch-All-Räume sind jetzt bei Kontext-Keywords als
# Butler-Ziele erlaubt. 'sony' matched den DM-Raum → Butler fragt.
decision = asyncio.run(router.route(
"Sony Vollformat Kamera",
origin_room_id="room_rc_plugin",
))
# V8.4.6: 'sony' context keyword matches DM (catch-all) → butler
assert decision.move_request_sent is True, (
f"V8.4.6: context keyword on catch-all should trigger butler, "
f"got move_request_sent={decision.move_request_sent}"
)
assert decision.target_room == "room_dm_andreas", (
f"Expected target_room='room_dm_andreas', got {decision.target_room}"
)
def test_sony_in_non_catchall_room_triggers_match(self):
"""Wenn 'sony' in einem Nicht-Catch-All-Raum wäre, würde es matchen."""
# Build a room map where 'sony' is in a non-catch-all room
tmp = tempfile.TemporaryDirectory()
map_path = Path(tmp.name) / "room-map.json"
test_data = {
"version": 5,
"rooms": {
"room_rc_plugin": {
"name": "#RC-Plugin",
"theme": "Rocket.Chat Plugin Entwicklung",
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
"keywords_100": ["plugin", "rocketchat"],
"keywords_context": ["adapter", "gateway", "sony"],
"catch_all": False,
},
"room_dm_andreas": {
"name": "DM mit Andreas",
"theme": "Direktnachrichten",
"description": "Catch-All",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
},
}
with open(map_path, "w") as f:
json.dump(test_data, f)
room_map = RoomMap.load(map_path)
# Test find_room_by_keywords directly
matched = room_map.find_room_by_keywords(
"Sony Vollformat Kamera adapter gateway",
origin_room_id="room_lan_doku",
)
assert matched is not None, (
"Expected keyword match for 'sony adapter gateway'"
)
assert matched.room_id == "room_rc_plugin", (
f"Expected room_rc_plugin, got {matched.room_id}"
)
# Now test full router flow with mock LLM
async def mock_llm_stay(prompt: str) -> str:
return "STAY"
router = _make_router(room_map, mock_llm_stay)
decision = asyncio.run(router.route(
"Sony Vollformat Kamera adapter gateway",
origin_room_id="room_lan_doku",
))
# 'sony' is a context keyword for #RC-Plugin (non-catch-all)
# → should trigger butler
assert decision.move_request_sent is True, (
f"Expected move_request_sent=True (butler), got {decision.move_request_sent}"
)
assert decision.target_room == "room_rc_plugin", (
f"Expected target_room='room_rc_plugin', got {decision.target_room}"
)
def test_100_percent_keyword_auto_routes(self):
"""100%-Keyword-Match routet automatisch (kein Butler)."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
decision = asyncio.run(router.route(
"Bitte die dokumentation aktualisieren",
origin_room_id="room_rc_plugin",
))
# 'dokumentation' matches (100% keyword for #LAN-Doku)
assert decision.target_room == "room_lan_doku", (
f"Expected target_room='room_lan_doku', got {decision.target_room}"
)
assert decision.move_request_sent is False, (
"100% keyword match should auto-route (no butler)"
)
# ── Regression: Bestehende Tests nicht brechen ─────────────────────────────
class TestRegression:
"""Bestehende Funktionalität bleibt erhalten."""
def test_meta_question_stays(self):
"""Meta-Fragen bleiben im Ursprungsraum."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
# "in welchem raum" matches meta pattern
decision = asyncio.run(router.route(
"In welchem Raum wurde meine Nachricht klassifiziert?",
origin_room_id="room_rc_plugin",
))
assert decision.is_meta is True
assert decision.stay_in_room is True
def test_empty_text_stays(self):
"""Leerer Text → stay_in_room."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
decision = asyncio.run(router.route(
"",
origin_room_id="room_rc_plugin",
))
assert decision.stay_in_room is True
def test_catch_all_origin_bypass(self):
"""Nachricht aus Catch-All-Raum → stay_in_room."""
room_map = _make_room_map_with_sony()
router = _make_router(room_map)
decision = asyncio.run(router.route(
"Dokumentiere das Plugin",
origin_room_id="room_dm_andreas",
))
# Catch-all origin bypass: message from catch-all room stays
assert decision.stay_in_room is True