6a09caa1e5
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
399 lines
14 KiB
Python
399 lines
14 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
|
|
|
|
Without RC_LIVE_URL set: all tests are skipped cleanly (no errors).
|
|
"""
|
|
|
|
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
|
|
|
|
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 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)
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# Token-Bucket Rate Limiter (max 60 calls/minute)
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
|
|
class RateLimiter:
|
|
"""Simple token-bucket rate limiter.
|
|
|
|
Allows max_tokens calls per window_seconds. Thread-safe via lock.
|
|
"""
|
|
|
|
def __init__(self, max_tokens: int = 60, 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=60, 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.
|
|
"""
|
|
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) -> RCRestClient:
|
|
"""Create an authenticated RCRestClient for the test session.
|
|
|
|
Performs self-check: verifies that the token matches the user identity.
|
|
"""
|
|
client = RCRestClient(
|
|
base_url=rc_config["url"],
|
|
auth_token=rc_config["token"],
|
|
user_id=rc_config["user_id"],
|
|
)
|
|
|
|
# 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
|
|
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 = []
|
|
if "onboarding" in status_text:
|
|
blocking_states.append(f"statusText='{user.get('statusText')}' (onboarding active)")
|
|
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
|
|
def rate_limiter() -> RateLimiter:
|
|
"""Rate limiter to stay under 60 calls/minute."""
|
|
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,
|
|
) -> str:
|
|
"""Post a test message with rate limiting and cleanup tracking.
|
|
|
|
Args:
|
|
client: Authenticated RCRestClient.
|
|
room_id: Target room ID.
|
|
text: Message text.
|
|
posted_ids: List to append the message ID to (for cleanup).
|
|
limiter: Optional rate limiter.
|
|
|
|
Returns:
|
|
The message _id.
|
|
"""
|
|
if limiter:
|
|
limiter.acquire()
|
|
msg_id = client.post_message(room_id, text)
|
|
posted_ids.append(msg_id)
|
|
return msg_id
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# 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]}"
|
|
)
|