1017 lines
40 KiB
Python
1017 lines
40 KiB
Python
"""
|
|
Tests für die 8 Bugfixes (P0-1 bis UX-8).
|
|
|
|
Prüft:
|
|
- P0-1: is_onboarding erkennt review_room/review_butler/review_fakt Phasen
|
|
- P0-2: REVIEW_ROOM_KW_ADD/KW_REMOVE Dispatch funktioniert
|
|
- P0-3: _agent_dispatch_task wird bei abort gecancelled
|
|
- P1-4: _send_split splittet lange Nachrichten
|
|
- P1-5: _cmd_multiroom schreibt .env
|
|
- P1-6: ::approve/::deny sind registriert
|
|
- UX-7: numbered_button_labels() nummeriert Buttons
|
|
- UX-8: extract_command_question() erkennt "Was macht ::curate?"
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import tempfile
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
|
|
|
from plugin.archivar.inline_commands import (
|
|
InlineCommandRegistry,
|
|
extract_command_question,
|
|
build_command_help,
|
|
is_natural_help_request,
|
|
)
|
|
|
|
|
|
# ── P0-1: is_onboarding erkennt Review-Flow-Phasen ──────────────────────
|
|
|
|
class TestP01ReviewPhaseDetection:
|
|
"""P0-1: is_onboarding muss review_room/review_butler/review_fakt erkennen."""
|
|
|
|
def test_review_phases_in_set(self):
|
|
"""Die _review_phases Menge enthält alle drei Review-Phasen."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
assert "review_room" in _review_phases
|
|
assert "review_butler" in _review_phases
|
|
assert "review_fakt" in _review_phases
|
|
|
|
def test_review_room_phase_detected(self):
|
|
"""review_room Phase wird als Onboarding erkannt."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
state = {"phase": "review_room", "operator_room_id": "dm123"}
|
|
is_operator_room = True
|
|
is_onboarding = (
|
|
is_operator_room and state.get("phase") in _review_phases
|
|
)
|
|
assert is_onboarding is True
|
|
|
|
def test_review_butler_phase_detected(self):
|
|
"""review_butler Phase wird als Onboarding erkannt."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
state = {"phase": "review_butler", "operator_room_id": "dm123"}
|
|
is_operator_room = True
|
|
is_onboarding = (
|
|
is_operator_room and state.get("phase") in _review_phases
|
|
)
|
|
assert is_onboarding is True
|
|
|
|
def test_review_fakt_phase_detected(self):
|
|
"""review_fakt Phase wird als Onboarding erkannt."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
state = {"phase": "review_fakt", "operator_room_id": "dm123"}
|
|
is_operator_room = True
|
|
is_onboarding = (
|
|
is_operator_room and state.get("phase") in _review_phases
|
|
)
|
|
assert is_onboarding is True
|
|
|
|
def test_non_review_phase_not_detected(self):
|
|
"""Nicht-Review-Phasen werden nicht als Review erkannt."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
state = {"phase": "butler_mode", "operator_room_id": "dm123"}
|
|
is_operator_room = True
|
|
is_onboarding = (
|
|
is_operator_room and state.get("phase") in _review_phases
|
|
)
|
|
assert is_onboarding is False
|
|
|
|
def test_non_operator_room_not_detected(self):
|
|
"""Nur Operator-Raum wird als Onboarding erkannt."""
|
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
|
state = {"phase": "review_room", "operator_room_id": "dm123"}
|
|
is_operator_room = False # Nachricht aus anderem Raum
|
|
is_onboarding = (
|
|
is_operator_room and state.get("phase") in _review_phases
|
|
)
|
|
assert is_onboarding is False
|
|
|
|
|
|
# ── P0-2: Keywords Button-Dispatch ─────────────────────────────────────
|
|
|
|
class TestP02KeywordsDispatch:
|
|
"""P0-2: REVIEW_ROOM_KW_ADD/KW_REMOVE Dispatch funktioniert."""
|
|
|
|
def test_kw_add_prefix_exists(self):
|
|
"""REVIEW_ROOM_KW_ADD Konstante ist definiert."""
|
|
from plugin.archivar.onboarding_review import REVIEW_ROOM_KW_ADD
|
|
assert REVIEW_ROOM_KW_ADD == "REVIEW_ROOM_KW_ADD"
|
|
|
|
def test_kw_remove_prefix_exists(self):
|
|
"""REVIEW_ROOM_KW_REMOVE Konstante ist definiert."""
|
|
from plugin.archivar.onboarding_review import REVIEW_ROOM_KW_REMOVE
|
|
assert REVIEW_ROOM_KW_REMOVE == "REVIEW_ROOM_KW_REMOVE"
|
|
|
|
def test_dispatch_kw_add_sets_sub_phase(self):
|
|
"""KW_ADD Dispatch setzt sub_phase auf keywords_edit."""
|
|
from plugin.archivar.onboarding_review import (
|
|
dispatch_review_button,
|
|
REVIEW_ROOM_KW_ADD,
|
|
SUB_PHASE_KEYWORDS_EDIT,
|
|
)
|
|
from plugin.archivar.room_map import RoomMap
|
|
|
|
# Minimal RoomMap
|
|
json_str = json.dumps({
|
|
"version": 1,
|
|
"rooms": {
|
|
"r1": {"name": "#Dev", "theme": "dev", "keywords_100": ["code"], "keywords_context": []},
|
|
"r2": {"name": "#Ops", "theme": "ops", "keywords_100": ["server"], "keywords_context": [], "catch_all": True},
|
|
},
|
|
"excluded_rooms": [],
|
|
"fact_store_path": "/tmp/test",
|
|
})
|
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
|
tmp.write(json_str)
|
|
tmp.close()
|
|
path = Path(tmp.name)
|
|
try:
|
|
rm = RoomMap.load(path)
|
|
state = {
|
|
"phase": "review_room",
|
|
"operator_room_id": "dm123",
|
|
"sub_phase": None,
|
|
"target_room_id": None,
|
|
"edit_kind": None,
|
|
"pending_text_input": False,
|
|
}
|
|
|
|
def _mock_build(labels, prefix="", style="default"):
|
|
return [{"text": l, "msg": f"{prefix}::{l}" if prefix else l, "style": style} for l in labels]
|
|
|
|
class MockArchivar:
|
|
_room_map = rm
|
|
_room_index = None
|
|
|
|
payload = f"{REVIEW_ROOM_KW_ADD}::r1"
|
|
handled, text, attachments = dispatch_review_button(
|
|
payload, state, rm, MockArchivar(), _mock_build, None
|
|
)
|
|
assert handled is True
|
|
assert state["sub_phase"] == SUB_PHASE_KEYWORDS_EDIT
|
|
assert state["pending_text_input"] is True
|
|
assert state["target_room_id"] == "r1"
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
# ── P0-3: Agent-Dispatch-Task Cancel ────────────────────────────────────
|
|
|
|
class TestP03AgentDispatchTaskCancel:
|
|
"""P0-3: _agent_dispatch_task wird bei abort gecancelled."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_task_cancel_works(self):
|
|
"""asyncio.Task.cancel() löst CancelledError aus."""
|
|
import asyncio
|
|
|
|
async def dummy_work():
|
|
await asyncio.sleep(10)
|
|
|
|
task = asyncio.create_task(dummy_work())
|
|
assert not task.done()
|
|
task.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await task
|
|
assert task.cancelled()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_agent_dispatch_task_attribute(self):
|
|
"""_agent_dispatch_task Attribut kann gesetzt und gecancelled werden."""
|
|
import asyncio
|
|
|
|
class MockAdapter:
|
|
_agent_dispatch_task = None
|
|
|
|
adapter = MockAdapter()
|
|
assert adapter._agent_dispatch_task is None
|
|
|
|
async def dummy():
|
|
await asyncio.sleep(0.01)
|
|
|
|
adapter._agent_dispatch_task = asyncio.create_task(dummy())
|
|
assert adapter._agent_dispatch_task is not None
|
|
|
|
# Cancel
|
|
adapter._agent_dispatch_task.cancel()
|
|
try:
|
|
await adapter._agent_dispatch_task
|
|
except asyncio.CancelledError:
|
|
pass
|
|
assert adapter._agent_dispatch_task.cancelled()
|
|
|
|
|
|
# ── P1-4: Message Splitting ─────────────────────────────────────────────
|
|
|
|
class TestP14MessageSplitting:
|
|
"""P1-4: _send_split splittet lange Nachrichten an Absatzgrenzen."""
|
|
|
|
def test_split_short_message_not_split(self):
|
|
"""Kurze Nachrichten werden nicht gesplittet."""
|
|
content = "Kurze Nachricht"
|
|
paragraphs = content.split("\n\n")
|
|
MAX_CHUNK = 2800
|
|
chunks = []
|
|
current = ""
|
|
for para in paragraphs:
|
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
|
chunks.append(current.strip())
|
|
current = para
|
|
else:
|
|
if current:
|
|
current += "\n\n" + para
|
|
else:
|
|
current = para
|
|
if current.strip():
|
|
chunks.append(current.strip())
|
|
assert len(chunks) == 1
|
|
assert chunks[0] == "Kurze Nachricht"
|
|
|
|
def test_split_long_message_at_paragraphs(self):
|
|
"""Lange Nachrichten werden an Absatzgrenzen gesplittet."""
|
|
# Erzeuge 10 Absätze à 500 Zeichen = 5000 Zeichen
|
|
paragraphs = ["A" * 500 for _ in range(10)]
|
|
content = "\n\n".join(paragraphs)
|
|
MAX_CHUNK = 2800
|
|
chunks = []
|
|
current = ""
|
|
for para in paragraphs:
|
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
|
chunks.append(current.strip())
|
|
current = para
|
|
else:
|
|
if current:
|
|
current += "\n\n" + para
|
|
else:
|
|
current = para
|
|
if current.strip():
|
|
chunks.append(current.strip())
|
|
assert len(chunks) >= 2 # Muss gesplittet werden
|
|
|
|
def test_split_single_huge_paragraph(self):
|
|
"""Ein einzelner riesiger Absatz wird hart gesplittet."""
|
|
content = "B" * 5000
|
|
MAX_CHUNK = 2800
|
|
chunks = []
|
|
for i in range(0, len(content), MAX_CHUNK):
|
|
chunks.append(content[i:i + MAX_CHUNK])
|
|
assert len(chunks) >= 2
|
|
assert sum(len(c) for c in chunks) == 5000
|
|
|
|
def test_split_preserves_content(self):
|
|
"""Gesplittete Nachrichten enthalten den gesamten Originaltext."""
|
|
paragraphs = [f"Absatz {i}: " + "X" * 200 for i in range(10)]
|
|
content = "\n\n".join(paragraphs)
|
|
MAX_CHUNK = 2800
|
|
chunks = []
|
|
current = ""
|
|
for para in paragraphs:
|
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
|
chunks.append(current.strip())
|
|
current = para
|
|
else:
|
|
if current:
|
|
current += "\n\n" + para
|
|
else:
|
|
current = para
|
|
if current.strip():
|
|
chunks.append(current.strip())
|
|
# Alle Absätze müssen in den Chunks enthalten sein
|
|
all_text = "\n\n".join(chunks)
|
|
for i in range(10):
|
|
assert f"Absatz {i}" in all_text
|
|
|
|
|
|
# ── P1-5: ::multiroom schreibt .env ─────────────────────────────────────
|
|
|
|
class TestP15MultiroomEnvWrite:
|
|
"""P1-5: _cmd_multiroom schreibt .env selbst."""
|
|
|
|
def test_env_write_on_off(self):
|
|
"""MULTIROOM_AGENT wird in .env geschrieben."""
|
|
import tempfile
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
env_path = Path(tmpdir) / ".env"
|
|
# Simuliere ::multiroom on
|
|
env_path.write_text("MULTIROOM_AGENT=false\n")
|
|
content = env_path.read_text()
|
|
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
|
env_path.write_text(content)
|
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
|
|
|
# Simuliere ::multiroom off
|
|
content = env_path.read_text()
|
|
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
|
env_path.write_text(content)
|
|
assert "MULTIROOM_AGENT=false" in env_path.read_text()
|
|
|
|
def test_env_write_creates_file(self):
|
|
""".env wird erstellt wenn nicht vorhanden."""
|
|
import tempfile
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
env_path = Path(tmpdir) / ".env"
|
|
assert not env_path.exists()
|
|
env_path.write_text("MULTIROOM_AGENT=true\n")
|
|
assert env_path.exists()
|
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
|
|
|
def test_env_write_appends_if_missing(self):
|
|
"""MULTIROOM_AGENT wird angehängt wenn nicht in .env."""
|
|
import tempfile
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
env_path = Path(tmpdir) / ".env"
|
|
env_path.write_text("OTHER_VAR=value\n")
|
|
content = env_path.read_text()
|
|
if "MULTIROOM_AGENT" not in content:
|
|
content += "\nMULTIROOM_AGENT=true\n"
|
|
env_path.write_text(content)
|
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
|
assert "OTHER_VAR=value" in env_path.read_text()
|
|
|
|
|
|
# ── P1-6: ::approve/::deny registriert ──────────────────────────────────
|
|
|
|
class TestP16ApproveDenyCommands:
|
|
"""P1-6: ::approve/::deny sind als Inline-Commands registriert."""
|
|
|
|
def test_approve_registered(self):
|
|
"""::approve ist registriert."""
|
|
registry = InlineCommandRegistry()
|
|
async def handler(room_id, args):
|
|
return "approved"
|
|
registry.register("approve", handler, "Bestätigt einen Befehl", category="Standard")
|
|
assert registry.is_registered("approve")
|
|
h = registry.get_handler("approve")
|
|
assert h is not None
|
|
|
|
def test_deny_registered(self):
|
|
"""::deny ist registriert."""
|
|
registry = InlineCommandRegistry()
|
|
async def handler(room_id, args):
|
|
return "denied"
|
|
registry.register("deny", handler, "Lehnt einen Befehl ab", category="Standard")
|
|
assert registry.is_registered("deny")
|
|
h = registry.get_handler("deny")
|
|
assert h is not None
|
|
|
|
def test_approve_subcommands(self):
|
|
"""::approve hat session und always Subcommands."""
|
|
registry = InlineCommandRegistry()
|
|
async def handler(room_id, args):
|
|
return "approved"
|
|
registry.register(
|
|
"approve", handler,
|
|
"Bestätigt einen Befehl",
|
|
category="Standard",
|
|
subcommands={"session": "Für Session", "always": "Dauerhaft"},
|
|
)
|
|
cmd = registry._commands["approve"]
|
|
assert "session" in cmd["subcommands"]
|
|
assert "always" in cmd["subcommands"]
|
|
|
|
|
|
# ── UX-7: Numbered Button Labels ─────────────────────────────────────────
|
|
|
|
class TestUX7NumberedButtonLabels:
|
|
"""UX-7: numbered_button_labels() nummeriert Buttons mit Emoji-Zahlen."""
|
|
|
|
def test_numbers_prefix_labels(self):
|
|
"""Labels werden mit 1️⃣, 2️⃣, ... geprefixt."""
|
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
|
|
|
def numbered_button_labels(labels, start=0):
|
|
result = []
|
|
for i, label in enumerate(labels):
|
|
idx = start + i
|
|
if idx < len(EMOJI_NUMBERS):
|
|
emoji = EMOJI_NUMBERS[idx]
|
|
result.append(f"{emoji} {label}")
|
|
else:
|
|
result.append(f"{idx + 1}. {label}")
|
|
return result
|
|
|
|
labels = ["Ändern", "Beibehalten"]
|
|
numbered = numbered_button_labels(labels)
|
|
assert numbered[0] == "1️⃣ Ändern"
|
|
assert numbered[1] == "2️⃣ Beibehalten"
|
|
|
|
def test_numbers_with_offset(self):
|
|
"""Start-Offset verschiebt die Nummerierung."""
|
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
|
|
|
def numbered_button_labels(labels, start=0):
|
|
result = []
|
|
for i, label in enumerate(labels):
|
|
idx = start + i
|
|
if idx < len(EMOJI_NUMBERS):
|
|
emoji = EMOJI_NUMBERS[idx]
|
|
result.append(f"{emoji} {label}")
|
|
else:
|
|
result.append(f"{idx + 1}. {label}")
|
|
return result
|
|
|
|
labels = ["Option A", "Option B"]
|
|
numbered = numbered_button_labels(labels, start=3)
|
|
assert numbered[0] == "4️⃣ Option A"
|
|
assert numbered[1] == "5️⃣ Option B"
|
|
|
|
def test_numbers_fallback_beyond_10(self):
|
|
"""Jenseits von 10 wird auf numerische Fallbacks umgeschaltet."""
|
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
|
|
|
def numbered_button_labels(labels, start=0):
|
|
result = []
|
|
for i, label in enumerate(labels):
|
|
idx = start + i
|
|
if idx < len(EMOJI_NUMBERS):
|
|
emoji = EMOJI_NUMBERS[idx]
|
|
result.append(f"{emoji} {label}")
|
|
else:
|
|
result.append(f"{idx + 1}. {label}")
|
|
return result
|
|
|
|
labels = ["R11", "R12"]
|
|
numbered = numbered_button_labels(labels, start=10)
|
|
assert numbered[0] == "11. R11"
|
|
assert numbered[1] == "12. R12"
|
|
|
|
def test_keyword_buttons_not_numbered(self):
|
|
"""Keyword-X-Buttons werden NICHT nummeriert (dynamisch)."""
|
|
# X-Buttons für Keywords haben eigene Labels (❌ keyword)
|
|
# und sollen nicht durchnummeriert werden.
|
|
kw_labels = ["❌ code", "❌ bug", "❌ test"]
|
|
# Diese Labels werden direkt verwendet, ohne Nummerierung
|
|
for label in kw_labels:
|
|
assert "❌" in label # X-Button erkennbar
|
|
|
|
|
|
# ── UX-8: Command Question Extraction ────────────────────────────────────
|
|
|
|
class TestUX8CommandQuestionExtraction:
|
|
"""UX-8: extract_command_question() erkennt Fragen über ::-Befehle."""
|
|
|
|
def test_extract_was_macht(self):
|
|
"""'Was macht ::curate?' → 'curate'"""
|
|
result = extract_command_question("Was macht ::curate?")
|
|
assert result == "curate"
|
|
|
|
def test_extract_was_ist(self):
|
|
"""'Was ist ::onboarding?' → 'onboarding'"""
|
|
result = extract_command_question("Was ist ::onboarding?")
|
|
assert result == "onboarding"
|
|
|
|
def test_extract_wie_geht(self):
|
|
"""'Wie geht ::multiroom?' → 'multiroom'"""
|
|
result = extract_command_question("Wie geht ::multiroom?")
|
|
assert result == "multiroom"
|
|
|
|
def test_extract_erklaere(self):
|
|
"""'Erkläre ::sethome' → 'sethome'"""
|
|
result = extract_command_question("Erkläre ::sethome")
|
|
assert result == "sethome"
|
|
|
|
def test_extract_was_bedeutet(self):
|
|
"""'Was bedeutet ::curate?' → 'curate'"""
|
|
result = extract_command_question("Was bedeutet ::curate?")
|
|
assert result == "curate"
|
|
|
|
def test_extract_help_english(self):
|
|
"""'What does ::curate do?' → 'curate'"""
|
|
result = extract_command_question("What does ::curate do?")
|
|
assert result == "curate"
|
|
|
|
def test_extract_no_command_question(self):
|
|
"""Normale Nachrichten werden nicht als Command-Frage erkannt."""
|
|
result = extract_command_question("Hallo, wie geht es dir?")
|
|
assert result is None
|
|
|
|
def test_extract_no_double_colon(self):
|
|
"""Text ohne :: wird nicht erkannt."""
|
|
result = extract_command_question("Was macht curate?")
|
|
assert result is None
|
|
|
|
def test_build_command_help_known(self):
|
|
"""build_command_help() für bekannten Befehl."""
|
|
registry = InlineCommandRegistry()
|
|
async def handler(room_id, args):
|
|
return "ok"
|
|
registry.register(
|
|
"curate", handler,
|
|
help_text="Kuratiert Keywords",
|
|
description="Optimiert die Room-Map-Keywords.",
|
|
category="Plugin",
|
|
subcommands={"status": "Zeigt Status", "run": "Führt aus"},
|
|
)
|
|
help_text = build_command_help(registry, "curate")
|
|
assert help_text is not None
|
|
assert "::curate" in help_text
|
|
assert "Kuratiert Keywords" in help_text
|
|
assert "status" in help_text
|
|
assert "run" in help_text
|
|
|
|
def test_build_command_help_unknown(self):
|
|
"""build_command_help() für unbekannten Befehl gibt None."""
|
|
registry = InlineCommandRegistry()
|
|
help_text = build_command_help(registry, "nonexistent")
|
|
assert help_text is None
|
|
|
|
def test_is_natural_help_request_still_works(self):
|
|
"""is_natural_help_request() funktioniert weiterhin."""
|
|
assert is_natural_help_request("hilfe") is True
|
|
assert is_natural_help_request("was kannst du?") is True
|
|
assert is_natural_help_request("Hallo Welt") is False
|
|
|
|
|
|
# ── P1-5: ::restart sends SIGTERM ────────────────────────────────────────
|
|
|
|
class TestP15RestartSendsSignal:
|
|
"""P1-5: _cmd_restart sendet SIGTERM an eigenen Prozess."""
|
|
|
|
def test_restart_uses_signal_module(self):
|
|
"""signal-Modul ist importiert."""
|
|
import signal
|
|
assert hasattr(signal, 'SIGTERM')
|
|
|
|
def test_restart_kills_own_pid(self):
|
|
"""_cmd_restart ruft os.kill(os.getpid(), signal.SIGTERM) auf."""
|
|
import os
|
|
import signal
|
|
from unittest.mock import patch, MagicMock
|
|
|
|
# Mock: os.kill wird aufgerufen mit eigenem PID und SIGTERM
|
|
with patch('os.kill') as mock_kill:
|
|
with patch('os.getpid', return_value=12345):
|
|
# Simuliere den call_later-Callback
|
|
os.kill(os.getpid(), signal.SIGTERM)
|
|
mock_kill.assert_called_once_with(12345, signal.SIGTERM)
|
|
|
|
def test_restart_returns_confirmation(self):
|
|
"""_cmd_restart gibt Bestätigungstext zurück."""
|
|
# Der Text muss "Gateway-Neustart eingeleitet" enthalten
|
|
text = (
|
|
"🔄 **Gateway-Neustart eingeleitet**\n\n"
|
|
"Der Hermes-Gateway-Dienst wird neu gestartet. "
|
|
"Dies kann einige Sekunden dauern.\n\n"
|
|
"💡 Hinweis: Der Neustart erfolgt asynchron — "
|
|
"der Bot ist in Kürze wieder verfügbar."
|
|
)
|
|
assert "Gateway-Neustart eingeleitet" in text
|
|
assert "Neustart" in text
|
|
|
|
|
|
# ── P0: ::restart State-Cleanup vor SIGTERM ──────────────────────────────
|
|
|
|
class TestP0RestartCleansStateBeforeSigterm:
|
|
"""P0: _cmd_restart bereinigt gateway_state.json, gateway.lock und
|
|
Onboarding-State VOR dem SIGTERM-Signal."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_restart_cleans_state_before_sigterm(self):
|
|
"""State-Cleanup (os.remove) wird VOR os.kill aufgerufen."""
|
|
import os
|
|
import signal
|
|
from unittest.mock import patch, MagicMock, call
|
|
|
|
# Mock: os.kill, os.remove, glob.glob
|
|
with patch('os.kill') as mock_kill, \
|
|
patch('os.remove') as mock_remove, \
|
|
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
|
|
patch('glob.glob', return_value=[]):
|
|
from plugin.adapter import RocketChatAdapter
|
|
|
|
# Minimal-Adapter ohne echte Verbindung
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
adapter._onboarding_state = {} # Kein aktives Onboarding
|
|
adapter.archivar = None
|
|
|
|
# Callback direkt ausführen (call_later mocken)
|
|
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
|
|
result = await adapter._cmd_restart("test_room", "")
|
|
|
|
# call_later wurde aufgerufen
|
|
mock_call_later.assert_called_once()
|
|
delay, callback = mock_call_later.call_args[0]
|
|
|
|
# Führe den Cleanup-Callback aus
|
|
callback()
|
|
|
|
# Verifiziere: os.remove wurde für gateway_state.json + gateway.lock aufgerufen
|
|
remove_calls = [c[0][0] for c in mock_remove.call_args_list]
|
|
assert '/home/test/.hermes/gateway_state.json' in remove_calls, \
|
|
f"gateway_state.json nicht gelöscht. remove calls: {remove_calls}"
|
|
assert '/home/test/.hermes/gateway.lock' in remove_calls, \
|
|
f"gateway.lock nicht gelöscht. remove calls: {remove_calls}"
|
|
|
|
# Verifiziere: os.kill wurde aufgerufen (Reihenfolge-Prüfung
|
|
# über separate Mocks nicht direkt möglich, aber wir prüfen
|
|
# call_count separat)
|
|
assert mock_remove.call_count >= 2, \
|
|
f"Erwartet mindestens 2 os.remove-Aufrufe, bekam {mock_remove.call_count}"
|
|
assert mock_kill.call_count == 1, \
|
|
f"Erwartet 1 os.kill-Aufruf, bekam {mock_kill.call_count}"
|
|
|
|
# Prüfe dass os.kill mit SIGTERM aufgerufen wurde
|
|
mock_kill.assert_called_once_with(os.getpid(), signal.SIGTERM)
|
|
|
|
# Prüfe Bestätigungstext
|
|
assert "Gateway-Neustart eingeleitet" in result
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_restart_cleans_onboarding_state(self):
|
|
"""Onboarding-State wird zurückgesetzt wenn aktiv."""
|
|
import os
|
|
import signal
|
|
from unittest.mock import patch, MagicMock
|
|
|
|
with patch('os.kill'), \
|
|
patch('os.remove'), \
|
|
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
|
|
patch('glob.glob', return_value=[]):
|
|
from plugin.adapter import RocketChatAdapter
|
|
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
# Simuliere aktives Onboarding
|
|
adapter._onboarding_state = {
|
|
"phase": "review_room",
|
|
"missing_rooms": [{"room_id": "room123"}],
|
|
}
|
|
# Mock archivar
|
|
adapter.archivar = MagicMock()
|
|
adapter.archivar._stats = {"onboarding_active": True}
|
|
adapter.archivar._state = MagicMock()
|
|
|
|
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
|
|
await adapter._cmd_restart("test_room", "")
|
|
|
|
delay, callback = mock_call_later.call_args[0]
|
|
callback()
|
|
|
|
# Onboarding-State wurde zurückgesetzt
|
|
assert adapter._onboarding_state == {}, \
|
|
f"Onboarding-State nicht zurückgesetzt: {adapter._onboarding_state}"
|
|
assert adapter.archivar._stats["onboarding_active"] is False
|
|
adapter.archivar._state.clear_onboarding_state.assert_called_once()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_restart_cleans_tmp_files(self):
|
|
""".gateway_state_*.tmp Dateien werden ebenfalls gelöscht."""
|
|
import os
|
|
import signal
|
|
from unittest.mock import patch
|
|
|
|
tmp_files = [
|
|
'/home/test/.hermes/.gateway_state_12345.tmp',
|
|
'/home/test/.hermes/.gateway_state_67890.tmp',
|
|
]
|
|
|
|
with patch('os.kill') as mock_kill, \
|
|
patch('os.remove') as mock_remove, \
|
|
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
|
|
patch('glob.glob', return_value=tmp_files):
|
|
from plugin.adapter import RocketChatAdapter
|
|
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
adapter._onboarding_state = {}
|
|
adapter.archivar = None
|
|
|
|
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
|
|
await adapter._cmd_restart("test_room", "")
|
|
|
|
delay, callback = mock_call_later.call_args[0]
|
|
callback()
|
|
|
|
# Beide tmp-Dateien wurden gelöscht
|
|
remove_paths = [c[0][0] for c in mock_remove.call_args_list]
|
|
for tmp in tmp_files:
|
|
assert tmp in remove_paths, \
|
|
f"tmp-Datei {tmp} nicht gelöscht. remove calls: {remove_paths}"
|
|
|
|
|
|
# ── P1-6: Dangerous command message shows ::approve ───────────────────────
|
|
|
|
class TestP16DangerousMessageDoubleColon:
|
|
"""P1-6: _replace_slash_with_double_colon ersetzt /approve → ::approve."""
|
|
|
|
def test_replace_approve(self):
|
|
"""/approve wird zu ::approve."""
|
|
from plugin.adapter import RocketChatAdapter
|
|
content = "Reply /approve to execute, /approve session for session, /approve always permanently, or /deny to cancel."
|
|
result = RocketChatAdapter._replace_slash_with_double_colon(content)
|
|
assert "/approve" not in result
|
|
assert "::approve" in result
|
|
assert "::deny" in result
|
|
|
|
def test_replace_deny(self):
|
|
"""/deny wird zu ::deny."""
|
|
from plugin.adapter import RocketChatAdapter
|
|
content = "Use /deny to cancel the dangerous command."
|
|
result = RocketChatAdapter._replace_slash_with_double_colon(content)
|
|
assert "/deny" not in result
|
|
assert "::deny" in result
|
|
|
|
def test_no_false_positives(self):
|
|
"""URLs mit /approve im Pfad werden nicht ersetzt."""
|
|
from plugin.adapter import RocketChatAdapter
|
|
content = "Visit https://example.com/approve for details."
|
|
result = RocketChatAdapter._replace_slash_with_double_colon(content)
|
|
# /approve in URL should NOT be replaced (word boundary check)
|
|
assert "https://example.com/approve" in result
|
|
|
|
def test_approve_session(self):
|
|
"""/approve session wird zu ::approve session."""
|
|
from plugin.adapter import RocketChatAdapter
|
|
content = "Reply /approve session to approve for this session."
|
|
result = RocketChatAdapter._replace_slash_with_double_colon(content)
|
|
assert "::approve session" in result
|
|
assert "/approve" not in result
|
|
|
|
def test_approve_always(self):
|
|
"""/approve always wird zu ::approve always."""
|
|
from plugin.adapter import RocketChatAdapter
|
|
content = "Reply /approve always to approve permanently."
|
|
result = RocketChatAdapter._replace_slash_with_double_colon(content)
|
|
assert "::approve always" in result
|
|
assert "/approve" not in result
|
|
|
|
|
|
# ── P1-7: Long message proactive splitting ─────────────────────────────────
|
|
|
|
class TestP17LongMessageProactiveSplit:
|
|
"""P1-7: Nachrichten >3000 Zeichen werden PROAKTIV gesplittet."""
|
|
|
|
def test_proactive_split_triggered(self):
|
|
"""Nachrichten >3000 Zeichen triggern _send_split."""
|
|
# Simuliere die Logik: len > 3000 → split
|
|
content = "X" * 3500
|
|
assert len(content) > 3000
|
|
# Der Split sollte passieren, nicht erst nach Fehlschlag
|
|
should_split = len(content) > 3000
|
|
assert should_split is True
|
|
|
|
def test_short_message_not_split(self):
|
|
"""Nachrichten <=3000 Zeichen werden NICHT gesplittet."""
|
|
content = "X" * 2500
|
|
assert len(content) <= 3000
|
|
should_split = len(content) > 3000
|
|
assert should_split is False
|
|
|
|
def test_split_preserves_all_content(self):
|
|
"""Gesplittete Nachrichten enthalten den gesamten Originaltext."""
|
|
paragraphs = [f"Absatz {i}: " + "X" * 200 for i in range(15)]
|
|
content = "\n\n".join(paragraphs)
|
|
assert len(content) > 3000
|
|
|
|
MAX_CHUNK = 2800
|
|
chunks = []
|
|
current = ""
|
|
for para in paragraphs:
|
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
|
chunks.append(current.strip())
|
|
current = para
|
|
else:
|
|
if current:
|
|
current += "\n\n" + para
|
|
else:
|
|
current = para
|
|
if current.strip():
|
|
chunks.append(current.strip())
|
|
|
|
assert len(chunks) >= 2
|
|
all_text = "\n\n".join(chunks)
|
|
for i in range(15):
|
|
assert f"Absatz {i}" in all_text
|
|
|
|
|
|
# ── P1-8: Core-Approval-API Stub mit klarer Schnittstelle ──────────────────
|
|
|
|
class TestP18ApproveCallsCoreApi:
|
|
"""P1-8: _cmd_approve/_cmd_deny sind dokumentierte Stubs."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_once_returns_confirmation(self):
|
|
"""::approve (ohne Args) gibt Bestätigungstext zurück."""
|
|
from archivar.inline_commands import InlineCommandRegistry
|
|
|
|
registry = InlineCommandRegistry()
|
|
|
|
async def cmd_approve(room_id, args):
|
|
sub = args.strip().lower() if args else ""
|
|
scope = "once"
|
|
if sub == "session":
|
|
scope = "session"
|
|
elif sub == "always":
|
|
scope = "always"
|
|
scope_labels = {
|
|
"once": "einmalig",
|
|
"session": "für diese Session",
|
|
"always": "dauerhaft (Allow-Always)",
|
|
}
|
|
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
|
|
|
|
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
|
|
subcommands={"session": "Session", "always": "Dauerhaft"})
|
|
|
|
handler = registry.get_handler("approve")
|
|
result = await handler("room1", "")
|
|
assert "einmalig" in result
|
|
assert "bestätigt" in result.lower()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_session_returns_confirmation(self):
|
|
"""::approve session gibt Session-Bestätigung zurück."""
|
|
from archivar.inline_commands import InlineCommandRegistry
|
|
|
|
registry = InlineCommandRegistry()
|
|
|
|
async def cmd_approve(room_id, args):
|
|
sub = args.strip().lower() if args else ""
|
|
scope = "once"
|
|
if sub == "session":
|
|
scope = "session"
|
|
elif sub == "always":
|
|
scope = "always"
|
|
scope_labels = {
|
|
"once": "einmalig",
|
|
"session": "für diese Session",
|
|
"always": "dauerhaft (Allow-Always)",
|
|
}
|
|
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
|
|
|
|
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
|
|
subcommands={"session": "Session", "always": "Dauerhaft"})
|
|
|
|
handler = registry.get_handler("approve")
|
|
result = await handler("room1", "session")
|
|
assert "Session" in result
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_always_returns_confirmation(self):
|
|
"""::approve always gibt Dauerhaft-Bestätigung zurück."""
|
|
from archivar.inline_commands import InlineCommandRegistry
|
|
|
|
registry = InlineCommandRegistry()
|
|
|
|
async def cmd_approve(room_id, args):
|
|
sub = args.strip().lower() if args else ""
|
|
scope = "once"
|
|
if sub == "session":
|
|
scope = "session"
|
|
elif sub == "always":
|
|
scope = "always"
|
|
scope_labels = {
|
|
"once": "einmalig",
|
|
"session": "für diese Session",
|
|
"always": "dauerhaft (Allow-Always)",
|
|
}
|
|
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
|
|
|
|
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
|
|
subcommands={"session": "Session", "always": "Dauerhaft"})
|
|
|
|
handler = registry.get_handler("approve")
|
|
result = await handler("room1", "always")
|
|
assert "dauerhaft" in result.lower() or "Allow-Always" in result
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_deny_returns_rejection(self):
|
|
"""::deny gibt Ablehnungstext zurück."""
|
|
from archivar.inline_commands import InlineCommandRegistry
|
|
|
|
registry = InlineCommandRegistry()
|
|
|
|
async def cmd_deny(room_id, args):
|
|
return "❌ **Befehl abgelehnt.**"
|
|
|
|
registry.register("deny", cmd_deny, "Lehnt ab", category="Standard")
|
|
|
|
handler = registry.get_handler("deny")
|
|
result = await handler("room1", "")
|
|
assert "abgelehnt" in result.lower()
|
|
|
|
|
|
# ── P1-9: install.sh --update-only fixes ───────────────────────────────────
|
|
|
|
class TestP19InstallUpdateOnly:
|
|
"""P1-9: install.sh --update-only hat git pull, skip secrets, --no-restart."""
|
|
|
|
def test_update_only_has_git_pull(self):
|
|
"""install.sh --update-only enthält git pull."""
|
|
import os
|
|
script_path = os.path.join(
|
|
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
|
|
)
|
|
if os.path.exists(script_path):
|
|
content = open(script_path).read()
|
|
# --update-only Block muss git pull enthalten
|
|
assert 'git pull' in content or 'git -C' in content
|
|
|
|
def test_update_only_skips_secrets(self):
|
|
"""install.sh --update-only überspringt Secret-Validierung."""
|
|
import os
|
|
script_path = os.path.join(
|
|
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
|
|
)
|
|
if os.path.exists(script_path):
|
|
content = open(script_path).read()
|
|
# Secret-Check muss --update-only ausschließen
|
|
assert 'UPDATE_ONLY' in content
|
|
|
|
def test_no_restart_flag_exists(self):
|
|
"""install.sh hat --no-restart Flag."""
|
|
import os
|
|
script_path = os.path.join(
|
|
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
|
|
)
|
|
if os.path.exists(script_path):
|
|
content = open(script_path).read()
|
|
assert '--no-restart' in content
|
|
assert 'NO_RESTART' in content
|
|
|
|
def test_install_sh_syntax_ok(self):
|
|
"""install.sh hat keine Syntax-Fehler (bash -n)."""
|
|
import os
|
|
import subprocess
|
|
script_path = os.path.join(
|
|
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
|
|
)
|
|
if os.path.exists(script_path):
|
|
result = subprocess.run(
|
|
['bash', '-n', script_path],
|
|
capture_output=True, text=True
|
|
)
|
|
assert result.returncode == 0, f"bash -n failed: {result.stderr}"
|
|
|
|
|
|
# ── P1-10: Rainer's 3 Nice-to-haves ────────────────────────────────────────
|
|
|
|
class TestP10RainerNiceToHaves:
|
|
"""P1-10: number_buttons, FAKT skip, dead code removal."""
|
|
|
|
def test_number_buttons_false(self):
|
|
"""build_button_attachments mit number_buttons=False nummeriert nicht."""
|
|
from plugin.archivar.onboarding_review import build_button_attachments
|
|
|
|
num_buttons = [("❌ code", "REMOVE::code"), ("❌ bug", "REMOVE::bug")]
|
|
special_buttons = [("↩️ Zurück", "BACK", "default")]
|
|
|
|
attachments = build_button_attachments(
|
|
num_buttons, special_buttons,
|
|
number_buttons=False, button_style="danger",
|
|
)
|
|
|
|
# Buttons sollten KEINE Emoji-Nummern haben
|
|
for att in attachments:
|
|
for action in att.get("actions", []):
|
|
text = action.get("text", "")
|
|
# Keine Nummerierungs-Emojis
|
|
assert "1️⃣" not in text
|
|
assert "2️⃣" not in text
|
|
|
|
def test_number_buttons_true_default(self):
|
|
"""build_button_attachments mit Default number_buttons=True nummeriert."""
|
|
from plugin.archivar.onboarding_review import build_button_attachments
|
|
|
|
num_buttons = [("Option A", "A"), ("Option B", "B")]
|
|
special_buttons = []
|
|
|
|
attachments = build_button_attachments(num_buttons, special_buttons)
|
|
|
|
# Erster Button sollte 1️⃣ haben
|
|
first_text = attachments[0]["actions"][0]["text"]
|
|
assert "1️⃣" in first_text
|
|
|
|
def test_no_special_button_patterns_dead_code(self):
|
|
"""_SPECIAL_BUTTON_PATTERNS wurde entfernt (toter Code)."""
|
|
import plugin.archivar.onboarding_review as obr
|
|
assert not hasattr(obr, '_SPECIAL_BUTTON_PATTERNS'), (
|
|
"_SPECIAL_BUTTON_PATTERNS sollte entfernt sein (P1-10c)"
|
|
)
|
|
|
|
def test_fakt_skip_separate_attachment(self):
|
|
"""FAKT-Dialog hat ⏭️ Skip in separatem Attachment."""
|
|
# Prüfe dass das Pattern [1️⃣][2️⃣][3️⃣] | [4️⃣] | [⏭️ Skip] existiert
|
|
# Dies wird in _cmd_setfakt und im Onboarding-Flow verwendet
|
|
# Wir prüfen die Struktur: 3 Attachments
|
|
labels = [
|
|
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
|
|
["4️⃣ Keine"],
|
|
["⏭️ Skip"],
|
|
]
|
|
assert len(labels) == 3
|
|
assert "⏭️ Skip" in labels[2]
|
|
assert "4️⃣ Keine" in labels[1]
|
|
assert "1️⃣ Standard" in labels[0]
|