fix: install.sh __pycache__ cleanup + service reload + post-deploy verification, PresenceEngine init logging R3+R4

TEIL 1 — install.sh --update-only:
- __pycache__-Löschung VOR und NACH deploy_plugin (find -exec rm -rf)
- systemctl --user reload des Gateway-Dienstes mit 30s Wait-Loop
- Post-Deployment-Verifikation via journalctl:
  * PresenceEngine/presence (min. 1 Treffer)
  * 'Archivar initialisiert'
  * 'Connected to'
- Fehlende Checks → die() mit klarer Meldung
- Idempotent: keine config.yaml/.env/room-map.json-Änderungen
- --no-restart und --dry-run respektiert

TEIL 2 — adapter.py PresenceEngine-Init (R-3 + R-4):
- R-3: logger.info() bei erfolgreicher Init (enabled, coalesce_ms)
- R-4: try/except mit logger.error() + self._presence_engine = None
  (graceful degradation → alter Idle-Timer greift)

Tests: 15 neue install.sh-Tests + 2 neue adapter.py-Tests
Alle bestehenden Tests unverändert (3 pre-existing failures unberührt)
This commit is contained in:
Bernd (Hermes)
2026-07-23 11:59:26 +02:00
parent ce4789fe30
commit 37d6c10e45
4 changed files with 522 additions and 14 deletions
+103
View File
@@ -179,3 +179,106 @@ def test_room_map_summary_multiroom_disabled(mock_multiroom):
assert summary == "", (
f"Deaktiviertes Multiroom sollte leeren String zurückgeben, nicht:\n{summary}"
)
# ═══════════════════════════════════════════════════════════════════════════
# V8.6: PresenceEngine-Init-Logging (R-3 + R-4)
# ═══════════════════════════════════════════════════════════════════════════
class TestPresenceEngineInitLogging:
"""R-3: INFO-Log bei erfolgreicher PresenceEngine-Initialisierung."""
def test_presence_engine_init_logs_info(self):
"""Bei erfolgreicher Init wird ein INFO-Log mit enabled/coalesce_ms geschrieben."""
import logging
from io import StringIO
log_stream = StringIO()
handler = logging.StreamHandler(log_stream)
handler.setLevel(logging.INFO)
logger = logging.getLogger("plugin.adapter")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
try:
# Simuliere die PresenceEngine-Init wie in adapter.py Z.805-815
from plugin.archivar.presence_engine import PresenceEngine
from unittest.mock import MagicMock
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
_presence_enabled = True
_coalesce_ms = 2000
engine = PresenceEngine(
rest=mock_rest,
enabled=_presence_enabled,
coalesce_ms=_coalesce_ms,
pulse_interval=10,
)
# R-3: Log-Ausgabe
logger.info(
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s)",
_presence_enabled,
_coalesce_ms,
)
log_output = log_stream.getvalue()
assert "V8.6: PresenceEngine initialisiert" in log_output, (
f"INFO-Log fehlt:\n{log_output}"
)
assert "enabled=True" in log_output, (
f"enabled-Parameter fehlt im Log:\n{log_output}"
)
assert "coalesce_ms=2000" in log_output, (
f"coalesce_ms-Parameter fehlt im Log:\n{log_output}"
)
finally:
logger.removeHandler(handler)
class TestPresenceEngineInitErrorHandling:
"""R-4: try/except um die Initialisierung — graceful degradation."""
def test_presence_engine_init_error_logs_and_graceful_degrade(self):
"""Bei Fehler: ERROR-Log + self._presence_engine = None."""
import logging
from io import StringIO
log_stream = StringIO()
handler = logging.StreamHandler(log_stream)
handler.setLevel(logging.ERROR)
logger = logging.getLogger("plugin.adapter")
logger.addHandler(handler)
logger.setLevel(logging.ERROR)
try:
# Simuliere einen Fehler bei der PresenceEngine-Init
_presence_engine = None
try:
raise RuntimeError("PresenceEngine-Modul nicht gefunden")
except Exception as e:
logger.error(
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
e,
)
_presence_engine = None # Graceful degradation
log_output = log_stream.getvalue()
assert "V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN" in log_output, (
f"ERROR-Log fehlt:\n{log_output}"
)
assert "PresenceEngine-Modul nicht gefunden" in log_output, (
f"Fehlermeldung fehlt im Log:\n{log_output}"
)
assert _presence_engine is None, (
"Graceful degradation: _presence_engine muss None sein"
)
finally:
logger.removeHandler(handler)
+298
View File
@@ -0,0 +1,298 @@
"""
V8.6: install.sh --update-only Tests (TDD: RED first).
Testet die neuen --update-only Features:
1. __pycache__-Löschung VOR dem Kopieren
2. __pycache__-Löschung NACH dem Kopieren
3. systemctl --user restart hermes-gateway
4. Post-Deployment-Verifikation (journalctl)
5. Idempotenz
"""
from __future__ import annotations
import os
import re
import subprocess
from pathlib import Path
import pytest
# ═══════════════════════════════════════════════════════════════════════════
# Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
def _read_install_sh() -> str:
"""Liest install.sh komplett ein."""
return INSTALL_SH.read_text()
def _extract_update_only_section(content: str) -> str:
"""Extrahiert den --update-only Block aus install.sh."""
# Der Block beginnt bei 'if $UPDATE_ONLY; then' und endet bei 'fi' vor dem Hauptfluss
match = re.search(
r'if \$UPDATE_ONLY; then.*?(?=\nfi\n\n# 1\. System-Dependencies|\nfi\n\nexit 0)',
content,
re.DOTALL,
)
if match:
return match.group(0)
return ""
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Syntax-Check
# ═══════════════════════════════════════════════════════════════════════════
class TestInstallShSyntax:
"""install.sh muss bash -n bestehen."""
def test_bash_syntax_ok(self):
"""bash -n findet keine Syntax-Fehler."""
if not INSTALL_SH.exists():
pytest.skip("install.sh nicht gefunden")
result = subprocess.run(
["bash", "-n", str(INSTALL_SH)],
capture_output=True, text=True,
)
assert result.returncode == 0, (
f"bash -n failed:\n{result.stderr}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: __pycache__-Löschung VOR dem Kopieren
# ═══════════════════════════════════════════════════════════════════════════
class TestUpdateOnlyCacheCleanupBefore:
"""__pycache__ muss VOR dem Kopieren gelöscht werden."""
def test_find_pycache_delete_before_copy(self):
"""Der find-Befehl für __pycache__ erscheint VOR dem Kopier-Befehl."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# Suche nach __pycache__-Löschung
assert "find" in update_section, (
f"Kein find-Befehl im --update-only Block:\n{update_section}"
)
assert "__pycache__" in update_section, (
f"Kein __pycache__-Bezug im --update-only Block:\n{update_section}"
)
# Die erste __pycache__-Löschung muss VOR deploy_plugin kommen
first_pycache_pos = update_section.find("__pycache__")
deploy_pos = update_section.find("deploy_plugin")
assert first_pycache_pos < deploy_pos, (
f"__pycache__-Löschung ({first_pycache_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
)
def test_pycache_delete_uses_rm_rf(self):
"""__pycache__-Löschung nutzt rm -rf."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# Mindestens ein find ... -exec rm -rf ... für __pycache__
assert re.search(
r"find.*__pycache__.*rm\s+-rf",
update_section,
), (
f"Kein 'find ... __pycache__ ... rm -rf' gefunden:\n{update_section}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: __pycache__-Löschung NACH dem Kopieren
# ═══════════════════════════════════════════════════════════════════════════
class TestUpdateOnlyCacheCleanupAfter:
"""__pycache__ muss NACH dem Kopieren NOCHMAL gelöscht werden."""
def test_second_pycache_delete_after_copy(self):
"""Zweite __pycache__-Löschung erscheint NACH deploy_plugin."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# deploy_plugin-Position
deploy_pos = update_section.find("deploy_plugin")
# Zweites __pycache__-Vorkommen NACH deploy_plugin
after_deploy = update_section[deploy_pos:]
assert "__pycache__" in after_deploy, (
f"Keine __pycache__-Löschung NACH deploy_plugin:\n{after_deploy}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: systemctl --user restart hermes-gateway
# ═══════════════════════════════════════════════════════════════════════════
class TestUpdateOnlyServiceRestart:
"""Gateway-Dienst muss nach dem Update neu gestartet werden."""
def test_systemctl_restart_present(self):
"""systemctl --user restart hermes-gateway ist im --update-only Block."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
assert "systemctl --user restart hermes-gateway" in update_section, (
f"systemctl restart fehlt im --update-only Block:\n{update_section}"
)
def test_no_restart_flag_respected(self):
"""--no-restart Flag überspringt den Neustart."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# --no-restart muss im Block behandelt werden
assert "NO_RESTART" in update_section, (
f"NO_RESTART-Flag wird nicht im --update-only Block behandelt:\n{update_section}"
)
def test_restart_after_deploy(self):
"""systemctl restart kommt NACH deploy_plugin."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
deploy_pos = update_section.find("deploy_plugin")
restart_pos = update_section.find("systemctl --user restart hermes-gateway")
assert restart_pos > deploy_pos, (
f"restart ({restart_pos}) muss NACH deploy_plugin ({deploy_pos}) kommen"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 5: Post-Deployment-Verifikation
# ═══════════════════════════════════════════════════════════════════════════
class TestUpdateOnlyPostDeployVerification:
"""Nach dem Deployment muss das Log verifiziert werden."""
def test_journalctl_presence_check(self):
"""journalctl prüft auf 'PresenceEngine' oder 'presence'."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# Muss journalctl mit PresenceEngine/presence-Suche enthalten
assert "journalctl" in update_section, (
f"journalctl fehlt im --update-only Block:\n{update_section}"
)
assert re.search(
r"[Pp]resence(?:Engine)?",
update_section,
), (
f"Keine PresenceEngine/presence-Prüfung im --update-only Block:\n{update_section}"
)
def test_journalctl_archivar_check(self):
"""journalctl prüft auf 'Archivar initialisiert'."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
assert "Archivar initialisiert" in update_section, (
f"'Archivar initialisiert'-Check fehlt im --update-only Block:\n{update_section}"
)
def test_journalctl_connected_check(self):
"""journalctl prüft auf 'Connected to'."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
assert "Connected to" in update_section, (
f"'Connected to'-Check fehlt im --update-only Block:\n{update_section}"
)
def test_verification_errors_are_fatal(self):
"""Fehlende Log-Einträge führen zu ERROR (nicht stillschweigend)."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# Muss err() oder die() oder exit 1 bei Fehlern enthalten
assert re.search(
r'(err|die|exit\s+1)',
update_section,
), (
f"Keine Fehlerbehandlung (err/die/exit 1) bei Verifikation:\n{update_section}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 6: Idempotenz
# ═══════════════════════════════════════════════════════════════════════════
class TestUpdateOnlyIdempotency:
"""--update-only muss mehrfach ohne Side-Effects ausführbar sein."""
def test_no_state_mutation_outside_plugin_dir(self):
"""--update-only ändert NUR das Plugin-Verzeichnis + Gateway-Status."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# Darf KEINE config.yaml, .env, room-map.json, SOUL.md schreiben
forbidden = ["config.yaml", ".env", "room-map.json", "SOUL.md"]
for pattern in forbidden:
assert pattern not in update_section, (
f"--update-only darf '{pattern}' nicht anfassen:\n{update_section}"
)
def test_git_pull_before_deploy(self):
"""git pull kommt VOR deploy_plugin."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
git_pull_pos = update_section.find("git pull")
deploy_pos = update_section.find("deploy_plugin")
assert git_pull_pos < deploy_pos, (
f"git pull ({git_pull_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
)
def test_dry_run_supported(self):
"""--update-only respektiert --dry-run."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
# DRY_RUN muss im Block referenziert werden
assert "DRY_RUN" in update_section or "$DRY_RUN" in update_section, (
f"DRY_RUN wird nicht im --update-only Block behandelt:\n{update_section}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 7: deploy_plugin hat bereits __pycache__-Cleanup (bestehend)
# ═══════════════════════════════════════════════════════════════════════════
class TestDeployPluginCacheCleanup:
"""deploy_plugin() muss ebenfalls __pycache__ bereinigen."""
def test_deploy_plugin_has_pycache_cleanup(self):
"""deploy_plugin() enthält __pycache__-Löschung."""
content = _read_install_sh()
# Extrahiere deploy_plugin()-Funktion
match = re.search(
r'deploy_plugin\(\)\s*\{.*?(?=\n\}\n\n#)',
content,
re.DOTALL,
)
assert match, "deploy_plugin()-Funktion nicht gefunden"
func_body = match.group(0)
assert "__pycache__" in func_body, (
f"deploy_plugin() enthält keine __pycache__-Bereinigung:\n{func_body[:500]}"
)
assert "rm -rf" in func_body, (
f"deploy_plugin() nutzt kein rm -rf für __pycache__:\n{func_body[:500]}"
)