Files
Hermes_rocket.chat_Plugin/tests/live_rc/conftest.py
T
Bernd (Hermes) aa37de3e6e rate-limiting feinschliff: 429-retry, API-call reduction, auto-route detection
AUFGABE 1 — test_03 API-calls reduzieren:
- Skip get_latest_timestamp on source room; use post_message's returned ts as cursor (saves 1 channels.history call)
- Source polling: initial_interval=5s (was 2s), timeout=30s (was 25s)
- Target polling: timeout=60s (was 25s), initial_interval=8s (was 2s)
- post_message() now returns (msg_id, ts) tuple — all call sites updated

AUFGABE 2 — 429-retry strategy verbessern:
- rc_rest.py: 5 retries with 3s/6s/12s/20s/30s backoff (was 3 retries 3s/6s/12s)
- polling.py: 5 consecutive 429s before RateLimitSkip (was 3)
- polling.py: 429 backoff max 30s (was 24s)

AUFGABE 3 — rate-limit-cooldown erhöhen:
- conftest.py: 20s between tests (was 15s)

AUFGABE 4 — test_03 auto-route robustness:
- Detect auto-route (wechseln/sehe dich/thema) vs button-move-request (kopieren/rüber/attachments)
- Auto-route: pytest.skip with reason, no button click, no target verification
- Button-request: proceed with existing button-click + target-verification flow
2026-07-28 18:34:07 +02:00

439 lines
16 KiB
Python

