""" F172 — Human-Tempo-Pacing (Bot-seitig) — Unit-Tests. Der Bot wartet mindestens HUMAN_TEMPO_MIN_DELAY Sekunden zwischen zwei ausgehenden Nachrichten, damit Antworten ein menschliches Tempo einhalten (statt "Bot-Feuerwerk"). Testet die Pacing-Helper in plugin/adapter.py. Abgedeckt: - Pacing aktiv (Default on, 2.0s) - deaktivierbar (HUMAN_TEMPO_PACING=off) - konfigurierbar (HUMAN_TEMPO_MIN_DELAY) - _await_human_tempo wartet den Mindestabstand (async) - Human-Tempo-Logik greift in _post_message_with_retry @implements: [F-172] """ from __future__ import annotations import asyncio import sys import time from pathlib import Path import pytest # Repo-Root = Parent von tests/ (adapter.py liegt in /plugin/adapter.py). # Wenn das Skript in einem flachen Ordner läuft, ist der Parent der Ordner. _REPO_ROOT = Path(__file__).resolve().parent.parent # tests/ -> Repo-Root _FALLBACK = Path(__file__).resolve().parent _ADAPTER_DIR = _REPO_ROOT if (_REPO_ROOT / "plugin/adapter.py").exists() else _FALLBACK sys.path.insert(0, str(_ADAPTER_DIR)) # Isolierten Import der Pacing-Helper (ohne die schweren archivar-Imports). import plugin.adapter as adapter_mod class _MonotonicClock: """Synthetische monotonic-Uhr für deterministische Tests.""" def __init__(self, start: float = 1000.0): self._now = start def advance(self, seconds: float) -> None: self._now += seconds def now(self) -> float: return self._now @pytest.fixture def fresh_pacing(monkeypatch): """Setzt das Pacing-Modul auf einen sauberen Zustand zurück.""" adapter_mod._HUMAN_TEMPO_LAST_SEND = 0.0 adapter_mod._HUMAN_TEMPO_PACING_ENABLED = True adapter_mod._HUMAN_TEMPO_MIN_DELAY = 2.0 yield def test_pacing_default_enabled(): """Ohne env ist Pacing aktiv (delay > 0).""" assert adapter_mod.human_tempo_min_delay() > 0.0 def test_pacing_default_delay_is_2s(monkeypatch, fresh_pacing): """Default Min-Delay ist 2.0 Sekunden.""" for var in ("HUMAN_TEMPO_MIN_DELAY", "HUMAN_TEMPO_PACING"): monkeypatch.delenv(var, raising=False) # Modul-Neuauswertung: setze Werte explizit. adapter_mod._HUMAN_TEMPO_MIN_DELAY = 2.0 assert adapter_mod.human_tempo_min_delay() == 2.0 def test_pacing_configurable_delay(monkeypatch, fresh_pacing): """HUMAN_TEMPO_MIN_DELAY=5.0 → delay 5.0.""" adapter_mod._HUMAN_TEMPO_MIN_DELAY = 5.0 assert adapter_mod.human_tempo_min_delay() == 5.0 def test_pacing_disable_via_flag(monkeypatch, fresh_pacing): """HUMAN_TEMPO_PACING=off → delay 0.0 (deaktiviert).""" adapter_mod._HUMAN_TEMPO_PACING_ENABLED = False assert adapter_mod.human_tempo_min_delay() == 0.0 def test_pacing_zero_delay_disabled(): """delay 0.0 → kein Warten (human_tempo_min_delay liefert 0).""" adapter_mod._HUMAN_TEMPO_MIN_DELAY = 0.0 adapter_mod._HUMAN_TEMPO_PACING_ENABLED = True assert adapter_mod.human_tempo_min_delay() == 0.0 # ═══════════════════════════════════════════════════════════════════════════ # _await_human_tempo: wartet den Mindestabstand # ═══════════════════════════════════════════════════════════════════════════ def test_await_human_tempo_waits_when_too_soon(monkeypatch, fresh_pacing): """Direkt nacheinander: zweiter Aufruf muss min. Delay warten.""" sleeps = [] async def fake_sleep(s): sleeps.append(s) monkeypatch.setattr(adapter_mod.asyncio, "sleep", fake_sleep) adapter_mod._HUMAN_TEMPO_MIN_DELAY = 2.0 adapter_mod._HUMAN_TEMPO_PACING_ENABLED = True # Erster Aufruf: kein letzter Send → kein Warten. asyncio.run(adapter_mod._await_human_tempo()) # Zweiter Aufruf direkt danach → muss ~2s warten. asyncio.run(adapter_mod._await_human_tempo()) assert sleeps, "F172: _await_human_tempo muss beim direkten Folge-Send warten" assert sleeps[0] >= 1.0, f"Erwartet >= 2s Wartezeit, bekam {sleeps[0]}s" def test_await_human_tempo_no_wait_after_long_enough(monkeypatch, fresh_pacing): """Nach hinreichend langer Pause (>= Delay) kein zusätzliches Warten.""" sleeps = [] async def fake_sleep(s): sleeps.append(s) monkeypatch.setattr(adapter_mod.asyncio, "sleep", fake_sleep) adapter_mod._HUMAN_TEMPO_MIN_DELAY = 2.0 adapter_mod._HUMAN_TEMPO_PACING_ENABLED = True asyncio.run(adapter_mod._await_human_tempo()) # setzt LAST_SEND # Manuell einen älteren Zeitstempel setzen (als wäre es 10s her). adapter_mod._HUMAN_TEMPO_LAST_SEND = time.monotonic() - 10.0 asyncio.run(adapter_mod._await_human_tempo()) assert sleeps == [], "F172: nach 10s Pause darf kein Zusatz-Wait kommen" def test_await_human_tempo_no_wait_when_disabled(monkeypatch, fresh_pacing): """Wenn Pacing deaktiviert ist, kein Warten.""" sleeps = [] async def fake_sleep(s): sleeps.append(s) monkeypatch.setattr(adapter_mod.asyncio, "sleep", fake_sleep) adapter_mod._HUMAN_TEMPO_PACING_ENABLED = False asyncio.run(adapter_mod._await_human_tempo()) assert sleeps == [] # ═══════════════════════════════════════════════════════════════════════════ # Verdrahtung im Send-Punkt (_post_message_with_retry ruft Pacing) # ═══════════════════════════════════════════════════════════════════════════ def test_post_message_with_retry_calls_pacing(monkeypatch, fresh_pacing): """_post_message_with_retry muss _await_human_tempo aufrufen.""" src = Path(adapter_mod.__file__).read_text() # _await_human_tempo muss im Body von _post_message_with_retry stehen # (der einzige Send-Chokepoint für ausgehende Nachrichten). body_start = src.find("async def _post_message_with_retry") assert body_start != -1, "F172: _post_message_with_retry nicht gefunden" body = src[body_start:body_start + 4000] assert "_await_human_tempo()" in body, ( "F172: _post_message_with_retry ruft _await_human_tempo() nicht auf" ) def test_f172_implements_markers(): """@implements: [F-172] muss in adapter.py stehen (Bindestrich-Konvention).""" src = Path(adapter_mod.__file__).read_text() assert "@implements: [F-172]" in src, ( "adapter.py fehlt der @implements: [F-172]-Marker" )