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

609 lines
23 KiB
Python

"""
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' → 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 pathlib import Path
from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock, call
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
# ── 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 TestB1StickyAnnouncementReal(unittest.TestCase):
"""B1: Echter Test — Sticky-Auto-Route postet Ankündigung im Ursprungsraum.
Mock self.rest.post_message, prüfe dass Ursprungsraum-Post mit
Ankündigungstext gemacht wurde.
"""
@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_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 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).
"""
@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_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,
}
# 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"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# 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_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: Expliziter Raumwechsel mit exaktem Match ─────────────────────────
class TestB3ExplicitSwitchReal(unittest.TestCase):
"""B3: Echter Test — Expliziter Raumwechsel mit room-map-Validierung.
- '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):
"""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"
keywords_100 = ["rocketchat plugin", "rc plugin"]
# 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)
self.assertTrue(name_match or kw_match)
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)
self.assertFalse(name_match or kw_match,
"'plugin' should NOT match 'rocketchat-plugin' (substring fix)")
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"]
# 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)
self.assertTrue(kw_match,
"keywords_100 should match even when name differs")
def test_case_insensitive_name_match(self):
"""'ROCKETCHAT-PLUGIN' vs 'rocketchat-plugin' → Match (case-insensitive)."""
entry_name = "rocketchat-plugin"
switch_room_name = "ROCKETCHAT-PLUGIN"
# Beide lower → exakter Match
name_match = switch_room_name.lower() == entry_name.lower()
self.assertTrue(name_match,
"Case-insensitive name match should work")
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"]
name_match = switch_room_name == entry_name
kw_match = any(kw.lower() == switch_room_name for kw in keywords_100)
self.assertFalse(name_match or kw_match,
"'rocket' should NOT match 'rocketchat-plugin'")
if __name__ == "__main__":
unittest.main()