Files
Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_subagent_status_presence.py
T
Bernd (Hermes) e9027d6681 feat: Phase 4 Live-Test — 16 neue Integrationstests
plugin/archivar/tests/test_subagent_status_presence.py (16 Tests):
- TestMarkBusyDoneWithBgTasks (2): bg>0 → kein online, bg=0 → online (Regression)
- TestHoneymoonExpiredWithBgTasks (1): Honeymoon+Subagent → kein online
- TestDetectionTimerReadsSubagentStatus (2): erkennt aktive/leere subagent_status.json
- TestPulseControllerAwayMode (5): pulse_target default/set/invalid/race-safety
- TestPulseControllerBusyMode (3): busy-mode, _update_presence_with_subagents idle/busy
- TestReadSubagentCount (3): count 0/2/missing-file

Production-Impact: none (tests only)
2026-08-02 11:19:35 +02:00

433 lines
18 KiB
Python

"""
V8.6 Phase 5: Subagent-Status — PresenceEngine Integrationstests.
Testet:
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
- _honeymoon_expired mit background_tasks > 0
- DetectionTimer liest subagent_status.json
- PulseController pulse_target="away" toggles
- PulseController pulse_target="busy" message-pulses
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
import threading
import time
from pathlib import Path
from unittest.mock import MagicMock, patch, call
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
# ═══════════════════════════════════════════════════════════════════════════
# B4: Autouse fixture — engine.shutdown() nach jedem Test
# ═══════════════════════════════════════════════════════════════════════════
_ENGINE_REGISTRY: list = []
@pytest.fixture(autouse=True)
def _shutdown_presence_engines():
"""Track all PresenceEngine instances and call shutdown() after each test."""
from plugin.archivar.presence_engine import PresenceEngine
_original_init = PresenceEngine.__init__
def _tracking_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
_ENGINE_REGISTRY.append(self)
PresenceEngine.__init__ = _tracking_init
_ENGINE_REGISTRY.clear()
try:
yield
finally:
PresenceEngine.__init__ = _original_init
for engine in _ENGINE_REGISTRY:
try:
engine.shutdown()
except Exception:
pass
_ENGINE_REGISTRY.clear()
# ═══════════════════════════════════════════════════════════════════════════
# Helper: create a PresenceEngine with mocked REST
# ═══════════════════════════════════════════════════════════════════════════
def _make_engine(**kwargs):
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, **kwargs)
return engine, mock_rest
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: mark_busy_done with bg_tasks > 0 does NOT transition to online
# ═══════════════════════════════════════════════════════════════════════════
class TestMarkBusyDoneWithBgTasks:
"""Test 3: mark_busy_done mit background_tasks > 0 geht NICHT auf online."""
def test_busy_done_with_bg_tasks_stays_away_or_busy(self):
"""Wenn background_tasks > 0, transitioniert mark_busy_done nicht auf online."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Simuliere: Hauptagent busy + Subagent läuft
engine.mark_busy_started(room_name="testroom")
engine.increment_background_tasks() # bg=1
# Honeymoon abwarten
time.sleep(1.2)
# mark_busy_done — sollte NICHT auf online gehen weil bg=1
engine.mark_busy_done()
# Flush coalesce
time.sleep(0.3)
# Prüfe: letzter gesendeter Status ist NICHT "online"
# (sollte "away" sein wegen Subagent-Pulse)
calls = mock_rest._request.call_args_list
assert len(calls) > 0, "Expected at least one REST call"
# Der letzte Call sollte nicht "online" mit leerer Message sein
last_call = calls[-1]
last_data = last_call[1].get("data", {})
# Entweder "away" (idle+subagent) oder "busy" (busy+subagent)
assert last_data.get("status") != "online", (
f"Expected non-online status, got {last_data}"
)
def test_busy_done_zero_bg_tasks_transitions_to_online(self):
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
engine, mock_rest = _make_engine(coalesce_ms=100)
engine.mark_busy_started(room_name="testroom")
# KEIN increment_background_tasks → bg=0
time.sleep(1.2)
engine.mark_busy_done()
time.sleep(0.3)
calls = mock_rest._request.call_args_list
last_call = calls[-1]
last_data = last_call[1].get("data", {})
assert last_data.get("status") == "online", (
f"Expected online status, got {last_data}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 5: _honeymoon_expired with bg_tasks > 0
# ═══════════════════════════════════════════════════════════════════════════
class TestHoneymoonExpiredWithBgTasks:
"""Test 5: _honeymoon_expired mit background_tasks > 0 geht nicht auf online."""
def test_honeymoon_expired_with_bg_tasks_does_not_transition(self):
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Starte busy, dann sofort mark_busy_done (Honeymoon läuft noch)
engine.mark_busy_started(room_name="testroom")
engine.increment_background_tasks() # bg=1
# Honeymoon abwarten
time.sleep(1.2)
# Honeymoon-Timer sollte gefeuert haben, aber bg=1 → kein online
# Rufe _transition_from_busy manuell auf um zu prüfen
engine._transition_from_busy()
time.sleep(0.3)
calls = mock_rest._request.call_args_list
last_call = calls[-1]
last_data = last_call[1].get("data", {})
assert last_data.get("status") != "online", (
f"Expected non-online status after honeymoon with bg_tasks, got {last_data}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 6: DetectionTimer reads subagent_status.json
# ═══════════════════════════════════════════════════════════════════════════
class TestDetectionTimerReadsSubagentStatus:
"""Test 6: DetectionTimer.check() liest subagent_status.json."""
def test_detection_timer_detects_subagent_status(self):
"""DetectionTimer erkennt aktive Einträge in subagent_status.json."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
# Schreibe einen aktiven Subagenten
subagent_path = _get_subagent_state_path()
_write_subagent_state(subagent_path, {
"active": [{"task_id": "t_123", "type": "delegate_task", "owner_room": "user:bernd"}],
"last_change_iso": "",
"schema_version": 1,
"source": "plugin_internal",
})
# DetectionTimer ohne gateway_state (damit PID-Sentinel + gateway fehlschlagen)
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
gateway_path = f.name
try:
# Leeres gateway_state → PID-Sentinel greift (Gateway lebt)
# Um subagent_status zu testen, mocken wir _check_gateway_pid_alive
timer = DetectionTimer(
gateway_state_path=gateway_path,
detection_interval=10.0,
)
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(stdout="", returncode=1)
result = timer.check()
# Sollte True sein weil subagent_status.json aktive Einträge hat
assert result is True, f"Expected True, got {result}"
finally:
os.unlink(gateway_path)
# Cleanup subagent_status.json
try:
os.unlink(subagent_path)
except OSError:
pass
def test_detection_timer_empty_subagent_status(self):
"""DetectionTimer erkennt leere subagent_status.json nicht als aktiv."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
subagent_path = _get_subagent_state_path()
_write_subagent_state(subagent_path, {
"active": [],
"last_change_iso": "",
"schema_version": 1,
"source": "plugin_internal",
})
# Auch plugin_state.json bereinigen (könnte bg_tasks vom vorherigen Test haben)
from plugin.archivar.presence_engine import _get_plugin_state_path, _write_plugin_state
plugin_path = _get_plugin_state_path()
_write_plugin_state(plugin_path, {
"background_tasks": 0,
"last_update_iso": "",
"source": "plugin_internal",
"schema_version": 1,
})
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
gateway_path = f.name
try:
timer = DetectionTimer(
gateway_state_path=gateway_path,
detection_interval=10.0,
)
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(stdout="", returncode=1)
result = timer.check()
# Sollte False sein weil keine Quellen aktiv
assert result is False, f"Expected False, got {result}"
finally:
os.unlink(gateway_path)
try:
os.unlink(subagent_path)
except OSError:
pass
# ═══════════════════════════════════════════════════════════════════════════
# Test 7: PulseController pulse_target="away" toggles
# ═══════════════════════════════════════════════════════════════════════════
class TestPulseControllerAwayMode:
"""Test 7: PulseController mit pulse_target='away' toggled online↔away."""
def test_pulse_target_default_is_away(self):
"""Default pulse_target ist 'away'."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
assert pc.get_pulse_target() == "away"
def test_set_pulse_target_away(self):
"""set_pulse_target('away') funktioniert."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
changed = pc.set_pulse_target("away")
assert changed is False # already "away"
assert pc.get_pulse_target() == "away"
def test_set_pulse_target_busy(self):
"""set_pulse_target('busy') wechselt Modus."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
changed = pc.set_pulse_target("busy")
assert changed is True
assert pc.get_pulse_target() == "busy"
def test_set_pulse_target_invalid_raises(self):
"""Ungültiger pulse_target wirft ValueError."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
with pytest.raises(ValueError):
pc.set_pulse_target("invalid")
def test_pulse_target_mode_sentinel_prevents_race(self):
"""Mode-Sentinel: parallele set_pulse_target-Aufrufe sind sicher."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
errors = []
def toggle_mode():
try:
for _ in range(50):
pc.set_pulse_target("away")
pc.set_pulse_target("busy")
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=toggle_mode) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
assert len(errors) == 0, f"Errors: {errors}"
# Final mode should be one of the two valid values
assert pc.get_pulse_target() in ("away", "busy")
# ═══════════════════════════════════════════════════════════════════════════
# Test 8: PulseController pulse_target="busy" message-pulses
# ═══════════════════════════════════════════════════════════════════════════
class TestPulseControllerBusyMode:
"""Test 8: PulseController mit pulse_target='busy' hält busy-Status."""
def test_busy_mode_does_not_toggle_to_online(self):
"""Im busy-Modus wird nicht auf online getoggled."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
pc.set_pulse_target("busy")
# Mock DDP
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock()
pc.bind_ddp(mock_ddp)
# Start pulse
pc.start()
time.sleep(0.4) # Wait for a few ticks
pc.stop()
# Im busy-Modus sollte der PulseController NICHT online↔away togglen
# sondern den busy-Status halten (via _update_presence_with_subagents)
# Hier testen wir nur dass der Mode korrekt gesetzt ist
assert pc.get_pulse_target() == "busy"
def test__update_presence_with_subagents_idle(self):
"""_update_presence_with_subagents bei idle startet away-Pulse."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Sicherstellen dass active_tasks == 0
assert engine._active_tasks == 0
engine._update_presence_with_subagents(3)
time.sleep(0.3)
# Sollte "away" mit Message "3 Subagent läuft" gesendet haben
calls = mock_rest._request.call_args_list
assert len(calls) > 0
last_data = calls[-1][1].get("data", {})
assert last_data.get("status") == "away"
assert "3 Subagent" in last_data.get("message", "")
def test__update_presence_with_subagents_busy(self):
"""_update_presence_with_subagents bei busy setzt busy+Message."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Simuliere busy
engine.increment_active_tasks()
engine.set_current_room("testroom")
engine._update_presence_with_subagents(2)
time.sleep(0.3)
calls = mock_rest._request.call_args_list
assert len(calls) > 0
last_data = calls[-1][1].get("data", {})
assert last_data.get("status") == "busy"
assert "2 Subagent" in last_data.get("message", "")
assert "testroom" in last_data.get("message", "")
# ═══════════════════════════════════════════════════════════════════════════
# Test: _read_subagent_count
# ═══════════════════════════════════════════════════════════════════════════
class TestReadSubagentCount:
"""Test: _read_subagent_count() liest subagent_status.json."""
def test_read_subagent_count_returns_zero_when_empty(self):
"""Leere Datei → 0."""
engine, _ = _make_engine()
# Clean state
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
_write_subagent_state(_get_subagent_state_path(), {
"active": [],
"last_change_iso": "",
"schema_version": 1,
"source": "plugin_internal",
})
assert engine._read_subagent_count() == 0
def test_read_subagent_count_returns_count(self):
"""Datei mit 2 Einträgen → 2."""
engine, _ = _make_engine()
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
_write_subagent_state(_get_subagent_state_path(), {
"active": [
{"task_id": "t_1", "type": "delegate_task"},
{"task_id": "t_2", "type": "terminal_background"},
],
"last_change_iso": "",
"schema_version": 1,
"source": "plugin_internal",
})
assert engine._read_subagent_count() == 2
def test_read_subagent_count_missing_file_returns_zero(self):
"""Fehlende Datei → 0 (graceful degradation)."""
engine, _ = _make_engine()
from plugin.archivar.subagent_tracker import _get_subagent_state_path
path = _get_subagent_state_path()
try:
os.unlink(path)
except OSError:
pass
assert engine._read_subagent_count() == 0