57ebbc6d6b
AUFGABE 1 — Rate-Limiter in _request(): - RCRestClient.__init__ nimmt optionalen rate_limiter - _request() ruft rate_limiter.acquire() VOR jedem API-Call auf - Schützt ALLE Endpoints: postMessage, channels.history, users.info, chat.delete - rc_client Fixture (session-scoped) injiziert rate_limiter in den Client AUFGABE 2 — 15s Cooldown zwischen Tests: - rate_limit_cooldown autouse Fixture in conftest.py - yield + time.sleep(15) nach jedem Test - RC Rate-Limit-Window (~10s) wird zuverlässig resettet AUFGABE 3 — test_03 Skip-Ursache: - test_02 und test_03 pollen nicht mehr direkt hintereinander ohne Pause - 15s Cooldown + zentraler Rate-Limiter verhindern kaskadierende 429s AUFGABE 4 — 429-Retry mit Backoff: - _request() retryed HTTP 429 mit 3s → 6s → 12s Backoff (max 3 Retries) - post_message failt nicht mehr sofort bei 429 CLEANUP: - Redundante rate_limiter.acquire() aus polling.py (wait_for_bot_message, get_latest_timestamp), conftest.py (post_test_message) und test_04_multi_room.py entfernt - rate_limiter Fixture auf session-scope (war eh globaler Singleton) - Docstrings aktualisiert
243 lines
8.1 KiB
Python
243 lines
8.1 KiB
Python
"""
|
|
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).
|
|
|
|
Rate limiting: if a rate_limiter is provided, every API call acquires
|
|
a token before the HTTP request. On HTTP 429, retries with exponential
|
|
backoff (3s → 6s → 12s, max 3 retries).
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
base_url: str,
|
|
auth_token: str,
|
|
user_id: str,
|
|
rate_limiter=None,
|
|
):
|
|
self.base_url = base_url.rstrip("/")
|
|
self.auth_token = auth_token
|
|
self.user_id = user_id
|
|
self.rate_limiter = rate_limiter
|
|
|
|
# ── Low-level request ──────────────────────────────────────────────
|
|
|
|
def _request(
|
|
self,
|
|
method: str,
|
|
endpoint: str,
|
|
data: Optional[dict] = None,
|
|
) -> dict:
|
|
"""Send an authenticated request to the RC REST API.
|
|
|
|
Rate limiting: acquires a token from self.rate_limiter (if set)
|
|
before every API call. On HTTP 429, retries with exponential
|
|
backoff (3s → 6s → 12s, max 3 retries).
|
|
|
|
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)
|
|
|
|
# 429 retry with exponential backoff: 3s → 6s → 12s, max 3 retries
|
|
max_429_retries = 3
|
|
for attempt in range(max_429_retries + 1):
|
|
# Rate-limit before every API call (protects post, history, delete, etc.)
|
|
if self.rate_limiter is not None:
|
|
self.rate_limiter.acquire()
|
|
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
return json.loads(resp.read().decode("utf-8"))
|
|
except urllib.error.HTTPError as e:
|
|
if e.code == 429 and attempt < max_429_retries:
|
|
backoff = 3.0 * (2 ** attempt) # 3s, 6s, 12s
|
|
logger.warning(
|
|
"HTTP 429 on %s %s (attempt %d/%d) — backing off %ds",
|
|
method, endpoint, attempt + 1, max_429_retries + 1, backoff,
|
|
)
|
|
time.sleep(backoff)
|
|
continue
|
|
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
|
|
|
|
# Should never reach here — all paths either return or raise
|
|
raise RCRestError(
|
|
f"Exhausted {max_429_retries + 1} attempts on {method} {endpoint}"
|
|
)
|
|
|
|
# ── 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", {})
|