feat: REST-basierte Live-Test-Harness für RC-Plugin

Implementiert die vollständige Test-Harness für Rocket.Chat Live-Tests
von .101 (Bernd) gegen .45 (MyTestBot) via REST API.

ARCHITEKTUR:
- tests/live_rc/conftest.py: Fixtures, Marker, Skip-Logik, Self-Check,
  Token-Bucket-Rate-Limiter (60 calls/min), Suite-Lock (/tmp/rc-live-tests.lock),
  Cleanup-Fixture, Message-Ownership-Assert, Bot-Status-Check
- helpers/rc_rest.py: REST-Client-Wrapper (post, history, users.info, self-check)
- helpers/polling.py: Cursor-basiertes Polling mit Rate-Limiter-Integration
  und exponentiellen Backoff bei HTTP 429

TESTS:
- test_01_echo.py: Smoke-Test — Bot antwortet auf einfache Nachricht
- test_02_button_click.py: ::-Text als Button-Klick-Simulation (E3)
- test_03-06: Skeletons mit @pytest.mark.skip

VERIFIZIERT:
- Ohne Env-Variablen: komplettes SKIP, keine Fehler
- Mit Env-Variablen + Bot im Onboarding: SKIP mit klarer Diagnose
- Rate-Limiter verhindert HTTP 429 (vorher: 100% Fehlerrate)
- Self-Check validiert Token/User-Identity vor jedem Lauf
- Suite-Lock verhindert parallele Läufe
This commit is contained in:
Bernd (Hermes)
2026-07-28 13:12:52 +02:00
parent aefdad0024
commit 6a09caa1e5
11 changed files with 1047 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Live RC test helpers."""
+158
View File
@@ -0,0 +1,158 @@
"""
Cursor-based polling for bot responses in Rocket.Chat live tests.
Waits for a message from a specific user (the bot) to appear in a room's
history after a given cursor timestamp. Uses progressive backoff with
rate limiting: 1s → 1s → 2s → 2s → 3s → 3s, max 12s total.
Rate limiter integration: each channels.history call acquires a token
from the rate limiter to stay under RC's 60 calls/minute limit.
"""
from __future__ import annotations
import logging
import time
from typing import Optional
from .rc_rest import RCRestClient
logger = logging.getLogger(__name__)
# Progressive backoff intervals in seconds (rate-limiter-friendly)
# With 60 calls/min rate limit, we can do ~1 call/sec. These intervals
# give RC breathing room while still polling reasonably fast.
_BACKOFF_INTERVALS = [1.0, 1.0, 2.0, 2.0, 3.0, 3.0]
_MAX_TOTAL_WAIT = 12.0 # seconds
class PollTimeout(Exception):
"""Raised when the bot does not respond within the timeout."""
def wait_for_bot_message(
client: RCRestClient,
room_id: str,
bot_username: str,
cursor: str,
timeout: float = _MAX_TOTAL_WAIT,
rate_limiter=None,
) -> dict:
"""Poll channels.history until a message from bot_username appears.
Uses the cursor (ISO timestamp) to only look at messages newer than
the test message that was just posted.
Rate limiting: if a rate_limiter is provided, each API call acquires
a token first. On HTTP 429 errors, uses exponential backoff.
Args:
client: Authenticated RCRestClient instance.
room_id: The room to poll.
bot_username: The bot's username (case-insensitive match).
cursor: ISO timestamp — only messages after this time are considered.
timeout: Maximum total wait time in seconds (default 12s).
rate_limiter: Optional RateLimiter instance for API call throttling.
Returns:
The first message dict from bot_username found after cursor.
Raises:
PollTimeout: If no bot message appears within timeout.
"""
deadline = time.monotonic() + timeout
interval_idx = 0
consecutive_429 = 0
while time.monotonic() < deadline:
# Rate-limit before API call
if rate_limiter is not None:
rate_limiter.acquire()
try:
messages = client.get_history(
room_id=room_id,
count=10,
oldest=cursor,
)
consecutive_429 = 0 # reset on success
except Exception as e:
error_str = str(e)
if "429" in error_str:
consecutive_429 += 1
# Exponential backoff on rate-limit errors
backoff = min(2 ** consecutive_429, 16) # 2s, 4s, 8s, 16s max
logger.warning(
"Poll: HTTP 429 (consecutive=%d) — backing off %ds",
consecutive_429, backoff,
)
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(backoff, remaining))
continue
else:
logger.warning("Poll: history fetch failed (will retry): %s", e)
messages = []
for msg in messages:
ts = msg.get("ts", "")
# Only consider messages strictly after cursor
if ts <= cursor:
continue
u = msg.get("u", {})
username = (u.get("username", "") or "").lower()
if username == bot_username.lower():
logger.info(
"Poll: found bot message %s after %.1fs",
msg.get("_id", "")[:12],
time.monotonic() - (deadline - timeout),
)
return msg
# Progressive backoff
if interval_idx < len(_BACKOFF_INTERVALS):
delay = _BACKOFF_INTERVALS[interval_idx]
interval_idx += 1
else:
delay = 3.0
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(delay, remaining))
raise PollTimeout(
f"Bot '{bot_username}' did not respond in room {room_id[:12]} "
f"within {timeout}s (cursor={cursor[:19]})"
)
def get_latest_timestamp(
client: RCRestClient,
room_id: str,
rate_limiter=None,
) -> str:
"""Get the timestamp of the most recent message in a room.
Used as a cursor before posting a test message — ensures we only
look at messages that appear AFTER our post.
Args:
client: Authenticated RCRestClient instance.
room_id: The room ID.
rate_limiter: Optional RateLimiter instance.
Returns:
ISO timestamp string, or "1970-01-01T00:00:00.000Z" if room is empty.
"""
if rate_limiter is not None:
rate_limiter.acquire()
try:
messages = client.get_history(room_id=room_id, count=1)
except Exception:
return "1970-01-01T00:00:00.000Z"
if messages:
return messages[0].get("ts", "1970-01-01T00:00:00.000Z")
return "1970-01-01T00:00:00.000Z"
+206
View File
@@ -0,0 +1,206 @@
"""
REST Client Wrapper for Rocket.Chat Live Tests.
Provides a clean Python interface to the Rocket.Chat REST API
for the test harness running on .101 (Bernd).
Zero external dependencies — stdlib only.
"""
from __future__ import annotations
import json
import logging
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
class RCRestError(Exception):
"""Raised when the RC REST API returns an error."""
class RCRestClient:
"""Thin wrapper around Rocket.Chat REST API for test automation.
Authenticates via personal access token (X-Auth-Token + X-User-Id headers).
"""
def __init__(self, base_url: str, auth_token: str, user_id: str):
self.base_url = base_url.rstrip("/")
self.auth_token = auth_token
self.user_id = user_id
# ── Low-level request ──────────────────────────────────────────────
def _request(
self,
method: str,
endpoint: str,
data: Optional[dict] = None,
) -> dict:
"""Send an authenticated request to the RC REST API.
Returns:
Parsed JSON response dict.
Raises:
RCRestError: On HTTP errors or connection failures.
"""
url = f"{self.base_url}{endpoint}"
headers = {
"X-Auth-Token": self.auth_token,
"X-User-Id": self.user_id,
}
body = None
if data is not None:
headers["Content-Type"] = "application/json"
body = json.dumps(data).encode("utf-8")
req = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
raise RCRestError(
f"HTTP {e.code} on {method} {endpoint}: {e.reason}"
) from e
except Exception as e:
raise RCRestError(
f"Connection error on {method} {endpoint}: {e}"
) from e
# ── Public API ─────────────────────────────────────────────────────
def self_check(self) -> dict:
"""Verify that the configured token matches the user identity.
Calls users.info?username=bernd and compares the returned _id
with the configured X-User-Id header.
Returns:
{"ok": True, "user_id": "...", "username": "..."} on success.
Raises:
RCRestError: If the token is invalid or user IDs don't match.
"""
# Use users.info with userId parameter (more reliable than username lookup)
r = self._request(
"GET",
f"/api/v1/users.info?userId={self.user_id}",
)
if not r.get("success"):
raise RCRestError(
f"Self-check failed: users.info returned success=false. "
f"Token may be invalid."
)
user = r.get("user", {})
returned_id = user.get("_id", "")
if returned_id != self.user_id:
raise RCRestError(
f"Self-check FAILED: X-User-Id={self.user_id} but "
f"users.info returned _id={returned_id}. "
f"Token/user mismatch — ABORT."
)
return {
"ok": True,
"user_id": returned_id,
"username": user.get("username", "unknown"),
}
def post_message(self, room_id: str, text: str) -> str:
"""Post a message to a room.
Args:
room_id: The room ID to post to.
text: The message text.
Returns:
The message _id from the API response.
Raises:
RCRestError: On API failure.
"""
r = self._request(
"POST",
"/api/v1/chat.postMessage",
data={"roomId": room_id, "text": text},
)
if not r.get("success"):
raise RCRestError(
f"chat.postMessage failed: {r.get('error', 'unknown error')}"
)
msg = r.get("message", {})
msg_id = msg.get("_id", "")
logger.info("Posted message %s to room %s", msg_id[:12], room_id[:12])
return msg_id
def get_history(
self,
room_id: str,
count: int = 20,
oldest: Optional[str] = None,
latest: Optional[str] = None,
) -> List[dict]:
"""Fetch recent messages from a room via channels.history.
Args:
room_id: The room ID.
count: Number of messages to fetch (max 100).
oldest: ISO timestamp — only messages AFTER this time.
latest: ISO timestamp — only messages BEFORE this time.
Returns:
List of message objects (sorted oldest→newest by RC).
"""
params = [f"roomId={room_id}", f"count={min(count, 100)}"]
if oldest:
params.append(f"oldest={oldest}")
if latest:
params.append(f"latest={latest}")
query = "&".join(params)
r = self._request("GET", f"/api/v1/channels.history?{query}")
if not r.get("success"):
raise RCRestError(
f"channels.history failed: {r.get('error', 'unknown error')}"
)
return r.get("messages", [])
def get_room_info(self, room_id: str) -> dict:
"""Get room information via channels.info."""
r = self._request(
"GET",
f"/api/v1/channels.info?roomId={room_id}",
)
if not r.get("success"):
raise RCRestError(
f"channels.info failed: {r.get('error', 'unknown error')}"
)
return r.get("channel", {})
def delete_message(self, room_id: str, message_id: str) -> bool:
"""Delete a message via chat.delete.
Returns True on success.
"""
r = self._request(
"POST",
"/api/v1/chat.delete",
data={"roomId": room_id, "msgId": message_id},
)
return bool(r.get("success"))
def get_user_info(self, username: str) -> dict:
"""Get user info by username."""
r = self._request(
"GET",
f"/api/v1/users.info?username={username}",
)
if not r.get("success"):
raise RCRestError(
f"users.info for {username} failed: {r.get('error', 'unknown error')}"
)
return r.get("user", {})