""" P0 Integration-Test: Onboarding-Button-Klick setzt Raum-Theme korrekt. ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:'), ohne '::' Suffix. _process_onboarding_response erwartet '::' als Trigger fuer Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler -> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption). Dieser Test verifiziert: 1. ONBOARD:::select_ wird als Button-Klick erkannt 2. _handle_onboarding_button_click wird aufgerufen (nicht interview answer) 3. build_button_attachments produziert korrekte msg-Payloads 4. Backward-compat: 2-Tupel ohne suffix -> msg = prefix """ from __future__ import annotations import asyncio import sys from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # ═══════════════════════════════════════════════════════════════════════════ # Helpers # ═══════════════════════════════════════════════════════════════════════════ def _make_mock_adapter(): """Erzeugt einen minimalen Mock-Adapter mit Onboarding-State.""" from plugin.adapter import RocketChatAdapter adapter = RocketChatAdapter.__new__(RocketChatAdapter) # Grundlegende Attribute adapter._subscribed_rooms = set() adapter._listen_task = None adapter._status_timer = None adapter._last_activity = 0.0 adapter._shutdown_event = MagicMock() 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 adapter._pending_move_requests = {} adapter._session_room_preferences = {} adapter._recent_auto_routes = {} adapter._explicit_switch_sticky = {} adapter._clarify_state = {} adapter._room_map_summary = "" # Mock REST mock_rest = MagicMock() mock_rest.auth_token = "fake-token" mock_rest.user_id = "fake-user-id" mock_rest.post_message = MagicMock(return_value="msg_12345") adapter.rest = mock_rest # Mock Archivar mock_archivar = MagicMock() mock_archivar._room_map = MagicMock() mock_archivar._stats = {"onboarding_active": True} mock_archivar._state = MagicMock() adapter.archivar = mock_archivar # Mock Post-Message adapter._post_message_with_retry = AsyncMock(return_value=True) # Mock _ask_onboarding_question (damit kein echter Rocket.Chat-Call) adapter._ask_onboarding_question = AsyncMock() # Mock _onboarding_next_room adapter._onboarding_next_room = AsyncMock() return adapter # ═══════════════════════════════════════════════════════════════════════════ # Tests: Dispatch-Pfad # ═══════════════════════════════════════════════════════════════════════════ class TestOnboardingButtonClickDispatch: """P0: ONBOARD:::select_ wird als Button-Klick erkannt.""" def test_button_click_with_suffix_starts_interview(self): """ONBOARD:::select_ -> _handle_onboarding_button_click -> Interview wird gestartet (current_room_index=0, current_question=1).""" adapter = _make_mock_adapter() test_rid = "room_test_123" adapter._onboarding_state = { "missing_rooms": [ {"room_id": test_rid, "name": "#Testraum"}, ], "current_room_index": -1, "current_question": 0, "collected_data": {}, "operator_room_id": "dm_operator", "skipped_rooms": [], } # Simuliere Button-Klick mit :: Suffix (der Fix) button_text = f"ONBOARD:{test_rid}::select_{test_rid}" asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator")) state = adapter._onboarding_state assert state["current_room_index"] == 0, ( f"current_room_index sollte 0 sein (Interview gestartet), " f"ist aber {state['current_room_index']}" ) assert state["current_question"] == 1, ( f"current_question sollte 1 sein (Frage 1: Theme), " f"ist aber {state['current_question']}" ) assert test_rid in state["collected_data"], ( f"collected_data sollte Eintrag fuer {test_rid} enthalten" ) adapter._ask_onboarding_question.assert_called_once() def test_button_click_without_suffix_is_silent_noop(self): """ONBOARD: ohne :: -> Fallthrough zu interview answer -> current_q=0 -> early return (stiller No-Op, kein Interview).""" adapter = _make_mock_adapter() test_rid = "room_test_456" adapter._onboarding_state = { "missing_rooms": [ {"room_id": test_rid, "name": "#Bugraum"}, ], "current_room_index": -1, "current_question": 0, "collected_data": {}, "operator_room_id": "dm_operator", "skipped_rooms": [], } # Simuliere Button-Klick OHNE :: Suffix (alter Bug) button_text = f"ONBOARD:{test_rid}" asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator")) state = adapter._onboarding_state # Kein Interview gestartet — stiller No-Op assert state["current_room_index"] == -1, ( f"Ohne :: sollte kein Interview gestartet werden, " f"current_room_index ist {state['current_room_index']}" ) assert state["current_question"] == 0 # _ask_onboarding_question wurde NICHT aufgerufen adapter._ask_onboarding_question.assert_not_called() def test_button_click_without_suffix_corrupts_theme_during_interview(self): """Der eigentliche Bug: Wenn Interview laeuft (current_q=1), wird ONBOARD: ohne :: als Theme-Text interpretiert -> Theme = 'ONBOARD:' (stille Korruption).""" adapter = _make_mock_adapter() test_rid = "room_test_789" adapter._onboarding_state = { "missing_rooms": [ {"room_id": test_rid, "name": "#Korrumpiert"}, ], "current_room_index": 0, "current_question": 1, # Frage 1: Theme "collected_data": { test_rid: {"theme": "", "keywords_100": [], "keywords_context": [], "catch_all": False}, }, "operator_room_id": "dm_operator", "skipped_rooms": [], } # Simuliere Button-Klick OHNE :: Suffix (alter Bug) button_text = f"ONBOARD:{test_rid}" asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator")) # BUG REPRODUZIERT: Theme wurde mit Room-ID als Literal ueberschrieben state = adapter._onboarding_state theme = state["collected_data"][test_rid]["theme"] assert theme == f"ONBOARD:{test_rid}", ( f"BUG REPRODUZIERT: Theme wurde mit '{theme}' ueberschrieben " f"(sollte NICHT die Room-ID als Literal enthalten)" ) def test_button_click_with_suffix_does_not_corrupt_theme(self): """Mit :: Suffix: Button-Klick wird korrekt erkannt, Theme bleibt unberuehrt (wird nicht mit Room-ID ueberschrieben).""" adapter = _make_mock_adapter() test_rid = "room_test_fixed" adapter._onboarding_state = { "missing_rooms": [ {"room_id": test_rid, "name": "#FixTest"}, ], "current_room_index": -1, "current_question": 0, "collected_data": {}, "operator_room_id": "dm_operator", "skipped_rooms": [], } # Simuliere Button-Klick MIT :: Suffix (der Fix) button_text = f"ONBOARD:{test_rid}::select_{test_rid}" asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator")) state = adapter._onboarding_state data = state["collected_data"].get(test_rid, {}) theme = data.get("theme", "") assert theme == "", ( f"Theme sollte leer sein (''), ist aber '{theme}' — " f"Room-ID wurde faelschlich als Theme gesetzt" ) # ═══════════════════════════════════════════════════════════════════════════ # Tests: button_builder Payload # ═══════════════════════════════════════════════════════════════════════════ class TestButtonBuilderPayload: """P0: build_button_attachments produziert korrekte msg-Payloads.""" def test_num_button_with_suffix_produces_double_colon(self): """3-Tupel (label, prefix, suffix) -> msg = 'prefix::suffix'.""" from plugin.archivar.button_builder import build_button_attachments test_rid = "room_bb_test" num_buttons = [ ("Testraum", f"ONBOARD:{test_rid}", f"select_{test_rid}"), ] attachments = build_button_attachments( num_buttons, [], color="#1d74f5", ) num_action = attachments[0]["actions"][0] assert num_action["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}", ( f"num_button msg sollte 'ONBOARD:{test_rid}::select_{test_rid}' sein, " f"ist aber '{num_action['msg']}'" ) def test_special_button_without_suffix_uses_prefix_only(self): """3-Tupel (label, prefix, style) ohne suffix -> msg = prefix (backward-compat).""" from plugin.archivar.button_builder import build_button_attachments special_buttons = [ ("⏭️ Überspringen", "ONBOARD", "default"), ] attachments = build_button_attachments( [], special_buttons, color="#1d74f5", ) special_action = attachments[0]["actions"][0] assert special_action["msg"] == "ONBOARD", ( f"special_button msg sollte 'ONBOARD' sein (backward-compat), " f"ist aber '{special_action['msg']}'" ) def test_two_tuple_backward_compat(self): """2-Tupel (label, prefix) ohne suffix -> msg = prefix (backward-compat).""" from plugin.archivar.button_builder import build_button_attachments num_buttons = [ ("ReviewRaum", "REVIEW_ROOM_EDIT::rid123::edit"), ] attachments = build_button_attachments( num_buttons, [], color="#1d74f5", ) num_action = attachments[0]["actions"][0] assert num_action["msg"] == "REVIEW_ROOM_EDIT::rid123::edit", ( f"2-Tupel msg sollte unveraendert 'REVIEW_ROOM_EDIT::rid123::edit' sein, " f"ist aber '{num_action['msg']}'" ) def test_mixed_buttons(self): """Gemischt: num_buttons mit suffix, special_buttons ohne suffix.""" from plugin.archivar.button_builder import build_button_attachments test_rid = "room_mixed" num_buttons = [ ("Raum A", f"ONBOARD:{test_rid}", f"select_{test_rid}"), ("Raum B", f"ONBOARD:other_rid", f"select_other_rid"), ] special_buttons = [ ("⏭️ Skip", "ONBOARD", "default"), ("⏰ Später", "ONBOARD", "default"), ] attachments = build_button_attachments( num_buttons, special_buttons, color="#1d74f5", ) # Erstes Attachment: num_buttons assert attachments[0]["actions"][0]["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}" assert attachments[0]["actions"][1]["msg"] == "ONBOARD:other_rid::select_other_rid" # Zweites Attachment: special_buttons assert attachments[1]["actions"][0]["msg"] == "ONBOARD" assert attachments[1]["actions"][1]["msg"] == "ONBOARD"