Files
Hermes_rocket.chat_Plugin/tests/live_rc/conftest.py
T
Bernd (Hermes) 05531f1d8d feat(F172): Human-Tempo-Pacing im Laborassistent-Harness
Pacing-Modul (tests/live_rc/helpers/pacing.py) simuliert menschliche
Interaktionsrhythmen im Test-Runner — NICHT im Archivar (bleibt unverändert).

- 3 Pacing-Klassen: think (30-60s), read (2-5s), click (3-8s), idle (0s)
- Jitter ±20% (uniform) gegen Lock-Step mit Hintergrund-Tickern
- Konfiguration: ENV (RC_LIVE_*) > CLI-Flags > Code-Default
  --human-tempo={on,off}, --fast-mode, --pacing-{think,read,click}-{min,max}, --pacing-jitter
- F169-Reset: ::reset-timeout wird vor Test-Start gepostet (Rainers Veto)
- Quota-Schutz: avoided_llm_calls-Zähler protokolliert vermiedene LLM-Calls
- 22 Unit-Tests (tests/test_pacing.py) — Pacing wirkt, Kategorien korrekt,
  Config änderbar, Jitter-Korridor, Quota-Telemetrie
- test_01_echo als Referenz-Integration (pacer.wait('think') nach REST-Post)

@implements: [F-172]
2026-09-05 12:32:48 +02:00

601 lines
21 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
from tests.live_rc.helpers.pacing import (
Pacer,
PacingConfig,
config_from_env,
)
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)",
)
# ═══════════════════════════════════════════════════════════════════════════
# F172 — Human-Tempo-Pacing CLI-Flags (Architektur §3.1)
# ═══════════════════════════════════════════════════════════════════════════
#
# Priorität: ENV > CLI > Code-Default (Architektur §3.2).
# ``--fast-mode`` ist ein Alias für ``--human-tempo=off`` (Unit-Tests ohne LLM).
def pytest_addoption(parser):
group = parser.getgroup("f172-pacing", "F172 Human-Tempo-Pacing")
group.addoption(
"--human-tempo",
action="store",
default=None,
choices=("on", "off"),
help="Human-Tempo-Pacing aktivieren (on, Default) oder deaktivieren (off).",
)
group.addoption(
"--fast-mode",
action="store_true",
default=False,
help="Alias für --human-tempo=off (deaktiviert Pacing, für Unit-Tests ohne LLM).",
)
group.addoption(
"--pacing-think-min",
action="store",
default=None,
type=float,
help="Minimale human_think-Pause in Sekunden (Default 30).",
)
group.addoption(
"--pacing-think-max",
action="store",
default=None,
type=float,
help="Maximale human_think-Pause in Sekunden (Default 60).",
)
group.addoption(
"--pacing-read-min",
action="store",
default=None,
type=float,
help="Minimale human_read-Pause in Sekunden (Default 2).",
)
group.addoption(
"--pacing-read-max",
action="store",
default=None,
type=float,
help="Maximale human_read-Pause in Sekunden (Default 5).",
)
group.addoption(
"--pacing-click-min",
action="store",
default=None,
type=float,
help="Minimale human_click-Pause in Sekunden (Default 3).",
)
group.addoption(
"--pacing-click-max",
action="store",
default=None,
type=float,
help="Maximale human_click-Pause in Sekunden (Default 8).",
)
group.addoption(
"--pacing-jitter",
action="store",
default=None,
type=float,
help="Anteilige Streuung (Default 0.2 = ±20%%).",
)
def _build_pacing_config(config) -> PacingConfig:
"""Baut die PacingConfig aus ENV + CLI (CLI hat Vorrang vor ENV)."""
cfg = config_from_env()
# --fast-mode gewinnt über alles (expliziter Off-Schalter).
if config.getoption("--fast-mode"):
cfg.enabled = False
# --human-tempo explizit gesetzt?
ht = config.getoption("--human-tempo")
if ht is not None:
cfg.enabled = ht == "on"
def _opt(name):
return config.getoption(name)
# CLI-Ranges überschreiben ENV/Default nur wenn explizit gesetzt.
if _opt("--pacing-think-min") is not None:
cfg.think_min_s = _opt("--pacing-think-min")
if _opt("--pacing-think-max") is not None:
cfg.think_max_s = _opt("--pacing-think-max")
if _opt("--pacing-read-min") is not None:
cfg.read_min_s = _opt("--pacing-read-min")
if _opt("--pacing-read-max") is not None:
cfg.read_max_s = _opt("--pacing-read-max")
if _opt("--pacing-click-min") is not None:
cfg.click_min_s = _opt("--pacing-click-min")
if _opt("--pacing-click-max") is not None:
cfg.click_max_s = _opt("--pacing-click-max")
if _opt("--pacing-jitter") is not None:
cfg.jitter = _opt("--pacing-jitter")
return cfg
# ═══════════════════════════════════════════════════════════════════════════
# 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: 15 calls/minute (was 30 — RC triggers 429 aggressively).
"""
def __init__(self, max_tokens: int = 15, 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=15, 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()
# ═══════════════════════════════════════════════════════════════════════════
# F172 — Pacing-Fixture (Architektur §4.2)
# ═══════════════════════════════════════════════════════════════════════════
@pytest.fixture(scope="session")
def pacer(request) -> Pacer:
"""Session-scoped Pacer, konfiguriert aus ENV + CLI-Flags.
Tests rufen ``pacer.wait("think"|"read"|"click"|"idle")`` explizit
zwischen REST-Post und Polling auf (Architektur §2.2: Harness setzt
den Pacing-Typ explizit, keine Inferenz).
"""
cfg = _build_pacing_config(request.config)
logger.info(
"F172: Pacing %s (think %.0f-%.0fs, read %.0f-%.0fs, click %.0f-%.0fs, jitter %.2f)",
"AKTIV" if cfg.enabled else "DEAKTIVIERT",
cfg.think_min_s, cfg.think_max_s,
cfg.read_min_s, cfg.read_max_s,
cfg.click_min_s, cfg.click_max_s,
cfg.jitter,
)
return Pacer(config=cfg)
@pytest.fixture(scope="session", autouse=True)
def _reset_timeout_before_suite(request, rc_client: RCRestClient, rc_config: dict):
"""F169-Reset VOR Test-Start (Rainers Veto, Architektur §5.2).
Postet ``::reset-timeout`` einmalig vor dem ersten Test, damit die
adaptive Timeout-Kalibrierung (Welford) nicht auf Bot-Tempo läuft.
Ohne diesen Reset kalibriert F169 auf die Burst-Spitzen des
Bot-Feuerwerks und der Timeout driftet zu lang (P-195-Kandidat).
"""
room_id = rc_config["test_room"]
try:
msg_id, _ = rc_client.post_message(room_id, "::reset-timeout")
logger.info(
"F169: ::reset-timeout vor Test-Start gesendet (msg %s)",
msg_id[:12],
)
except RCRestError as e:
# Nicht fatal — Reset ist Best-Effort, Test läuft weiter.
logger.warning("F169: ::reset-timeout fehlgeschlagen: %s", e)
yield
@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]}"
)