""" Tests für das RoomMap-Datenmodell. Prüft: - Laden und Validieren von room-map.json - Keyword-Matching - Validierungsfehler (0/2 Catch-All, excluded_rooms) - Legacy-Env-Var-Migration """ from __future__ import annotations import json import os import tempfile from pathlib import Path import pytest # Ensure the archivar package is importable import sys sys.path.insert(0, str(Path(__file__).resolve().parents[3])) from plugin.archivar.room_map import ( RoomMap, RoomEntry, RoomMapValidationError, _migrate_from_env_vars, ) # ── Helpers ──────────────────────────────────────────────────────────────── def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None = None) -> str: """Create a minimal valid room-map.json as a string.""" data: dict = { "version": 1, "rooms": {}, "excluded_rooms": excluded or [], "fact_store_path": "/tmp/test_docs", } for room in (rooms or []): data["rooms"][room["room_id"]] = { "name": room["name"], "theme": room.get("theme", ""), "keywords": room.get("keywords", []), "catch_all": room.get("catch_all", False), } return json.dumps(data) def _tmp_map(content: str) -> Path: """Write content to a temp file and return its Path.""" tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8") tmp.write(content) tmp.close() return Path(tmp.name) # ── Basic Loading ────────────────────────────────────────────────────────── class TestRoomMapLoad: """RoomMap.load() — basic loading.""" def test_load_valid_map(self): """Load a map with 3 rooms, 1 catch-all, 1 excluded.""" json_str = _make_map_json( rooms=[ {"room_id": "r1", "name": "#Dev", "theme": "dev room", "keywords": ["code", "bug"]}, {"room_id": "r2", "name": "#Ops", "theme": "ops room", "keywords": ["server", "docker"]}, {"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ], excluded=["rx99"], ) path = _tmp_map(json_str) try: rm = RoomMap.load(path) assert rm.version == 1 assert len(rm.rooms) == 3 assert rm.catch_all_room is not None assert rm.catch_all_room.room_id == "r3" assert "rx99" in rm.excluded_room_ids assert str(rm.fact_store_path) == "/tmp/test_docs" finally: path.unlink(missing_ok=True) def test_load_empty_rooms(self): """Map with no rooms — should load but fail validation.""" json_str = _make_map_json(rooms=[]) path = _tmp_map(json_str) try: rm = RoomMap.load(path) assert len(rm.rooms) == 0 # Validation should raise with pytest.raises(RoomMapValidationError, match="No catch_all"): rm.validate() finally: path.unlink(missing_ok=True) def test_load_file_not_found(self): """Missing file should raise FileNotFoundError.""" with pytest.raises(FileNotFoundError): RoomMap.load(Path("/tmp/nonexistent_room_map_2026.json")) # ── Keyword Matching ─────────────────────────────────────────────────────── class TestRoomMapKeywords: """RoomMap.find_room_by_keywords() tests.""" @pytest.fixture def room_map(self) -> RoomMap: json_str = _make_map_json( rooms=[ {"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]}, {"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]}, {"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ], ) path = _tmp_map(json_str) try: return RoomMap.load(path) finally: path.unlink(missing_ok=True) def test_keyword_match_plugin(self, room_map): """Plugin keywords should match #Plugin room.""" result = room_map.find_room_by_keywords("Das Plugin hat einen Gateway-Bug") assert result is not None assert result.name == "#Plugin" def test_keyword_match_bat(self, room_map): """BAT keywords should match #BAT room.""" result = room_map.find_room_by_keywords("Das Docker-Image für Trading ist kaputt") assert result is not None assert result.name == "#BAT" def test_keyword_multiple_matches(self, room_map): """Most matching keywords wins.""" # "gateway" matches both Plugin and BAT, but "plugin" gives Plugin an edge result = room_map.find_room_by_keywords("gateway plugin trading") assert result is not None assert result.name == "#Plugin" # plugin + gateway = 2 vs trading = 1 def test_no_keyword_match(self, room_map): """No keywords should return None.""" result = room_map.find_room_by_keywords("Hallo wie gehts") assert result is None def test_catch_all_never_matches_keywords(self, room_map): """Catch-all room has no keywords, never returned.""" result = room_map.find_room_by_keywords("irgendwas") assert result is None # Not the catch-all def test_keyword_case_insensitive(self, room_map): """Keywords are case-insensitive.""" result = room_map.find_room_by_keywords("PLUGIN ADAPTER") assert result is not None assert result.name == "#Plugin" # ── Exclusion ────────────────────────────────────────────────────────────── class TestRoomMapExclusion: """Room exclusion tests.""" def test_excluded_room(self): json_str = _make_map_json( rooms=[ {"room_id": "r1", "name": "#Bot-Room", "theme": "multi-agent", "keywords": []}, {"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ], excluded=["r1"], ) path = _tmp_map(json_str) try: rm = RoomMap.load(path) assert rm.is_excluded("r1") is True assert rm.is_excluded("admin") is False assert rm.is_excluded("nonexistent") is False finally: path.unlink(missing_ok=True) # ── Validation ───────────────────────────────────────────────────────────── class TestRoomMapValidation: """RoomMap.validate() tests.""" def _load(self, rooms: list[dict], excluded: list[str] | None = None) -> RoomMap: json_str = _make_map_json(rooms=rooms, excluded=excluded) path = _tmp_map(json_str) try: return RoomMap.load(path) finally: path.unlink(missing_ok=True) def test_no_catch_all(self): """0 catch-all rooms → RoomMapValidationError.""" rm = self._load([ {"room_id": "r1", "name": "#A", "theme": "A"}, {"room_id": "r2", "name": "#B", "theme": "B"}, ]) with pytest.raises(RoomMapValidationError, match="No catch_all"): rm.validate() def test_two_catch_all(self): """2 catch-all rooms → RoomMapValidationError.""" rm = self._load([ {"room_id": "r1", "name": "#A", "theme": "A", "keywords": [], "catch_all": True}, {"room_id": "r2", "name": "#B", "theme": "B", "keywords": [], "catch_all": True}, ]) with pytest.raises(RoomMapValidationError, match="Multiple catch_all"): rm.validate() def test_catch_all_in_excluded(self): """Catch-all in excluded_rooms → RoomMapValidationError.""" rm = self._load( rooms=[ {"room_id": "r1", "name": "#Excluded", "theme": "bad", "keywords": [], "catch_all": True}, ], excluded=["r1"], ) with pytest.raises(RoomMapValidationError, match="excluded_rooms"): rm.validate() def test_valid_map_with_subscriptions(self): """Valid map with subscribed room IDs — no errors.""" rm = self._load([ {"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []}, {"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ]) errors = rm.validate(subscribed_ids={"r1", "admin"}) assert errors == [] def test_room_not_subscribed_warning(self): """Room not in subscribed_ids → non-fatal warning.""" rm = self._load([ {"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []}, {"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ]) errors = rm.validate(subscribed_ids={"admin"}) # r1 not subscribed assert len(errors) >= 1 assert any("not in subscribed" in e for e in errors) def test_catch_all_not_subscribed_warning(self): """Catch-all not in subscribed_ids → warning (not fatal).""" rm = self._load([ {"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True}, ]) errors = rm.validate(subscribed_ids={"r999"}) assert len(errors) >= 1 assert any("catch_all room" in e.lower() for e in errors) # ── Migration from Legacy Env Vars ───────────────────────────────────────── class TestMigrationFromEnvVars: """_migrate_from_env_vars() tests.""" def teardown_method(self): """Clean up env vars after each test.""" for key in list(os.environ): if key.startswith("ARCHIVAR_"): del os.environ[key] def test_no_env_vars(self): """No legacy env vars → None.""" assert _migrate_from_env_vars() is None def test_with_catchall_only(self): """ARCHIVAR_CATCHALL_ROOM set → catch-all in migrated map.""" os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall" result = _migrate_from_env_vars() assert result is not None assert "room_catchall" in result["rooms"] assert result["rooms"]["room_catchall"]["catch_all"] is True def test_with_multiple_rooms(self): """Multiple legacy vars → all rooms in migrated map.""" os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall" os.environ["ARCHIVAR_ALARM_ROOM"] = "room_alarm" os.environ["ARCHIVAR_FRAGE_ROOM"] = "room_frage" result = _migrate_from_env_vars() assert result is not None assert len(result["rooms"]) >= 3 def test_alarm_same_as_catchall_not_duplicated(self): """If ALARM_ROOM == CATCHALL_ROOM, don't create duplicate.""" os.environ["ARCHIVAR_CATCHALL_ROOM"] = "same_room" os.environ["ARCHIVAR_ALARM_ROOM"] = "same_room" result = _migrate_from_env_vars() assert result is not None # Should only have one entry for "same_room" with catch_all=True assert "same_room" in result["rooms"] assert result["rooms"]["same_room"]["catch_all"] is True def test_project_rooms(self): """ARCHIVAR_PROJECT_ROOMS JSON → project rooms in migrated map.""" os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_admin" os.environ["ARCHIVAR_PROJECT_ROOMS"] = '{"plugin": "r_plugin", "bat": "r_bat"}' result = _migrate_from_env_vars() assert result is not None assert "r_plugin" in result["rooms"] assert "r_bat" in result["rooms"] # ── RoomEntry ────────────────────────────────────────────────────────────── class TestRoomEntry: """RoomEntry dataclass tests.""" def test_match_score(self): entry = RoomEntry( room_id="r1", name="#Dev", theme="dev", keywords=["plugin", "gateway", "adapter"], ) assert entry.match_score("Das Plugin braucht einen Gateway-Fix") == 2 assert entry.match_score("Der Adapter ist kaputt") == 1 assert entry.match_score("Hallo Welt") == 0 def test_match_score_no_keywords(self): entry = RoomEntry( room_id="admin", name="DM Admin", theme="admin", keywords=[], catch_all=True, ) assert entry.match_score("irgendwas") == 0 def test_match_score_case_insensitive(self): entry = RoomEntry( room_id="r1", name="#Dev", theme="dev", keywords=["Plugin", "GATEWAY"], ) assert entry.match_score("plugin gateway") == 2