diff --git a/tests/live_rc/test_03_move_request.py b/tests/live_rc/test_03_move_request.py index ce5dcc6..18c6635 100644 --- a/tests/live_rc/test_03_move_request.py +++ b/tests/live_rc/test_03_move_request.py @@ -7,23 +7,28 @@ Räume: - Target: test-rc-target (RC_LIVE_TARGET_ROOM) - Haupt-Testraum: rc-test-automated (RC_LIVE_TEST_ROOM) -Test-Szenario: -1. Bernd postet in test-rc-source eine Nachricht mit Keyword 'rocketchat' -2. Bot erkennt Keyword, sendet Move-Request mit Buttons in test-rc-source -3. Bernd sendet Button-Klick-Payload via REST (MOVE_REQ:::confirm_move) -4. Bot kopiert Nachricht nach test-rc-target -5. Bernd liest test-rc-target via channels.history und verifiziert die kopierte Nachricht +Test-Szenario (echter Button-Move-Request-Pfad): +1. /reset an source_room senden (sticky-topic clear) +2. Context-Keyword-Text posten, der einen Room-Match via keywords_context + triggert (z.B. "hermes deployment pipeline" → #Rocketchat-Plugin) +3. Bot sendet Move-Request-Buttons in source_room (butler_mode=cognitive) +4. Button-Payload "MOVE_REQ:::confirm_move" via REST posten +5. Warten auf kopierte Nachricht im Zielraum (#Rocketchat-Plugin) +6. Verifizieren: kopierte Nachricht enthält "(Auftrag von @" + Original-Keyword + +BUTLER-MODE-GUARD: +- Wenn butler_mode=off → pytest.skip mit klarer Meldung. + Der Test verifiziert den echten Button-Move-Request-Pfad, nicht Auto-Route. ENV-Vars: - RC_LIVE_SOURCE_ROOM=6a68c21ddee04395ed6f5415 - RC_LIVE_TARGET_ROOM=6a68c21ddee04395ed6f5419 +- RC_LIVE_ROCKETCHAT_PLUGIN_ROOM (optional, default aus room-map.json) RATE-LIMIT OPTIMIERUNG: - Kein separater get_latest_timestamp für source — nutzt den TS aus post_message - Polling source: initial_interval=5s (statt 2s) - Polling target: timeout=60s, initial_interval=8s -- Auto-Route-Erkennung: wenn Bot auto-routet (100% keyword match), wird - kein Button-Klick simuliert und keine Target-Verifikation erwartet """ from __future__ import annotations @@ -47,6 +52,9 @@ from tests.live_rc.helpers.polling import ( logger = logging.getLogger(__name__) +# Room ID for #Rocketchat-Plugin from room-map.json (fallback if env var not set) +_DEFAULT_ROCKETCHAT_PLUGIN_ROOM = "6a19b0ff02aeecd36b1aa16c" + def _get_env_room(name: str) -> str: """Get a room ID from env var, skip test if not set.""" @@ -56,6 +64,50 @@ def _get_env_room(name: str) -> str: return val +def _get_butler_mode(rc_client) -> str: + """Read butler_mode from env var or detect from bot. + + Priority: + 1. RC_LIVE_BUTLER_MODE env var (explicit override) + 2. Default: 'cognitive' (room_map.py default) + + Returns 'cognitive', 'strict', or 'off'. + """ + env_mode = (os.getenv("RC_LIVE_BUTLER_MODE") or "").strip().lower() + if env_mode in ("cognitive", "strict", "off"): + return env_mode + # Default: cognitive (room_map.py line 192) + return "cognitive" + + +def _has_move_request_indicator(msg: dict) -> bool: + """Check if a bot message contains a move-request indicator. + + Looks for: + - Button attachments (rc-action-block with type=button) + - Text indicators: 'rüber', 'kopieren', 'verschieben', 'move' + """ + text = (msg.get("msg") or "").lower() + + # Text-based indicators + text_indicators = ["rüber", "kopieren", "verschieben", "move"] + if any(ind in text for ind in text_indicators): + return True + + # Button attachment check + attachments = msg.get("attachments", []) + for att in attachments: + if att.get("type") == "rc-action-block": + return True + # Some bots use actionButtons in the attachment + actions = att.get("actions", []) + for action in actions: + if action.get("type") == "button": + return True + + return False + + @pytest.mark.live_rc def test_03_move_request( rc_client, @@ -66,25 +118,43 @@ def test_03_move_request( cleanup_messages, bot_status_check, ): - """Move-Flow: Bot erkennt Move-Request und routet in Zielraum. + """Move-Flow: Bot erkennt Context-Keyword und sendet Move-Request-Buttons. - Steps: - 1. Poste Keyword-Nachricht in Source-Room - 2. Warte auf Move-Request-Buttons vom Bot in Source-Room - 3. Simuliere Button-Klick (MOVE_REQ:::confirm_move) in Source-Room - 4. Warte auf kopierte Nachricht in Target-Room - 5. Verifiziere: kopierte Nachricht enthält Original-Text + Präfix + Verifiziert den echten Button-Move-Request-Pfad: + 1. Context-Keyword triggert Butler-Mode (nicht 100%-Auto-Route) + 2. Bot sendet Move-Request-Buttons im Source-Room + 3. Button-Klick (confirm_move) kopiert Nachricht in Zielraum + 4. Zielraum enthält kopierte Nachricht mit "(Auftrag von @..."-Präfix + + BUTLER-MODE-GUARD: Wenn butler_mode=off, wird der Test mit einer + klaren Meldung geskippt — der Button-Pfad ist dann nicht verfügbar. """ source_room = _get_env_room("RC_LIVE_SOURCE_ROOM") target_room = _get_env_room("RC_LIVE_TARGET_ROOM") + # Zielraum für die Kopie: #Rocketchat-Plugin (aus room-map.json) + rocket_chat_plugin_room = ( + os.getenv("RC_LIVE_ROCKETCHAT_PLUGIN_ROOM") or _DEFAULT_ROCKETCHAT_PLUGIN_ROOM + ).strip() + posted_ids_source: list = [] posted_ids_target: list = [] - # Pre-step: Send /reset to clear sticky topics from previous tests. - # Previous tests (test_02, etc.) may have set a sticky topic on - # rc-test-automated, which would cause the bot to auto-route there - # instead of test-rc-target. /reset clears all sticky state. + # ── Butler-Mode-Guard ────────────────────────────────────────────── + # Wenn butler_mode=off, kann der Bot keine Move-Request-Buttons senden. + # Der Test soll dann sauber skippen, nicht failen. + butler_mode = _get_butler_mode(rc_client) + if butler_mode == "off": + pytest.skip( + "butler_mode=off — kein Button-Move-Request möglich. " + "Der Test verifiziert den echten Button-Pfad, nicht Auto-Route. " + "Setze butler_mode=cognitive oder strict um den Test auszuführen." + ) + + # ── Pre-step: /reset an source_room senden ───────────────────────── + # Clear sticky topics from previous tests. Previous tests (test_02, etc.) + # may have set a sticky topic that would cause auto-routing instead of + # butler mode. _reset_msg_id, _ = post_test_message( rc_client, source_room, "/reset", posted_ids_source, rate_limiter, @@ -94,115 +164,77 @@ def test_03_move_request( _reset_msg_id[:12], ) # Give the bot 5 seconds to process /reset AND send its response - # before posting the keyword. The /reset response ("Konversation - # zurückgesetzt...") must arrive BEFORE the keyword post so that - # source_cursor (from the keyword post_message return) sits AFTER - # the /reset response. Otherwise wait_for_bot_message picks up the - # /reset response as a "move-request" and the assertion fails. + # before posting the keyword. The /reset response must arrive BEFORE + # the keyword post so that source_cursor sits AFTER the /reset response. time.sleep(5.0) - # Step 1: Post keyword message in source room. - # SKIP separate get_latest_timestamp — use the timestamp from post_message - # as cursor. Saves one channels.history API call. - keyword_text = "rocketchat Test Move-Request — bitte in den Zielraum routen" + # ── Step 1: Post context-keyword message in source room ───────────── + # Use a context keyword (NOT 100% keyword) to trigger butler mode. + # "hermes" + "deployment" are keywords_context for #Rocketchat-Plugin. + # 100% keywords like "rocketchat" would auto-route (move_request_sent=False). + keyword_text = ( + "hermes deployment pipeline — bitte in den Rocketchat-Plugin-Raum routen" + ) msg_id, source_cursor = post_test_message( rc_client, source_room, keyword_text, posted_ids_source, rate_limiter, ) logger.info( - "Test 03: posted keyword message %s in source room (cursor=%s)", + "Test 03: posted context-keyword message %s in source room (cursor=%s)", msg_id[:12], source_cursor[:19], ) - # Step 2: Wait for bot to send move-request buttons in source room. - # Use initial_interval=5s to reduce API call density (was 2s). + # ── Step 2: Wait for bot to send move-request buttons ─────────────── + # Use initial_interval=5s to reduce API call density. try: move_req_msg = wait_for_bot_message( client=rc_client, room_id=source_room, bot_username=bot_username, cursor=source_cursor, - timeout=30.0, # Archivar needs time to classify + send buttons + timeout=30.0, rate_limiter=rate_limiter, initial_interval=5.0, ) except RateLimitSkip as e: pytest.skip(f"Rate limit triggered: {e}") except PollTimeout as e: + # Check if butler_mode is actually off (runtime check) pytest.fail( f"Bot did not send move-request buttons in source room within 30s. " - f"Check that the Archivar is running and the keyword 'rocketchat' " - f"matches the target room. Error: {e}" + f"Check that butler_mode is not 'off' and the Archivar is running. " + f"Context keyword: 'hermes deployment pipeline'. Error: {e}" ) move_req_text = move_req_msg.get("msg", "") - logger.info("Test 03: bot move-request text: '%s'", move_req_text[:120]) + logger.info("Test 03: bot move-request text: '%s'", move_req_text[:200]) posted_ids_source.append(move_req_msg.get("_id", "")) - # Verify the bot response is a valid routing action. - # Two valid forms: - # A) Move-Request with buttons (Butler mode): contains "kopieren" or "rüber" - # B) Auto-Route announcement (100% keyword / FAISS): contains "wechseln", - # "thema", "sehe dich", "move", "raum", or the target room name. - # Both are valid routing behaviors — the bot either asks for confirmation - # (Butler) or auto-routes with an announcement. - _routing_keywords = [ - "kopieren", "rüber", "wechseln", "thema", "sehe dich", - "move", "raum", "rüberkopieren", "wechsel", - ] - _has_routing_keyword = any(kw in move_req_text.lower() for kw in _routing_keywords) - _has_target_room = ( - "rc-test-automated" in move_req_text.lower() - or "test-rc-target" in move_req_text.lower() - ) - assert _has_routing_keyword or _has_target_room, ( - f"Bot response is neither a move-request nor an auto-route announcement. " - f"Expected routing keywords ({_routing_keywords}) or target room name. " + # ── Assertion A: Move-Request-Indikator ──────────────────────────── + # The bot response must contain a move-request indicator: + # either button attachments or text like "rüber"/"kopieren"/"verschieben" + assert _has_move_request_indicator(move_req_msg), ( + f"Bot response is not a move-request. " + f"Expected button attachment or text indicator " + f"('rüber'/'kopieren'/'verschieben'/'move'). " f"Got: '{move_req_text[:200]}'" ) - # AUFGABE 4: Detect auto-route vs. button-move-request. - # Auto-route keywords: "wechseln", "sehe dich", "thema" — bot already - # routed the message, no button click needed, no copy to target expected. - # PRIORITY: auto-route keywords take precedence over button keywords - # and attachments. An auto-route announcement may have a room link card - # (attachment), but it's still an auto-route — skip immediately. - _auto_route_keywords = ["wechseln", "sehe dich", "thema"] - _is_auto_route = any(kw in move_req_text.lower() for kw in _auto_route_keywords) - - if _is_auto_route: - # Bot auto-routed (100% keyword match) — no button click needed, - # no copy to target expected. This is valid bot behavior. - # Also check if the auto-route target is NOT test-rc-target - # (sticky topic from previous tests may point elsewhere). - _target_is_wrong = ( - "rc-test-automated" in move_req_text.lower() - and "test-rc-target" not in move_req_text.lower() - ) - if _target_is_wrong: - logger.info( - "Test 03: Bot auto-routed to rc-test-automated (sticky topic " - "from previous test) — not test-rc-target" - ) - pytest.skip( - "Bot has sticky topic on rc-test-automated from previous test. " - "Run /reset in source room before test_03 to clear sticky topics." - ) - logger.info( - "Test 03: Bot auto-routed (100%% keyword match) — " - "no button click needed, skipping target verification" - ) - pytest.skip( - "Bot auto-routed (100% keyword match), no copy to target expected" - ) - - # Step 3: Simulate button click — post MOVE_REQ:::confirm_move - # This is the payload the bot's native button sends when clicked. - # The adapter parses it at line 2395-2396 and routes to confirm_move handler. - target_cursor = get_latest_timestamp(rc_client, target_room, rate_limiter=rate_limiter) - logger.info("Test 03: target cursor = %s", target_cursor[:19]) + # ── Step 3: Get target cursor BEFORE posting button payload ──────── + # The copy lands in #Rocketchat-Plugin room, not test-rc-target. + # We use the rocket_chat_plugin_room for verification. + target_cursor = get_latest_timestamp( + rc_client, rocket_chat_plugin_room, rate_limiter=rate_limiter + ) + logger.info( + "Test 03: target cursor (Rocketchat-Plugin room) = %s", + target_cursor[:19], + ) + # ── Step 4: Simulate button click — post MOVE_REQ payload ────────── + # Format: MOVE_REQ:::confirm_move + # "confirm_move" maps to "✅Ja" (rüberkopieren) in adapter.py:2494 button_payload = f"MOVE_REQ:{source_room}::confirm_move" button_msg_id, _ = post_test_message( rc_client, source_room, button_payload, @@ -213,15 +245,13 @@ def test_03_move_request( button_payload[:60], button_msg_id[:12], ) - # Step 4: Wait for copied message in target room. + # ── Step 5: Wait for copied message in target room ────────────────── # The bot posts: "*(Auftrag von @bernd, hierher kopiert)*\n" - # Use timeout=60s and initial_interval=8s to reduce API call density. - # The 429 retry in rc_rest.py now has 5 retries (71s total), so a single - # 429 on the target room won't kill the test. + # in the #Rocketchat-Plugin room. try: copied_msg = wait_for_bot_message( client=rc_client, - room_id=target_room, + room_id=rocket_chat_plugin_room, bot_username=bot_username, cursor=target_cursor, timeout=60.0, @@ -232,8 +262,8 @@ def test_03_move_request( pytest.skip(f"Rate limit triggered: {e}") except PollTimeout as e: pytest.fail( - f"Bot did not copy message to target room within 60s. " - f"Check that the bot is subscribed to the target room and " + f"Bot did not copy message to Rocketchat-Plugin room within 60s. " + f"Check that the bot is subscribed to the room and " f"the move-request handler is working. Error: {e}" ) @@ -241,24 +271,39 @@ def test_03_move_request( logger.info("Test 03: copied message in target: '%s'", copied_text[:200]) posted_ids_target.append(copied_msg.get("_id", "")) - # Step 5: Verify the copied message - # Should contain the prefix and the original keyword text + # ── Assertion B: Copied message has correct prefix + keyword ─────── assert "Auftrag von" in copied_text or "hierher kopiert" in copied_text, ( - f"Copied message missing move prefix. Got: '{copied_text[:200]}'" + f"Copied message missing move prefix '(Auftrag von @...'. " + f"Got: '{copied_text[:200]}'" ) - assert "rocketchat" in copied_text.lower(), ( - f"Copied message does not contain original keyword 'rocketchat'. " + assert "hermes" in copied_text.lower(), ( + f"Copied message does not contain original keyword 'hermes'. " f"Got: '{copied_text[:200]}'" ) - # Verify message ownership + # ── Assertion C: Message ownership ───────────────────────────────── + assert_bot_message( + move_req_msg, + expected_username=bot_username, + context="test_03_move_request_source", + ) assert_bot_message( copied_msg, expected_username=bot_username, context="test_03_move_request_target", ) - # Cleanup: delete messages from both rooms + # ── Assertion D: Cursor-Trennung ──────────────────────────────────── + # The target message must be strictly after the source cursor, + # otherwise it's from a previous test session. + copied_ts = copied_msg.get("ts", "") + assert copied_ts > target_cursor, ( + f"Target message timestamp {copied_ts[:19]} is not after " + f"target_cursor {target_cursor[:19]} — message may be from " + f"a previous test session" + ) + + # ── Cleanup ──────────────────────────────────────────────────────── for mid in posted_ids_source: try: rc_client.delete_message(source_room, mid) @@ -266,8 +311,8 @@ def test_03_move_request( logger.warning("Cleanup source: failed to delete %s: %s", mid[:12], e) for mid in posted_ids_target: try: - rc_client.delete_message(target_room, mid) + rc_client.delete_message(rocket_chat_plugin_room, mid) except Exception as e: logger.warning("Cleanup target: failed to delete %s: %s", mid[:12], e) - logger.info("Test 03 PASSED: move-request flow OK") + logger.info("Test 03 PASSED: move-request button flow OK")