"""Tests für die Auto-Onboarding-Funktion des Archivar-Moduls.""" import json import os import sys import tempfile import unittest from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch # Füge das plugin-Verzeichnis zum Python-Pfad hinzu sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from archivar.adapter_integration import ArchivarMessageHandler from archivar.room_map import RoomMap, RoomEntry class TestAutoOnboarding(unittest.TestCase): """Testfälle für die Auto-Onboarding-Funktion.""" def setUp(self): """Set up test fixtures before each test method.""" # Erstelle eine temporäre room-map.json für Tests self.temp_dir = tempfile.TemporaryDirectory() self.temp_path = Path(self.temp_dir.name) / "room-map.json" # Mock-Daten für die RoomMap (v2 Schema) self.test_data = { "version": 2, "rooms": { "catchall_room_id": { "name": "#CatchAll", "theme": "Catch-all room for everything else", "keywords_100": [], "keywords_context": [], "catch_all": True } }, "excluded_rooms": [], "fact_store_path": str(self.temp_path.parent / "docs") } # Schreibe die Testdaten in die temporäre Datei with open(self.temp_path, 'w') as f: json.dump(self.test_data, f) def tearDown(self): """Tear down test fixtures after each test method.""" self.temp_dir.cleanup() @patch('archivar.adapter_integration.ROOM_MAP_PATH') def test_single_room_auto_catch_all(self, mock_room_map_path): """Testet die Single-Room-Regel: 1 relevanter Raum → automatisch catch_all.""" mock_room_map_path.return_value = str(self.temp_path) # Erstelle einen ArchivarMessageHandler handler = ArchivarMessageHandler() # Mock die _load_room_map Methode, um unsere Testdaten zu verwenden with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)): handler._room_map = handler._load_room_map() # Simuliere subscribed_rooms mit nur einem relevanten Raum subscribed_rooms = { "single_room_id": {"name": "#SingleRoom", "type": "c"} } # Führe die Prüfung aus missing = handler.check_room_map_completeness(subscribed_rooms) # Es sollten keine fehlenden Räume gemeldet werden (Single-Room-Regel) self.assertEqual(len(missing), 0) # Der Raum sollte automatisch als catch_all hinzugefügt worden sein self.assertIn("single_room_id", handler._room_map.rooms) self.assertTrue(handler._room_map.rooms["single_room_id"].catch_all) @patch('archivar.adapter_integration.ROOM_MAP_PATH') def test_multi_room_onboarding_triggered(self, mock_room_map_path): """Testet dass Onboarding bei mehreren fehlenden Räumen ausgelöst wird.""" mock_room_map_path.return_value = str(self.temp_path) # Erstelle einen ArchivarMessageHandler handler = ArchivarMessageHandler() # Mock die _load_room_map Methode, um unsere Testdaten zu verwenden with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)): handler._room_map = handler._load_room_map() # Simuliere subscribed_rooms mit mehreren relevanten Räumen subscribed_rooms = { "room1_id": {"name": "#Room1", "type": "c"}, "room2_id": {"name": "#Room2", "type": "p"} } # Führe die Prüfung aus missing = handler.check_room_map_completeness(subscribed_rooms) # Es sollten 2 fehlende Räume gemeldet werden self.assertEqual(len(missing), 2) self.assertEqual(missing[0]["room_id"], "room1_id") self.assertEqual(missing[1]["room_id"], "room2_id") @patch('archivar.adapter_integration.ROOM_MAP_PATH') def test_dm_rooms_ignored(self, mock_room_map_path): """Testet dass DM-Räume ignoriert werden (außer Operator-DM).""" mock_room_map_path.return_value = str(self.temp_path) # Erstelle einen ArchivarMessageHandler handler = ArchivarMessageHandler() # Mock die _load_room_map Methode, um unsere Testdaten zu verwenden with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)): handler._room_map = handler._load_room_map() # Simuliere subscribed_rooms mit DM-Räumen subscribed_rooms = { "dm1_id": {"name": "DM mit Bernd", "type": "d"}, "dm2_id": {"name": "DM mit Bernd, Thomas", "type": "d"}, "channel_id": {"name": "#Channel", "type": "c"} } # Führe die Prüfung aus missing = handler.check_room_map_completeness(subscribed_rooms) # Single-Room-Regel: der einzige Channel wird automatisch Catch-All # → keine fehlenden Räume. DMs wurden korrekt ignoriert. self.assertEqual(len(missing), 0) # Verifiziere: der Channel ist jetzt in der Map als Catch-All self.assertIn("channel_id", handler._room_map.rooms) self.assertTrue(handler._room_map.rooms["channel_id"].catch_all) @patch('archivar.adapter_integration.ROOM_MAP_PATH') def test_map_already_complete_no_action(self, mock_room_map_path): """Testet dass nichts passiert wenn die Map bereits vollständig ist.""" mock_room_map_path.return_value = str(self.temp_path) # Erstelle Testdaten mit bereits vorhandenen Räumen test_data_with_rooms = { "version": 2, "rooms": { "catchall_room_id": { "name": "#CatchAll", "theme": "Catch-all room for everything else", "keywords_100": [], "keywords_context": [], "catch_all": True }, "room1_id": { "name": "#Room1", "theme": "First test room", "keywords_100": ["test"], "keywords_context": [], "catch_all": False } }, "excluded_rooms": [], "fact_store_path": str(self.temp_path.parent / "docs") } # Erstelle einen ArchivarMessageHandler handler = ArchivarMessageHandler() # Mock die _load_room_map Methode, um unsere Testdaten zu verwenden with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(test_data_with_rooms)): handler._room_map = handler._load_room_map() # Simuliere subscribed_rooms mit Räumen, die bereits in der Map sind subscribed_rooms = { "room1_id": {"name": "#Room1", "type": "c"} } # Führe die Prüfung aus missing = handler.check_room_map_completeness(subscribed_rooms) # Es sollten keine fehlenden Räume gemeldet werden self.assertEqual(len(missing), 0) class TestAutoOnboardingV2(unittest.TestCase): """v2-spezifische Tests: keywords_100/keywords_context Trennung, File-Lock.""" def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.temp_path = Path(self.temp_dir.name) / "room-map.json" self.test_data = { "version": 2, "rooms": { "catchall_room_id": { "name": "#CatchAll", "theme": "Catch-all room", "keywords_100": [], "keywords_context": [], "catch_all": True } }, "excluded_rooms": [], "fact_store_path": str(self.temp_path.parent / "docs") } with open(self.temp_path, 'w') as f: json.dump(self.test_data, f) def tearDown(self): self.temp_dir.cleanup() def test_v2_add_or_update_room_separate_keywords(self): """Testet dass add_or_update_room keywords_100 und keywords_context trennt.""" room_map = RoomMap._from_dict(self.test_data) room_map.add_or_update_room( room_id="proj_room_id", name="#Projektraum", theme="Entwicklung des Plugins", keywords_100=["plugin", "gateway"], keywords_context=["architektur", "deployment"], catch_all=False, ) entry = room_map.rooms["proj_room_id"] self.assertEqual(entry.keywords_100, ["plugin", "gateway"]) self.assertEqual(entry.keywords_context, ["architektur", "deployment"]) self.assertNotEqual(entry.keywords_100, entry.keywords_context) def test_v2_single_room_auto_catch_all_fields(self): """Testet dass Single-Room-Regel v2-Felder korrekt setzt.""" room_map = RoomMap._from_dict(self.test_data) # Simuliere: nur 1 relevanter Raum, nicht in Map room_map.add_or_update_room( room_id="single_room_id", name="#SingleRoom", theme="Automatisch zugewiesener Catch-All-Raum", keywords_100=[], keywords_context=[], catch_all=True, ) entry = room_map.rooms["single_room_id"] self.assertTrue(entry.catch_all) self.assertEqual(entry.keywords_100, []) self.assertEqual(entry.keywords_context, []) # Altes catch_all (catchall_room_id) sollte NICHT mehr catch_all sein self.assertFalse(room_map.rooms["catchall_room_id"].catch_all) def test_v2_save_with_file_lock(self): """Testet dass RoomMap.save() mit File-Lock funktioniert.""" room_map = RoomMap._from_dict(self.test_data) room_map.add_or_update_room( room_id="test_room_id", name="#TestRaum", theme="Test-Thema", keywords_100=["test"], keywords_context=["versuch"], catch_all=False, ) # Save sollte ohne Exception durchlaufen RoomMap.save(room_map, self.temp_path) # Reload und verifiziere reloaded = RoomMap.load(self.temp_path) entry = reloaded.rooms["test_room_id"] self.assertEqual(entry.name, "#TestRaum") self.assertEqual(entry.theme, "Test-Thema") self.assertEqual(entry.keywords_100, ["test"]) self.assertEqual(entry.keywords_context, ["versuch"]) self.assertFalse(entry.catch_all) def test_v2_reload_updates_in_memory(self): """Testet dass reload() die In-Memory-Daten aktualisiert.""" room_map = RoomMap._from_dict(self.test_data) # Schreibe eine geänderte Map auf Disk modified_data = dict(self.test_data) modified_data["rooms"]["new_room_id"] = { "name": "#NeuerRaum", "theme": "Neues Thema", "keywords_100": ["neu"], "keywords_context": ["frisch"], "catch_all": False, } with open(self.temp_path, 'w') as f: json.dump(modified_data, f) # Vor reload: new_room_id nicht in Map self.assertNotIn("new_room_id", room_map.rooms) # Reload room_map.reload(self.temp_path) # Nach reload: new_room_id in Map self.assertIn("new_room_id", room_map.rooms) entry = room_map.rooms["new_room_id"] self.assertEqual(entry.keywords_100, ["neu"]) self.assertEqual(entry.keywords_context, ["frisch"]) if __name__ == '__main__': unittest.main()