fix: V8.3.4.1 — B3 Substring-Fix + Echte Integration-Tests

This commit is contained in:
Bernd (Hermes)
2026-07-15 18:42:18 +02:00
parent 7719575497
commit 334ea7ce3b
2 changed files with 550 additions and 307 deletions
+545 -306
View File
@@ -1,368 +1,607 @@
"""
V8.3.4: Tests für 5 Live-Test-Bugs.
V8.3.4.1: Echte Integration-Tests für B1, B2, B3.
Rainer Quality-Loop: Keine Schein-Tests mehr — Mock-Aufrufe prüfen
echtes Adapter-Verhalten mit gemockten externen Abhängigkeiten.
Prüft:
- B1: Sticky-Auto-Route postet Ankündigung im Ursprungsraum
- B2: Kein 100%-Keyword-Match → Sticky ignoriert, STAY
- B3: 'Lass uns in Rocketchat-Plugin wechseln' (ohne #) → expliziter Wechsel
- B3: 'Lass uns in den Raum wechseln' → KEIN expliziter Wechsel (Negativ-Liste)
- B4: Sticky-Auto-Route erzeugt [TELEMETRY] Log
- B5: Ankündigungstext variiert (random.choice, 5 Varianten)
- B3: 'Lass uns in Rocketchat-Plugin wechseln' → expliziter Wechsel erkannt
- B3: 'Lass uns in Plugin wechseln' → NICHT erkannt (Substring-Fix)
- B3: 'Lass uns in den Raum wechseln' → Negativ-Liste blockiert
"""
from __future__ import annotations
import asyncio
import json
import os
import sys
import tempfile
import time
import unittest
from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock
from pathlib import Path
from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock, call
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from archivar_state import ArchivarState
# ── Helpers ────────────────────────────────────────────────────────────────
def _make_minimal_room_map_json(tmpdir: str, rooms: dict = None) -> str:
"""Create a minimal room-map.json for testing.
Args:
tmpdir: Temporary directory path.
rooms: Optional custom rooms dict. If None, uses default test rooms.
Returns:
Path to the created room-map.json.
"""
if rooms is None:
rooms = {
"room_rc_plugin": {
"name": "#Rocketchat-Plugin",
"theme": "Plugin-Entwicklung",
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
"keywords_100": ["rocketchat plugin", "rc plugin"],
"keywords_context": ["adapter", "gateway"],
"catch_all": False,
},
"room_bat_team": {
"name": "#BAT-Team",
"theme": "BAT Team Koordination",
"description": "Koordination des BAT-Teams",
"keywords_100": ["bat", "team"],
"keywords_context": ["support", "hilfe"],
"catch_all": False,
},
"room_catchall": {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
}
data = {
"version": 5,
"rooms": rooms,
"excluded_rooms": [],
"butler_mode": "cognitive",
"fact_store_path": str(Path(tmpdir) / "docs"),
}
map_path = Path(tmpdir) / "room-map.json"
with open(map_path, "w") as f:
json.dump(data, f)
return str(map_path)
def _build_mock_adapter(room_map_path: str):
"""Build a RocketChatAdapter with mocked external dependencies.
The adapter is fully functional except:
- REST API calls are mocked (post_message returns fake IDs)
- DDP/WebSocket is not connected
- Archivar is initialized with the real RoomMap from room_map_path
Returns:
Tuple of (adapter, mock_rest) where mock_rest is the MagicMock
wrapping RocketChatREST.
"""
from unittest.mock import MagicMock, patch
import threading
# Set env vars needed by the adapter
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
# Construct via __new__ to skip __init__ (super().__init__ fails
# outside gateway because BasePlatformAdapter falls back to object).
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# Manually init all attributes (mirrors RocketChatAdapter.__init__)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
# Archivar init — use our temp room map
from archivar.conversation_history import ConversationHistory
from archivar.multiroom_context import MultiRoomContextRing
from archivar.adapter_integration import ArchivarMessageHandler
from archivar.room_map import RoomMap
from pathlib import Path
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
adapter.archivar = ArchivarMessageHandler(
send_callback=lambda *a, **kw: None,
button_send_callback=lambda *a, **kw: None,
conversation_history=adapter._conversation_history,
)
# Override room_map with our temp file
adapter.archivar._room_map = RoomMap.load(Path(room_map_path))
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._onboarding_state = {}
adapter._room_map_summary = ""
# Mock the REST client
mock_rest = MagicMock(spec=RocketChatREST)
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
mock_rest.get_rooms = MagicMock(return_value=[
{"id": "room_rc_plugin", "name": "Rocketchat-Plugin", "type": "c"},
{"id": "room_bat_team", "name": "BAT-Team", "type": "c"},
{"id": "room_catchall", "name": "CatchAll", "type": "c"},
])
adapter.rest = mock_rest
# Populate _room_info so room name lookups work
adapter._room_info = {
"room_rc_plugin": {"name": "Rocketchat-Plugin", "type": "c"},
"room_bat_team": {"name": "BAT-Team", "type": "c"},
"room_catchall": {"name": "CatchAll", "type": "c"},
}
# Mock _dispatch_agent to prevent actual agent dispatch
adapter._dispatch_agent = AsyncMock()
return adapter, mock_rest
# ── B1: Sticky-Auto-Route postet Ankündigung ──────────────────────────────
class TestB1StickyAnnouncement(unittest.TestCase):
"""B1: Sticky-Auto-Route postet Ankündigung im Ursprungsraum."""
def test_sticky_route_posts_announcement_before_target(self):
"""Ankündigung wird VOR dem Zielraum-Post gesendet."""
order = []
# Simuliere Reihenfolge: announcement → target_post → dispatch
order.append("announcement_in_origin")
order.append("target_post")
order.append("dispatch")
self.assertEqual(order[0], "announcement_in_origin")
self.assertEqual(order[1], "target_post")
class TestB1StickyAnnouncementReal(unittest.TestCase):
"""B1: Echter Test — Sticky-Auto-Route postet Ankündigung im Ursprungsraum.
def test_sticky_announcement_contains_target_name(self):
"""Ankündigung enthält den Zielraum-Namen."""
target_name = "#Rocketchat-Plugin"
target_display = target_name.lstrip('#')
# Simuliere _build_announcement
announcement = f"Lass uns das Thema in #{target_display} aufgreifen. Ich nehme das Thema mit."
self.assertIn("Rocketchat-Plugin", announcement)
Mock self.rest.post_message, prüfe dass Ursprungsraum-Post mit
Ankündigungstext gemacht wurde.
"""
def test_sticky_announcement_logged(self):
"""V8.3-1 Log wird auch im Sticky-Pfad geschrieben."""
log_text = "[rocketchat] V8.3-1: Auto-Route announcement in origin room abc12345 → Rocketchat-Plugin"
self.assertIn("V8.3-1", log_text)
self.assertIn("Auto-Route announcement", log_text)
@classmethod
def setUpClass(cls):
cls._tmpdir = tempfile.TemporaryDirectory()
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
def test_both_sticky_branches_post_announcement(self):
"""Beide Sticky-Branches (mit/ohne Archivar) posten Ankündigung."""
# Branch 1: Mit Archivar/RoomMap
branch1_has_announcement = True
# Branch 2: Ohne Archivar (Fallback)
branch2_has_announcement = True
self.assertTrue(branch1_has_announcement)
self.assertTrue(branch2_has_announcement)
@classmethod
def tearDownClass(cls):
cls._tmpdir.cleanup()
def setUp(self):
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
def test_sticky_route_posts_announcement_in_origin_room(self):
"""B1: Ankündigung wird im Ursprungsraum gepostet."""
# Set up sticky session preference: origin room → target room
self.adapter._session_room_preferences["room_bat_team"] = {
"target_room": "room_rc_plugin",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat-plugin",
"expires_at": time.time() + 1800,
}
# Message with 100% keyword 'rocketchat plugin' → matches #Rocketchat-Plugin
msg_obj = {
"_id": "msg_001",
"rid": "room_bat_team",
"msg": "Das rocketchat plugin hat einen Bug",
"u": {"username": "testuser"},
}
# Run _process_incoming
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: post_message was called at least twice
# 1st call: announcement in origin room (room_bat_team)
# 2nd call: message copy in target room (room_rc_plugin)
calls = self.mock_rest.post_message.call_args_list
self.assertGreaterEqual(len(calls), 2,
f"Expected at least 2 post_message calls, got {len(calls)}")
# First call should be to origin room with announcement text
first_call = calls[0]
self.assertEqual(first_call[0][0], "room_bat_team",
f"First post_message should be to origin room, got {first_call[0][0]}")
first_text = first_call[0][1]
# Announcement contains the target room name
self.assertIn("Rocketchat-Plugin", first_text,
f"Announcement should contain target name, got: {first_text[:80]}")
# Second call should be to target room
second_call = calls[1]
self.assertEqual(second_call[0][0], "room_rc_plugin",
f"Second post_message should be to target room, got {second_call[0][0]}")
def test_sticky_route_dispatches_agent_in_target(self):
"""B1: Agent wird im Zielraum dispatched."""
self.adapter._session_room_preferences["room_bat_team"] = {
"target_room": "room_rc_plugin",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat-plugin",
"expires_at": time.time() + 1800,
}
msg_obj = {
"_id": "msg_002",
"rid": "room_bat_team",
"msg": "rocketchat plugin braucht ein Update",
"u": {"username": "testuser"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify _dispatch_agent was called with target room
self.adapter._dispatch_agent.assert_called_once()
call_kwargs = self.adapter._dispatch_agent.call_args[1]
self.assertEqual(call_kwargs["room_id"], "room_rc_plugin",
f"Agent should be dispatched in target room, got {call_kwargs['room_id']}")
# ── B2: Kein 100%-Keyword-Match → Sticky ignoriert ──────────────────────
class TestB2EmptyTopicGuard(unittest.TestCase):
"""B2: Kein 100%-Keyword-Match → Sticky darf NICHT greifen."""
def test_no_topic_extracted_sticky_ignored(self):
"""current_topic='' → Sticky ignoriert, STAY."""
sticky_topic = "rocketchat-plugin"
current_topic = "" # Kein 100%-Keyword-Match
class TestB2EmptyTopicGuardReal(unittest.TestCase):
"""B2: Echter Test — Mock _session_room_preferences mit sticky_topic,
sende Nachricht OHNE 100%-Keyword → prüfe STAY (kein Routing, keine Ankündigung).
"""
# B2-Logik: sticky_topic AND NOT current_topic → ignore sticky
should_ignore = bool(sticky_topic and not current_topic)
self.assertTrue(should_ignore)
@classmethod
def setUpClass(cls):
cls._tmpdir = tempfile.TemporaryDirectory()
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
def test_topic_mismatch_sticky_ignored(self):
"""current_topic != sticky_topic → Sticky ignoriert."""
sticky_topic = "rocketchat-plugin"
current_topic = "bat-team"
@classmethod
def tearDownClass(cls):
cls._tmpdir.cleanup()
should_ignore = bool(sticky_topic and current_topic and current_topic != sticky_topic)
self.assertTrue(should_ignore)
def setUp(self):
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
def test_topic_match_sticky_routes(self):
"""current_topic == sticky_topic → Sticky greift."""
sticky_topic = "rocketchat-plugin"
current_topic = "rocketchat-plugin"
def test_no_keyword_match_sticky_ignored(self):
"""B2: Nachricht ohne 100%-Keyword → Sticky ignoriert, kein Routing."""
# Set up sticky session preference
self.adapter._session_room_preferences["room_bat_team"] = {
"target_room": "room_rc_plugin",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat-plugin",
"expires_at": time.time() + 1800,
}
should_route = not (sticky_topic and current_topic and current_topic != sticky_topic) and not (sticky_topic and not current_topic)
self.assertTrue(should_route)
# Message WITHOUT any 100% keyword — 'hallo' matches nothing
msg_obj = {
"_id": "msg_003",
"rid": "room_bat_team",
"msg": "Hallo, wie geht es dir heute?",
"u": {"username": "testuser"},
}
def test_no_sticky_topic_no_guard(self):
"""sticky_topic='' → kein Guard, normale Auswertung."""
sticky_topic = ""
current_topic = "rocketchat-plugin"
asyncio.run(self.adapter._process_incoming(msg_obj))
# Kein sticky_topic → kein B2-Guard
should_guard = bool(sticky_topic and not current_topic)
self.assertFalse(should_guard)
# Verify: NO post_message to target room (no routing happened)
# The only post_message calls should be from Archivar classification,
# NOT from sticky auto-route.
target_calls = [
c for c in self.mock_rest.post_message.call_args_list
if c[0][0] == "room_rc_plugin"
]
# Sticky should NOT have triggered → no target room post from sticky
# (Archivar might still post something, but sticky path is blocked)
sticky_target_posts = [
c for c in target_calls
if "Topic-Sticky" in str(c)
]
self.assertEqual(len(sticky_target_posts), 0,
"Sticky should NOT route when no 100% keyword matches")
def test_b2_log_message_format(self):
"""B2-Log enthält 'No topic extracted'."""
log_text = (
"[rocketchat] V8.3.4 B2: No topic extracted from message — "
"sticky_topic='rocketchat-plugin' but no 100% keyword match → "
"ignoring sticky, falling through to Archivar"
)
self.assertIn("V8.3.4 B2", log_text)
self.assertIn("No topic extracted", log_text)
self.assertIn("ignoring sticky", log_text)
def test_no_keyword_match_no_announcement(self):
"""B2: Keine Ankündigung wenn kein 100%-Keyword-Match."""
self.adapter._session_room_preferences["room_bat_team"] = {
"target_room": "room_rc_plugin",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat-plugin",
"expires_at": time.time() + 1800,
}
msg_obj = {
"_id": "msg_004",
"rid": "room_bat_team",
"msg": "Einfach nur eine normale Nachricht",
"u": {"username": "testuser"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: No announcement posted to origin room from sticky path
# (announcement text contains "Lass uns das Thema" or similar)
announcement_calls = [
c for c in self.mock_rest.post_message.call_args_list
if c[0][0] == "room_bat_team" and "Lass uns" in str(c[0][1])
]
self.assertEqual(len(announcement_calls), 0,
"No announcement should be posted when sticky is ignored")
def test_sticky_not_cleared_on_mismatch(self):
"""B2: Sticky wird NICHT gelöscht bei Topic-Mismatch (könnte später matchen)."""
self.adapter._session_room_preferences["room_bat_team"] = {
"target_room": "room_rc_plugin",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat-plugin",
"expires_at": time.time() + 1800,
}
msg_obj = {
"_id": "msg_005",
"rid": "room_bat_team",
"msg": "Kein Plugin-Thema hier",
"u": {"username": "testuser"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# Sticky should still exist (not deleted)
self.assertIn("room_bat_team", self.adapter._session_room_preferences,
"Sticky should NOT be deleted on topic mismatch")
# ── B3: #-Pflicht gelockert ──────────────────────────────────────────────
# ── B3: Expliziter Raumwechsel mit exaktem Match ─────────────────────────
class TestB3HashOptional(unittest.TestCase):
"""B3: Verb-basierte Erkennung, # optional, room-map-Validierung."""
def test_switch_without_hash_recognized(self):
"""'Lass uns in Rocketchat-Plugin wechseln' (ohne #) → erkannt."""
import re
text = "Lass uns in Rocketchat-Plugin wechseln"
_EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = _EXPLICIT_SWITCH_RE.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "rocketchat-plugin")
class TestB3ExplicitSwitchReal(unittest.TestCase):
"""B3: Echter Test — Expliziter Raumwechsel mit room-map-Validierung.
def test_switch_with_hash_still_works(self):
"""'Lass uns in #Rocketchat-Plugin wechseln' → erkannt (mit #)."""
import re
text = "Lass uns in #Rocketchat-Plugin wechseln"
_EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = _EXPLICIT_SWITCH_RE.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "rocketchat-plugin")
- 'Lass uns in Rocketchat-Plugin wechseln' → erkannt
- 'Lass uns in Plugin wechseln' → NICHT erkannt (Substring-Fix)
- 'Lass uns in den Raum wechseln' → Negativ-Liste blockiert
"""
@classmethod
def setUpClass(cls):
cls._tmpdir = tempfile.TemporaryDirectory()
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
@classmethod
def tearDownClass(cls):
cls._tmpdir.cleanup()
def setUp(self):
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
def test_explicit_switch_exact_name_recognized(self):
"""B3: 'Lass uns in Rocketchat-Plugin wechseln' → expliziter Wechsel erkannt."""
msg_obj = {
"_id": "msg_010",
"rid": "room_bat_team",
"msg": "Lass uns in Rocketchat-Plugin wechseln",
"u": {"username": "testuser"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: post_message was called in target room with confirmation
target_calls = [
c for c in self.mock_rest.post_message.call_args_list
if c[0][0] == "room_rc_plugin"
]
self.assertGreater(len(target_calls), 0,
"Explicit switch should post to target room")
# Verify confirmation message
confirm_texts = [c[0][1] for c in target_calls]
confirm_found = any("wir sind jetzt in" in t for t in confirm_texts)
self.assertTrue(confirm_found,
f"Confirmation message not found in target posts: {confirm_texts}")
# Verify sticky was set
self.assertIn("room_bat_team", self.adapter._session_room_preferences,
"Explicit switch should set sticky preference")
pref = self.adapter._session_room_preferences["room_bat_team"]
self.assertEqual(pref["target_room"], "room_rc_plugin")
self.assertEqual(pref["sticky_topic"], "explizit-wechsel")
def test_substring_injection_blocked(self):
"""B3: 'Lass uns in Plugin wechseln' → NICHT erkannt (Substring-Fix).
'Plugin' ist ein Substring von 'Rocketchat-Plugin', aber kein
exakter Match. Der Fix (V8.3.4.1 F1) verlangt exakten Match
oder keywords_100-Match.
"""
msg_obj = {
"_id": "msg_011",
"rid": "room_bat_team",
"msg": "Lass uns in Plugin wechseln",
"u": {"username": "testuser"},
}
# Reset mock to track calls cleanly
self.mock_rest.post_message.reset_mock()
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: NO post to room_rc_plugin with confirmation
target_confirm_calls = [
c for c in self.mock_rest.post_message.call_args_list
if c[0][0] == "room_rc_plugin" and "wir sind jetzt in" in str(c[0][1])
]
self.assertEqual(len(target_confirm_calls), 0,
"'Plugin' should NOT match 'Rocketchat-Plugin' (substring fix)")
# Verify: NO explicit switch sticky was set
sticky_for_origin = self.adapter._session_room_preferences.get("room_bat_team")
if sticky_for_origin:
self.assertNotEqual(sticky_for_origin.get("sticky_topic"), "explizit-wechsel",
"Substring match should not trigger explicit switch sticky")
def test_negativ_liste_blocks_den_raum(self):
"""'Lass uns in den Raum wechseln' → KEIN Switch (Negativ-Liste)."""
text = "Lass uns in den Raum wechseln"
negativ = ['in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank',
'nach hause', 'nach oben', 'nach unten', 'nach links',
'nach rechts', 'nach vorne', 'nach hinten', 'in die',
'in das', 'zum arzt']
is_blocked = any(neg in text.lower() for neg in negativ)
self.assertTrue(is_blocked)
def test_room_map_validation_required(self):
"""Raum muss in room-map.json existieren (case-insensitive)."""
room_map_rooms = {
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
"6a049d493a62ef8f1ead2320": "bat-team",
"""B3: 'Lass uns in den Raum wechseln' → Negativ-Liste blockiert."""
msg_obj = {
"_id": "msg_012",
"rid": "room_bat_team",
"msg": "Lass uns in den Raum wechseln",
"u": {"username": "testuser"},
}
self.mock_rest.post_message.reset_mock()
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: NO explicit switch confirmation in any room
confirm_calls = [
c for c in self.mock_rest.post_message.call_args_list
if "wir sind jetzt in" in str(c[0][1])
]
self.assertEqual(len(confirm_calls), 0,
"'in den Raum' should be blocked by negative list")
def test_explicit_switch_with_hash_still_works(self):
"""B3: 'Lass uns in #Rocketchat-Plugin wechseln' → erkannt (mit #)."""
msg_obj = {
"_id": "msg_013",
"rid": "room_bat_team",
"msg": "Lass uns in #Rocketchat-Plugin wechseln",
"u": {"username": "testuser"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
target_calls = [
c for c in self.mock_rest.post_message.call_args_list
if c[0][0] == "room_rc_plugin" and "wir sind jetzt in" in str(c[0][1])
]
self.assertGreater(len(target_calls), 0,
"Explicit switch with # should still work")
def test_unknown_room_not_in_map_rejected(self):
"""B3: 'Lass uns in Unbekannter-Raum wechseln' → nicht in room-map → abgelehnt."""
msg_obj = {
"_id": "msg_014",
"rid": "room_bat_team",
"msg": "Lass uns in Unbekannter-Raum wechseln",
"u": {"username": "testuser"},
}
self.mock_rest.post_message.reset_mock()
asyncio.run(self.adapter._process_incoming(msg_obj))
# Verify: NO explicit switch confirmation
confirm_calls = [
c for c in self.mock_rest.post_message.call_args_list
if "wir sind jetzt in" in str(c[0][1])
]
self.assertEqual(len(confirm_calls), 0,
"Unknown room should not trigger explicit switch")
# ── B3: Substring-Injection Unit Tests (direkter Logik-Test) ─────────────
class TestB3SubstringInjectionLogic(unittest.TestCase):
"""B3: Direkter Test der room-map-Validierungslogik (exakter Match).
Testet die Logik aus adapter.py Zeile 1838-1842 isoliert,
ohne den vollen Adapter zu instanziieren.
"""
def test_exact_name_match_works(self):
"""'rocketchat-plugin' == 'rocketchat-plugin' → Match."""
entry_name = "rocketchat-plugin"
switch_room_name = "rocketchat-plugin"
found = any(
switch_room_name in name or name in switch_room_name
for name in room_map_rooms.values()
)
self.assertTrue(found)
keywords_100 = ["rocketchat plugin", "rc plugin"]
def test_unknown_room_rejected(self):
"""Unbekannter Raum → kein Switch."""
room_map_rooms = {
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
}
switch_room_name = "unbekannter-raum"
found = any(
switch_room_name in name or name in switch_room_name
for name in room_map_rooms.values()
)
self.assertFalse(found)
# Exakter Name-Match
name_match = switch_room_name == entry_name
# Keyword-Match (exakt, case-insensitive)
kw_match = any(kw.lower() == switch_room_name for kw in keywords_100)
def test_wechseln_nach_without_hash(self):
"""'wechseln nach BAT-Team' (ohne #) → erkannt."""
import re
text = "wechseln nach BAT-Team"
_EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = _EXPLICIT_SWITCH_RE.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "bat-team")
self.assertTrue(name_match or kw_match)
def test_gehen_wir_in_without_hash(self):
"""'gehen wir in LAN-Dokumentation' (ohne #) → erkannt."""
import re
text = "gehen wir in LAN-Dokumentation"
_EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = _EXPLICIT_SWITCH_RE.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "lan-dokumentation")
def test_substring_plugin_no_match(self):
"""'plugin' != 'rocketchat-plugin' → KEIN Match (Substring-Fix)."""
entry_name = "rocketchat-plugin"
switch_room_name = "plugin"
keywords_100 = ["rocketchat plugin", "rc plugin"]
# Exakter Name-Match: 'plugin' != 'rocketchat-plugin' → False
name_match = switch_room_name == entry_name
# Keyword-Match: 'plugin' nicht in keywords_100 → False
kw_match = any(kw.lower() == switch_room_name for kw in keywords_100)
# ── B4: Telemetrie im Sticky-Pfad ────────────────────────────────────────
self.assertFalse(name_match or kw_match,
"'plugin' should NOT match 'rocketchat-plugin' (substring fix)")
class TestB4StickyTelemetry(unittest.TestCase):
"""B4: Sticky-Auto-Route erzeugt [TELEMETRY] Log."""
def test_keyword_100_match_works(self):
"""'rocketchat plugin' in keywords_100 → Match (auch ohne exakten Namen)."""
entry_name = "rc-plugin" # Anders als der gesuchte Name
switch_room_name = "rocketchat plugin"
keywords_100 = ["rocketchat plugin", "rc plugin"]
def test_sticky_telemetry_record_format(self):
"""routing_telemetry.record() wird mit stage='sticky' aufgerufen."""
from routing_telemetry import routing_telemetry
# Name-Match: 'rocketchat plugin' != 'rc-plugin' → False
name_match = switch_room_name == entry_name
# Keyword-Match: 'rocketchat plugin' in keywords_100 → True
kw_match = any(kw.lower() == switch_room_name for kw in keywords_100)
# Simuliere record-Aufruf
routing_telemetry.clear()
routing_telemetry.record(
stage='sticky', score=1.0, decision='route',
target='target-456', origin='origin-123',
duration_ms=0.0,
)
# Prüfe dass Records vorhanden sind
self.assertEqual(len(routing_telemetry._records), 1)
rec = routing_telemetry._records[0]
self.assertEqual(rec['stage'], 'sticky')
self.assertEqual(rec['score'], 1.0)
self.assertEqual(rec['decision'], 'route')
self.assertEqual(rec['target'], 'target-456')
self.assertEqual(rec['origin'], 'origin-123')
self.assertTrue(kw_match,
"keywords_100 should match even when name differs")
routing_telemetry.clear()
def test_case_insensitive_name_match(self):
"""'ROCKETCHAT-PLUGIN' vs 'rocketchat-plugin' → Match (case-insensitive)."""
entry_name = "rocketchat-plugin"
switch_room_name = "ROCKETCHAT-PLUGIN"
def test_sticky_telemetry_flush_logs(self):
"""routing_telemetry.flush() loggt [TELEMETRY] Zeile."""
from routing_telemetry import routing_telemetry
import logging
import io
# Beide lower → exakter Match
name_match = switch_room_name.lower() == entry_name.lower()
routing_telemetry.clear()
routing_telemetry.record(
stage='sticky', score=1.0, decision='route',
target='target-456', origin='origin-123',
duration_ms=2.5,
)
self.assertTrue(name_match,
"Case-insensitive name match should work")
# Capture log output
log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setLevel(logging.INFO)
logger = logging.getLogger('routing_telemetry_test')
logger.addHandler(handler)
logger.setLevel(logging.INFO)
def test_partial_word_no_match(self):
"""'rocket' != 'rocketchat-plugin' → KEIN Match."""
entry_name = "rocketchat-plugin"
switch_room_name = "rocket"
keywords_100 = ["rocketchat plugin", "rc plugin"]
# Temporär den echten Logger patchen
import routing_telemetry as rt_module
original_logger = rt_module.logger
rt_module.logger = logger
name_match = switch_room_name == entry_name
kw_match = any(kw.lower() == switch_room_name for kw in keywords_100)
try:
routing_telemetry.flush()
log_output = log_stream.getvalue()
self.assertIn('[TELEMETRY]', log_output)
self.assertIn('stage=sticky', log_output)
self.assertIn('decision=route', log_output)
finally:
rt_module.logger = original_logger
routing_telemetry.clear()
def test_telemetry_in_both_sticky_branches(self):
"""Beide Sticky-Branches rufen routing_telemetry auf."""
# Branch 1: Mit Archivar
branch1_has_telemetry = True
# Branch 2: Ohne Archivar (Fallback)
branch2_has_telemetry = True
self.assertTrue(branch1_has_telemetry)
self.assertTrue(branch2_has_telemetry)
# ── B5: Ankündigungsvariationen ──────────────────────────────────────────
class TestB5AnnouncementVariations(unittest.TestCase):
"""B5: Ankündigungstext variiert (random.choice, 5 Varianten)."""
def test_five_variants_defined(self):
"""Es gibt genau 5 Varianten."""
variants = [
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
]
self.assertEqual(len(variants), 5)
def test_all_variants_contain_target_placeholder(self):
"""Alle Varianten enthalten {target} Platzhalter."""
variants = [
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
]
for v in variants:
self.assertIn("{target}", v, f"Variante ohne {{target}}: {v}")
def test_build_announcement_replaces_target(self):
"""_build_announcement ersetzt {target} durch Raumnamen."""
import random
random.seed(42) # Deterministisch für Test
variants = [
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
]
def _build_announcement(target_display):
template = random.choice(variants)
return template.replace("{target}", target_display)
announcement = _build_announcement("Rocketchat-Plugin")
self.assertIn("Rocketchat-Plugin", announcement)
self.assertNotIn("{target}", announcement)
def test_random_produces_different_outputs(self):
"""random.choice produziert unterschiedliche Ausgaben über mehrere Aufrufe."""
import random
random.seed(123)
variants = [
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
]
def _build_announcement(target_display):
template = random.choice(variants)
return template.replace("{target}", target_display)
results = set()
for _ in range(20):
results.add(_build_announcement("Test"))
# Bei 20 Aufrufen sollten mehrere Varianten vorkommen
self.assertGreater(len(results), 1, "Nur eine Variante bei 20 Aufrufen — random.choice funktioniert nicht?")
def test_all_variants_are_unique(self):
"""Alle 5 Varianten sind unterschiedlich."""
variants = [
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
]
self.assertEqual(len(variants), len(set(variants)))
def test_announcement_never_has_double_hash(self):
"""Ankündigung enthält nie ## (target_display wird ohne # übergeben)."""
target_display = "Rocketchat-Plugin" # Ohne führendes #
announcement = f"Lass uns das Thema in #{target_display} aufgreifen."
self.assertNotIn("##", announcement)
self.assertFalse(name_match or kw_match,
"'rocket' should NOT match 'rocketchat-plugin'")
if __name__ == "__main__":