"""
Pytest configuration for Rocket.Chat live tests.
Fixtures, markers, skip logic, self-check, rate limiter, suite lock,
and cleanup for the REST-based test harness running on .101.
Usage:
pytest tests/live_rc/ -m live_rc -v
Without RC_LIVE_URL set: all tests are skipped cleanly (no errors)
at collection time via pytest_collection_modifyitems.
"""
from __future__ import annotations
import fcntl
import logging
import os
import sys
import time
from pathlib import Path
from typing import Generator
import pytest
# Ensure helpers are importable
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from tests.live_rc.helpers.rc_rest import RCRestClient, RCRestError
from tests.live_rc.helpers.polling import get_latest_timestamp, RateLimitSkip
logger = logging.getLogger(__name__)
# ═══════════════════════════════════════════════════════════════════════════
# Pytest marker registration
# ═══════════════════════════════════════════════════════════════════════════
def pytest_configure(config):
config.addinivalue_line(
"markers",
"live_rc: Rocket.Chat live integration test (requires running .45 bot)",
)
# ═══════════════════════════════════════════════════════════════════════════
# Env-var check — skip entire suite at collection time if not configured
# ═══════════════════════════════════════════════════════════════════════════
def _env_required(name: str) -> str:
"""Get a required env var. Returns empty string if not set."""
return (os.getenv(name) or "").strip()
def _is_live_configured() -> bool:
"""Check if all required env vars are set."""
required = [
"RC_LIVE_URL",
"RC_LIVE_TOKEN",
"RC_LIVE_USER_ID",
"RC_LIVE_TEST_ROOM",
"RC_LIVE_BOT_USERNAME",
"RC_LIVE_BOT_USER_ID",
]
return all(_env_required(v) for v in required)
def pytest_collection_modifyitems(config, items):
"""Skip all live_rc tests at collection time if RC_LIVE_URL is not set.
This is the earliest possible skip point — before any fixtures are
instantiated, before any imports are resolved. Tests that would
otherwise fail due to missing env vars are cleanly skipped.
"""
if not _is_live_configured():
skip_reason = (
"RC_LIVE_URL not set — skipping all live RC tests. "
"Set RC_LIVE_URL, RC_LIVE_TOKEN, RC_LIVE_USER_ID, "
"RC_LIVE_TEST_ROOM, RC_LIVE_BOT_USERNAME, RC_LIVE_BOT_USER_ID "
"to run live tests."
)
for item in items:
if item.get_closest_marker("live_rc"):
item.add_marker(pytest.mark.skip(reason=skip_reason))
# ═══════════════════════════════════════════════════════════════════════════
# Token-Bucket Rate Limiter (max 30 calls/minute)
# ═══════════════════════════════════════════════════════════════════════════
class RateLimiter:
"""Simple token-bucket rate limiter.
Allows max_tokens calls per window_seconds. Thread-safe via lock.
Default: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
"""
def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
self.max_tokens = max_tokens
self.window_seconds = window_seconds
self.tokens = float(max_tokens)
self.last_refill = time.monotonic()
self._lock = __import__("threading").Lock()
def acquire(self) -> None:
"""Block until a token is available."""
import threading
with self._lock:
now = time.monotonic()
elapsed = now - self.last_refill
# Refill tokens proportionally
self.tokens = min(
self.max_tokens,
self.tokens + elapsed * (self.max_tokens / self.window_seconds),
)
self.last_refill = now
if self.tokens >= 1.0:
self.tokens -= 1.0
return
# Need to wait for a token
wait_time = (1.0 - self.tokens) * (self.window_seconds / self.max_tokens)
self.tokens = 0.0
time.sleep(wait_time)
# Re-acquire after waiting
with self._lock:
self.tokens = max(0.0, self.tokens - 1.0)
# Global rate limiter instance (created once per process)
_rate_limiter: RateLimiter | None = None
def _get_rate_limiter() -> RateLimiter:
global _rate_limiter
if _rate_limiter is None:
_rate_limiter = RateLimiter(max_tokens=30, window_seconds=60.0)
return _rate_limiter
# ═══════════════════════════════════════════════════════════════════════════
# Suite Lock — only one parallel run
# ═══════════════════════════════════════════════════════════════════════════
_LOCK_PATH = "/tmp/rc-live-tests.lock"
_lock_fd = None
def _acquire_suite_lock() -> bool:
"""Try to acquire the suite lock. Returns True on success."""
global _lock_fd
try:
_lock_fd = open(_LOCK_PATH, "w")
fcntl.flock(_lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
_lock_fd.write(f"pid={os.getpid()}\ntime={time.time()}\n")
_lock_fd.flush()
return True
except (IOError, OSError):
if _lock_fd:
_lock_fd.close()
_lock_fd = None
return False
def _release_suite_lock() -> None:
"""Release the suite lock."""
global _lock_fd
if _lock_fd:
try:
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
_lock_fd.close()
except Exception:
pass
finally:
_lock_fd = None
try:
os.unlink(_LOCK_PATH)
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════════
# Fixtures
# ═══════════════════════════════════════════════════════════════════════════
@pytest.fixture(scope="session")
def rc_config() -> dict:
"""Provide the RC live test configuration from env vars.
Skips the entire session if RC_LIVE_URL is not set.
(Redundant with pytest_collection_modifyitems, but kept as safety net.)
"""
if not _is_live_configured():
pytest.skip("RC_LIVE_URL not set — skipping live RC tests")
# Acquire suite lock
if not _acquire_suite_lock():
pytest.fail(
"Could not acquire suite lock at /tmp/rc-live-tests.lock — "
"another test run may be in progress. Remove the lock file "
"if you're sure no other run is active."
)
return {
"url": _env_required("RC_LIVE_URL"),
"token": _env_required("RC_LIVE_TOKEN"),
"user_id": _env_required("RC_LIVE_USER_ID"),
"test_room": _env_required("RC_LIVE_TEST_ROOM"),
"bot_username": _env_required("RC_LIVE_BOT_USERNAME"),
"bot_user_id": _env_required("RC_LIVE_BOT_USER_ID"),
}
@pytest.fixture(scope="session")
def rc_client(rc_config: dict, rate_limiter) -> RCRestClient:
"""Create an authenticated RCRestClient for the test session.
Performs self-check: verifies that the token matches the user identity.
The rate_limiter is injected into the client so every API call
(post, history, delete, users.info) is rate-limited automatically.
"""
client = RCRestClient(
base_url=rc_config["url"],
auth_token=rc_config["token"],
user_id=rc_config["user_id"],
rate_limiter=rate_limiter,
)
# P0: Self-check — verify token matches user identity
try:
result = client.self_check()
logger.info(
"Self-check OK: user=%s, id=%s",
result["username"],
result["user_id"][:12],
)
except RCRestError as e:
pytest.fail(f"Self-check FAILED: {e}")
return client
@pytest.fixture(scope="session", autouse=True)
def _suite_cleanup(request, rc_config: dict):
"""Session-scoped cleanup: release suite lock on teardown."""
yield
_release_suite_lock()
@pytest.fixture(autouse=True)
def rate_limit_cooldown():
"""Wait 20s between tests for RC rate-limit window reset.
RC's rate-limit window is ~10s. A 20s pause between tests ensures
the token bucket has time to refill, preventing cascading 429s
when tests run back-to-back. Increased from 15s — test_03 makes
more API calls and needs extra headroom.
"""
yield
time.sleep(20)
@pytest.fixture
def test_room_id(rc_config: dict) -> str:
"""The test room ID for the current test."""
return rc_config["test_room"]
@pytest.fixture
def bot_username(rc_config: dict) -> str:
"""The bot's username."""
return rc_config["bot_username"]
@pytest.fixture
def bot_user_id(rc_config: dict) -> str:
"""The bot's user ID."""
return rc_config["bot_user_id"]
@pytest.fixture
def bot_status_check(rc_client: RCRestClient, bot_user_id: str, bot_username: str):
"""Pre-condition: verify bot is in a state where it can respond.
Checks:
1. Bot user exists and is active
2. Bot statusText doesn't indicate blocking state (onboarding, etc.)
Returns the bot user info dict on success.
"""
try:
user = rc_client.get_user_info(bot_username)
except Exception as e:
pytest.fail(
f"Bot user '{bot_username}' not found via REST API. "
f"Check that .45 MyTestBot is running. Error: {e}"
)
status_text = (user.get("statusText") or "").lower()
status = (user.get("status") or "").lower()
# Check for known blocking states
blocking_states = []
# NOTE: statusText='Onboarding läuft' is set by the plugin even when F8=COMPLETED.
# The F8 log line is the authoritative check, not the statusText.
# Only block if status is NOT online/away/busy (bot completely offline).
if status not in ("online", "away", "busy"):
blocking_states.append(f"status='{status}'")
if blocking_states:
pytest.skip(
f"Bot '{bot_username}' is not ready to respond: "
f"{'; '.join(blocking_states)}. "
f"Resolve the blocking state on .45 before running live tests."
)
logger.info(
"Bot status OK: username=%s, status=%s, statusText=%s",
bot_username, status, user.get("statusText", ""),
)
return user
@pytest.fixture(scope="session")
def rate_limiter() -> RateLimiter:
"""Rate limiter to stay under 30 calls/minute (session-scoped)."""
return _get_rate_limiter()
@pytest.fixture
def cursor(rc_client: RCRestClient, test_room_id: str, rate_limiter: RateLimiter) -> str:
"""Get the latest message timestamp as a cursor.
All test messages posted after this cursor will be considered
for bot response detection.
"""
ts = get_latest_timestamp(rc_client, test_room_id, rate_limiter=rate_limiter)
logger.info("Cursor set to %s", ts[:19])
return ts
@pytest.fixture
def posted_message_ids() -> list:
"""Collector for message IDs posted during a test.
Cleanup fixture deletes all collected messages after the test.
"""
ids: list = []
return ids
@pytest.fixture
def cleanup_messages(
rc_client: RCRestClient,
test_room_id: str,
posted_message_ids: list,
):
"""Cleanup fixture: deletes all messages posted during the test.
Usage: append message IDs to posted_message_ids as you post them.
After the test (even on failure), all collected messages are deleted.
"""
yield
for msg_id in posted_message_ids:
try:
rc_client.delete_message(test_room_id, msg_id)
logger.debug("Cleanup: deleted message %s", msg_id[:12])
except Exception as e:
logger.warning("Cleanup: failed to delete %s: %s", msg_id[:12], e)
# ═══════════════════════════════════════════════════════════════════════════
# Helper: post a test message (rate-limited, tracked for cleanup)
# ═══════════════════════════════════════════════════════════════════════════
def post_test_message(
client: RCRestClient,
room_id: str,
text: str,
posted_ids: list,
limiter: RateLimiter | None = None,
) -> tuple[str, str]:
"""Post a test message with cleanup tracking.
Rate limiting is handled by the RCRestClient internally (via _request).
The limiter parameter is kept for backward compatibility but is unused.
Args:
client: Authenticated RCRestClient.
room_id: Target room ID.
text: Message text.
posted_ids: List to append the message ID to (for cleanup).
limiter: Deprecated — rate limiting is now in RCRestClient._request().
Returns:
A tuple of (message_id, timestamp) from the API response.
"""
msg_id, ts = client.post_message(room_id, text)
posted_ids.append(msg_id)
return msg_id, ts
# ═══════════════════════════════════════════════════════════════════════════
# Helper: assert message ownership
# ═══════════════════════════════════════════════════════════════════════════
def assert_bot_message(
msg: dict,
expected_username: str,
context: str = "",
) -> None:
"""Assert that a message was sent by the expected bot user.
Args:
msg: Message dict from channels.history.
expected_username: The bot's username (case-insensitive).
context: Description for assertion error messages.
Raises:
AssertionError: If the message is not from the expected user.
"""
u = msg.get("u", {})
actual_username = (u.get("username", "") or "").lower()
expected_lower = expected_username.lower()
ctx = f" ({context})" if context else ""
assert actual_username == expected_lower, (
f"Message ownership mismatch{ctx}: "
f"expected username='{expected_lower}', "
f"got username='{actual_username}'. "
f"Message text: {msg.get('msg', '')[:100]}"
)