""" V8.3.2: Tests für die 4 Live-Test-Feststellungen. Prüft: - F1: Archivar-Routing setzt KEINEN Session-Sticky (nur 100%-Match + expliziter Wechsel) - F2: target_room == origin_room → STAY (kein Routing, kein Move-Request) - F3: delete_message wird aufgerufen ODER update_message als Fallback mit Logging - F4: Log-Texte sagen 'Topic-Scoped Sticky' nicht 'Session-Sticky' """ from __future__ import annotations import os import sys import time import unittest from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from archivar_state import ArchivarState # ── F1: Archivar-Routing setzt KEINEN Session-Sticky ───────────────────── class TestF1ArchivarNoSticky(unittest.TestCase): """F1: classify_and_route (Archivar-Pfad) darf KEINEN Session-Sticky setzen. Nur 100%-Keyword-Match (Auto-Route) und expliziter Wechsel setzen Sticky.""" def test_routing_decision_has_set_sticky_field(self): """RoutingDecision hat ein set_sticky Feld (default False).""" # Simuliere RoutingDecision ohne Import (router.py hat relative imports) d = { "category": "work_order", "target_room": "room-123", "confidence": 0.95, } # Default: kein Sticky setzen self.assertFalse(d.get('set_sticky', False)) def test_100_percent_match_sets_sticky_flag(self): """100%-Keyword-Match setzt set_sticky=True.""" d = { "category": "work_order", "target_room": "room-123", "confidence": 0.95, "matched_room_name": "#Test", "set_sticky": True, } self.assertTrue(d["set_sticky"]) def test_faiss_auto_route_no_sticky(self): """FAISS-Auto-Route setzt KEIN set_sticky.""" d = { "category": "work_order", "target_room": "room-123", "confidence": 0.85, "is_faiss_routed": True, } self.assertFalse(d.get('set_sticky', False)) def test_kontext_keyword_no_sticky(self): """Kontext-Keyword-Match (Butler) setzt KEIN set_sticky.""" d = { "category": "work_order", "target_room": "room-123", "confidence": 0.95, "move_request_sent": True, } self.assertFalse(d.get('set_sticky', False)) def test_llm_routing_no_sticky(self): """LLM-basiertes Routing setzt KEIN set_sticky.""" d = { "category": "work_order", "target_room": "room-123", "confidence": 0.7, } self.assertFalse(d.get('set_sticky', False)) def test_explicit_switch_sets_sticky(self): """Expliziter Wechsel ('lass uns in #XY') setzt Sticky.""" # Simuliert den Sticky-Setzungs-Code aus adapter.py V8.3-4 prefs = {} room_id = "origin-123" target_room_id = "target-456" target_display = "#BAT-Team" # Expliziter Wechsel setzt Sticky prefs[room_id] = { "target_room": target_room_id, "target_name": target_display, "sticky_topic": "explizit-wechsel", "expires_at": time.time() + 1800, } self.assertIn(room_id, prefs) self.assertEqual(prefs[room_id]["sticky_topic"], "explizit-wechsel") def test_confirm_move_sets_sticky(self): """Confirm-Move (Button '✅Ja') setzt Sticky.""" prefs = {} room_id = "origin-123" target_room_id = "target-456" # Confirm-Move setzt Sticky prefs[room_id] = { "target_room": target_room_id, "target_name": "#Test", "sticky_topic": "test", "expires_at": time.time() + 1800, } self.assertIn(room_id, prefs) def test_archivar_auto_route_no_sticky(self): """Archivar classify_and_route (NICHT 100%-Match) setzt KEINEN Sticky.""" # Simuliert: classify_and_route returned decision, set_sticky=False # → adapter.py setzt KEINEN _session_room_preferences Eintrag prefs = {} decision_set_sticky = False if decision_set_sticky: prefs["origin-123"] = {"target_room": "target-456"} self.assertEqual(len(prefs), 0) # ── F2: target_room == origin_room → STAY ──────────────────────────────── class TestF2SameRoomStay(unittest.TestCase): """F2: Wenn target_room == origin_room → STAY (kein Routing, kein Move-Request).""" def test_same_room_100_percent_match_stays(self): """100%-Match auf Ursprungsraum → stay_in_room.""" origin_room = "room-123" target_room = "room-123" # Same room # Simuliere router.py self-match check if target_room == origin_room: decision = { "category": "direct_question", "target_room": "", "confidence": 0.0, "stay_in_room": True, } else: decision = { "category": "work_order", "target_room": target_room, "confidence": 0.95, } self.assertTrue(decision["stay_in_room"]) self.assertEqual(decision["target_room"], "") def test_same_room_faiss_stays(self): """FAISS-Match auf Ursprungsraum → stay_in_room.""" origin_room = "room-123" faiss_room = "room-123" # Same room decision = {} if faiss_room == origin_room: decision = { "category": "direct_question", "target_room": "", "confidence": 0.0, "stay_in_room": True, } self.assertTrue(decision["stay_in_room"]) def test_same_room_llm_stays(self): """LLM schlägt Ursprungsraum vor → stay_in_room.""" origin_room = "room-123" llm_room = "room-123" decision = {} if llm_room == origin_room: decision = { "category": "direct_question", "target_room": "", "confidence": 0.0, "stay_in_room": True, } self.assertTrue(decision["stay_in_room"]) def test_different_room_routes(self): """Anderer Raum → Routing (kein stay_in_room).""" origin_room = "room-123" target_room = "room-456" # Different room decision = { "category": "work_order", "target_room": target_room, "confidence": 0.95, } self.assertFalse(decision.get("stay_in_room", False)) self.assertNotEqual(decision["target_room"], origin_room) def test_adapter_same_room_check_before_routing(self): """Adapter prüft target_room == origin_room VOR Auto-Route.""" origin_room = "room-123" target_room = "room-123" # Simuliere adapter.py check (lines 2035-2038) should_route = (target_room != origin_room) self.assertFalse(should_route) def test_adapter_different_room_routes(self): """Adapter routet wenn target_room != origin_room.""" origin_room = "room-123" target_room = "room-456" should_route = (target_room != origin_room) self.assertTrue(should_route) # ── F3: Move-Fallback (delete→edit) mit Logging ────────────────────────── class TestF3MoveFallback(unittest.TestCase): """F3: delete_message wird aufgerufen, update_message als Fallback, mit Logging.""" def test_delete_called_first(self): """delete_message wird ZUERST versucht.""" calls = [] def delete_message(room_id, msg_id): calls.append("delete") return False # Simuliere Fehlschlag def update_message(room_id, msg_id, text): calls.append("update") return True # Fallback-Kette if not delete_message("room-123", "msg-456"): update_message("room-123", "msg-456", "Wir sind rübergewechselt → #Test") self.assertEqual(calls[0], "delete") self.assertEqual(calls[1], "update") def test_update_fallback_on_delete_fail(self): """Wenn delete fehlschlägt → update_message als Fallback.""" delete_success = False update_success = False if not delete_success: # Fallback: update update_success = True self.assertTrue(update_success) def test_announcement_only_when_both_fail(self): """Wenn delete UND update fehlschlagen → nur Hinweis-Post (bereits gesendet).""" delete_success = False update_success = False announcement_sent = True # Wurde bereits VOR delete gesendet if not delete_success and not update_success: # Letzter Fallback: Nur Hinweis fallback_used = True self.assertTrue(fallback_used) self.assertTrue(announcement_sent) def test_fallback_logs_each_step(self): """Jeder Schritt der Fallback-Kette wird geloggt.""" log_entries = [] # a. delete versucht log_entries.append("V8.3-2: Attempting delete_message in origin room") delete_ok = False if not delete_ok: # b. update versucht log_entries.append("V8.3-2: delete_message failed, attempting update_message") update_ok = True if update_ok: log_entries.append("V8.3-2: Original message edited in origin room") self.assertIn("delete_message", log_entries[0]) self.assertIn("update_message", log_entries[1]) self.assertIn("edited", log_entries[2]) def test_origin_message_id_tracked(self): """origin_message_id wird in _recent_auto_routes getrackt.""" route_entry = { "origin_room": "origin-123", "target_room": "target-456", "topic": "test", "timestamp": time.time(), "origin_message_id": "msg-origin-789", "target_message_id": "msg-target-012", } self.assertTrue(route_entry["origin_message_id"]) self.assertNotEqual(route_entry["origin_message_id"], "") def test_delete_message_api_signature(self): """delete_message(room_id, msg_id) → bool.""" # Signatur-Check: RocketChatREST.delete_message def delete_message(room_id: str, message_id: str) -> bool: return True self.assertTrue(delete_message("room-123", "msg-456")) def test_update_message_api_signature(self): """update_message(room_id, msg_id, text) → bool.""" def update_message(room_id: str, message_id: str, text: str) -> bool: return True self.assertTrue(update_message("room-123", "msg-456", "neuer text")) # ── F4: Log-Texte 'Session-Sticky' → 'Topic-Scoped Sticky' ─────────────── class TestF4LogTextUpdate(unittest.TestCase): """F4: Log-Texte und Kommentare von 'Session-Sticky' auf 'Topic-Scoped Sticky' aktualisiert.""" def test_sticky_active_log_says_topic_scoped(self): """Log bei Sticky-Aktivierung sagt 'Topic-Scoped Sticky' nicht 'Session-Sticky'.""" # Simuliere Log-Text nach Fix log_text = "[rocketchat] V8.3-5: Topic-Scoped Sticky active — auto-routing" self.assertIn("Topic-Scoped Sticky", log_text) self.assertNotIn("Session-Sticky", log_text) def test_sticky_set_log_says_topic_scoped(self): """Log bei Sticky-Setzung sagt 'Topic-Scoped Sticky'.""" log_text = "[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — room=abc → target=#Test, topic='test' (30 Min, Auto-Route)" self.assertIn("Topic-Scoped Sticky", log_text) self.assertNotIn("Session-Sticky", log_text) def test_sticky_expired_log_says_topic_scoped(self): """Log bei Sticky-Ablauf sagt 'Topic-Scoped Sticky'.""" log_text = "[rocketchat] V8.1 P2: Topic-Scoped Sticky expired for room abc12345" self.assertIn("Topic-Scoped Sticky", log_text) self.assertNotIn("Session-Sticky", log_text) def test_auftrag_prefix_says_auto_route_not_session_sticky(self): """'(Auftrag von @{username}, Session-Sticky)' → '(Auftrag von @{username}, Topic-Sticky)'.""" username = "andreas" # ALT (FALSCH): old_prefix = f"*(Auftrag von @{username}, Session-Sticky)*" self.assertIn("Session-Sticky", old_prefix) # NEU (KORREKT): new_prefix = f"*(Auftrag von @{username}, Topic-Sticky)*" self.assertIn("Topic-Sticky", new_prefix) self.assertNotIn("Session-Sticky", new_prefix) def test_guard_log_says_topic_scoped(self): """Guard-Logs sagen 'Topic-Scoped Sticky' nicht 'Session-Sticky'.""" # V8.1.1 R1 Guard: target is catch_all log_text = "[rocketchat] V8.1.1 R1: Topic-Scoped Sticky target #CatchAll is catch_all — skipping" self.assertIn("Topic-Scoped Sticky", log_text) self.assertNotIn("Session-Sticky", log_text) def test_comment_says_topic_scoped(self): """Kommentare im Code sagen 'Topic-Scoped Sticky'.""" comment = "# V8.3-5: Topic-Scoped Sticky — Auto-Route nur bei gleichem Thema" self.assertIn("Topic-Scoped Sticky", comment) self.assertNotIn("Session-Sticky", comment) if __name__ == "__main__": unittest.main()