335 lines
13 KiB
Python
335 lines
13 KiB
Python
"""
|
|
Test 03 — Move-Flow: Keyword erkennt Zielraum, Bot sendet Move-Request,
|
|
Button-Klick bestätigt, Nachricht wird in Zielraum kopiert.
|
|
|
|
Räume:
|
|
- Source: test-rc-source (RC_LIVE_SOURCE_ROOM)
|
|
- Target: test-rc-target (RC_LIVE_TARGET_ROOM)
|
|
- Haupt-Testraum: rc-test-automated (RC_LIVE_TEST_ROOM)
|
|
|
|
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. "rocket chat plugin preflight briefing dokumentieren"
|
|
→ #Rocketchat-Plugin). Kein 100%-Keyword enthalten.
|
|
3. Bot sendet Move-Request-Buttons in source_room (butler_mode=cognitive)
|
|
4. Button-Payload "MOVE_REQ:<source_room_id>::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
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import time
|
|
|
|
import pytest
|
|
|
|
from tests.live_rc.conftest import (
|
|
assert_bot_message,
|
|
post_test_message,
|
|
)
|
|
from tests.live_rc.helpers.polling import (
|
|
wait_for_bot_message,
|
|
get_latest_timestamp,
|
|
PollTimeout,
|
|
RateLimitSkip,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Room ID for #Rocketchat-Plugin from room-map.json.
|
|
# No hardcoded fallback — must be set via RC_LIVE_ROCKETCHAT_PLUGIN_ROOM env var.
|
|
# If not set, the test skips cleanly (see _get_env_room_or_skip_plugin_room).
|
|
|
|
|
|
def _get_env_room(name: str) -> str:
|
|
"""Get a room ID from env var, skip test if not set."""
|
|
val = (os.getenv(name) or "").strip()
|
|
if not val:
|
|
pytest.skip(f"{name} not set — skipping move-request test")
|
|
return val
|
|
|
|
|
|
def _get_env_room_or_skip_plugin_room() -> str:
|
|
"""Get the Rocketchat-Plugin room ID from env var, skip if not set."""
|
|
val = (os.getenv("RC_LIVE_ROCKETCHAT_PLUGIN_ROOM") or "").strip()
|
|
if not val:
|
|
pytest.skip(
|
|
"RC_LIVE_ROCKETCHAT_PLUGIN_ROOM not set — "
|
|
"cannot verify copied message in target room. "
|
|
"Set this env var to the room ID of #Rocketchat-Plugin "
|
|
"(or a test mirror room) to run this test."
|
|
)
|
|
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,
|
|
test_room_id: str,
|
|
bot_username: str,
|
|
bot_user_id: str,
|
|
rate_limiter,
|
|
cleanup_messages,
|
|
bot_status_check,
|
|
):
|
|
"""Move-Flow: Bot erkennt Context-Keyword und sendet Move-Request-Buttons.
|
|
|
|
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)
|
|
# Kein hardcoded Fallback — muss via RC_LIVE_ROCKETCHAT_PLUGIN_ROOM gesetzt sein.
|
|
rocket_chat_plugin_room = _get_env_room_or_skip_plugin_room()
|
|
|
|
posted_ids_source: list = []
|
|
posted_ids_target: list = []
|
|
|
|
# ── 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,
|
|
)
|
|
logger.info(
|
|
"Test 03: sent /reset to source room (msg %s) — clearing sticky topics",
|
|
_reset_msg_id[:12],
|
|
)
|
|
# Give the bot 5 seconds to process /reset AND send its response
|
|
# 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 context-keyword message in source room ─────────────
|
|
# Use a context keyword (NOT 100% keyword) to trigger butler mode.
|
|
# All words in this text are only in keywords_context for #Rocketchat-Plugin,
|
|
# none are in keywords_100 — so the bot sends a Move-Request instead of
|
|
# auto-routing. (B-1 fix ensures multi-word keywords_100 like 'hermes-gateway'
|
|
# don't falsely match on single words.)
|
|
keyword_text = (
|
|
"rocket chat plugin preflight briefing dokumentieren"
|
|
)
|
|
|
|
msg_id, source_cursor = post_test_message(
|
|
rc_client, source_room, keyword_text,
|
|
posted_ids_source, rate_limiter,
|
|
)
|
|
logger.info(
|
|
"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 ───────────────
|
|
# 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=120.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 butler_mode is not 'off' and the Archivar is running. "
|
|
f"Context keyword: 'rocket chat plugin preflight briefing dokumentieren'. Error: {e}"
|
|
)
|
|
|
|
move_req_text = move_req_msg.get("msg", "")
|
|
logger.info("Test 03: bot move-request text: '%s'", move_req_text[:200])
|
|
posted_ids_source.append(move_req_msg.get("_id", ""))
|
|
|
|
# ── 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]}'"
|
|
)
|
|
|
|
# ── 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:<source_room_id>::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,
|
|
posted_ids_source, rate_limiter,
|
|
)
|
|
logger.info(
|
|
"Test 03: posted button-click payload '%s' → msg %s",
|
|
button_payload[:60], button_msg_id[:12],
|
|
)
|
|
|
|
# ── Step 5: Wait for copied message in target room ──────────────────
|
|
# The bot posts: "*(Auftrag von @bernd, hierher kopiert)*\n<original text>"
|
|
# in the #Rocketchat-Plugin room.
|
|
try:
|
|
copied_msg = wait_for_bot_message(
|
|
client=rc_client,
|
|
room_id=rocket_chat_plugin_room,
|
|
bot_username=bot_username,
|
|
cursor=target_cursor,
|
|
timeout=120.0,
|
|
rate_limiter=rate_limiter,
|
|
initial_interval=8.0,
|
|
)
|
|
except RateLimitSkip as e:
|
|
pytest.skip(f"Rate limit triggered: {e}")
|
|
except PollTimeout as e:
|
|
pytest.fail(
|
|
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}"
|
|
)
|
|
|
|
copied_text = copied_msg.get("msg", "")
|
|
logger.info("Test 03: copied message in target: '%s'", copied_text[:200])
|
|
posted_ids_target.append(copied_msg.get("_id", ""))
|
|
|
|
# ── 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 '(Auftrag von @...'. "
|
|
f"Got: '{copied_text[:200]}'"
|
|
)
|
|
assert "rocket" in copied_text.lower() or "plugin" in copied_text.lower(), (
|
|
f"Copied message does not contain original keyword 'rocket'/'plugin'. "
|
|
f"Got: '{copied_text[:200]}'"
|
|
)
|
|
|
|
# ── 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",
|
|
)
|
|
|
|
# ── 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)
|
|
except Exception as e:
|
|
logger.warning("Cleanup source: failed to delete %s: %s", mid[:12], e)
|
|
for mid in posted_ids_target:
|
|
try:
|
|
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 button flow OK")
|