eed0f564dd
F1 (P0): target_message_id-Tracking - RocketChatREST.post_message() gibt jetzt message._id zurück (Optional[str]) - _post_message_with_retry() gibt message_id zurück (Optional[str]) - Auto-Route speichert target_message_id in _recent_auto_routes - Widerspruch nutzt target_message_id für delete_message im Zielraum F2 (P0): Widerspruchs-Detector präzisiert - Wortgrenzen-Match: re.search(r'\b' + re.escape(kw) + r'\b', text) - Satzkontext-Whitelist: Keyword am Satzanfang ODER mit '!' im Satz - Widerspruch greift NUR wenn Auto-Route in den letzten 10 Min - 'Das ist nein nicht möglich' → KEIN Widerspruch mehr F3 (P1): Raumwechsel-Validierung - #-Pflicht: Match muss '#' vor dem Raum-Namen haben - Negativ-Liste: 'in den', 'nach hause', 'nach oben' etc. blocken - room-map-Validierung: Nur Räume aus room-map.json werden akzeptiert F4 (P2): sticky_topic-Vergleich vereinheitlicht - Auto-Route sticky_topic jetzt via room_name_to_topic(target_name) - Konsistent mit current_topic-Berechnung im Session-Sticky-Pfad F5 (P2): Docstring korrigiert - delete_message: 'POST /api/v1/chat.delete' (nicht DELETE) F6 (P2): 22 Integration-Tests in test_v8_3_1.py - F1: 4 Tests (message_id tracking) - F2: 9 Tests (Wortgrenzen, Satzkontext, 10-Min-Fenster) - F3: 6 Tests (#-Pflicht, Negativ-Liste, room-map) - F4: 3 Tests (sticky_topic-Vereinheitlichung)
334 lines
14 KiB
Python
334 lines
14 KiB
Python
"""
|
|
V8.3.1: Integration-Tests für die 3 Pflicht-Fixes.
|
|
|
|
Prüft:
|
|
- F1: target_message_id-Tracking (post_message → message._id)
|
|
- F2: Widerspruchs-Detector Präzision (Wortgrenzen, Satzkontext, 10-Min-Fenster)
|
|
- F3: Raumwechsel-Validierung (#-Pflicht, Negativ-Liste, room-map-Check)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
import time
|
|
import unittest
|
|
from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
|
|
from archivar_state import ArchivarState
|
|
|
|
|
|
# ── F1: target_message_id-Tracking ────────────────────────────────────────
|
|
|
|
class TestF1TargetMessageIdTracking(unittest.TestCase):
|
|
"""F1: _post_message_with_retry muss message_id zurückgeben und
|
|
_recent_auto_routes muss target_message_id enthalten."""
|
|
|
|
def test_post_message_returns_message_id(self):
|
|
"""RocketChatREST.post_message() gibt message._id aus API-Response zurück."""
|
|
from unittest.mock import MagicMock
|
|
import json
|
|
|
|
# Simuliere Rocket.Chat API-Response
|
|
mock_response: dict = {
|
|
"success": True,
|
|
"message": {"_id": "msg-abc123", "rid": "room-xyz"},
|
|
}
|
|
|
|
# Test: message._id wird extrahiert
|
|
msg_id = (mock_response.get("message") or {}).get("_id")
|
|
self.assertEqual(msg_id, "msg-abc123")
|
|
|
|
def test_post_message_returns_none_on_failure(self):
|
|
"""post_message() gibt None zurück wenn success=False."""
|
|
mock_response = {"success": False}
|
|
msg_id = None
|
|
if mock_response.get("success"):
|
|
msg_id = (mock_response.get("message") or {}).get("_id")
|
|
self.assertIsNone(msg_id)
|
|
|
|
def test_recent_auto_routes_stores_target_message_id(self):
|
|
"""_recent_auto_routes Eintrag enthält target_message_id."""
|
|
target_message_id = "msg-target-789"
|
|
route_entry = {
|
|
"origin_room": "origin-123",
|
|
"target_room": "target-456",
|
|
"topic": "rocketchat-plugin",
|
|
"timestamp": time.time(),
|
|
"origin_message_id": "msg-origin-456",
|
|
"target_message_id": target_message_id,
|
|
}
|
|
self.assertEqual(route_entry["target_message_id"], "msg-target-789")
|
|
self.assertNotEqual(route_entry["target_message_id"], "")
|
|
|
|
def test_widerspruch_uses_target_message_id(self):
|
|
"""Widerspruch nutzt target_message_id zum Löschen im Zielraum."""
|
|
route_info = {
|
|
"target_room": "target-456",
|
|
"target_message_id": "msg-target-789",
|
|
"timestamp": time.time() - 60, # 1 Min her
|
|
}
|
|
target_msg_id = route_info.get("target_message_id", "")
|
|
self.assertTrue(target_msg_id) # Nicht leer
|
|
# delete_message wird mit target_room + target_msg_id aufgerufen
|
|
self.assertEqual(target_msg_id, "msg-target-789")
|
|
|
|
|
|
# ── F2: Widerspruchs-Detector Präzision ──────────────────────────────────
|
|
|
|
class TestF2WiderspruchPrecision(unittest.TestCase):
|
|
"""F2: Widerspruch nur bei Wortgrenzen + Satzkontext + 10-Min-Fenster."""
|
|
|
|
def test_word_boundary_match(self):
|
|
"""'nein' in 'Das ist nein nicht möglich' matcht Wortgrenzen,
|
|
aber Satzkontext-Whitelist blockt (kein Satzanfang, kein !)."""
|
|
import re
|
|
text = "Das ist nein nicht möglich"
|
|
kw = "nein"
|
|
# Wortgrenzen-Match: 'nein' ist ein eigenständiges Wort → matcht
|
|
word_match = bool(re.search(r'\b' + re.escape(kw) + r'\b', text.lower()))
|
|
self.assertTrue(word_match) # Wortgrenzen-Match: ja
|
|
|
|
# Aber: Satzkontext-Whitelist blockt — Satz beginnt nicht mit 'nein',
|
|
# kein '!' im Satz → KEIN Widerspruch
|
|
def _widerspruch_matches(kw, txt):
|
|
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
|
|
pos = m.start()
|
|
sentence_start = 0
|
|
for i in range(pos - 1, -1, -1):
|
|
if txt[i] in '.!?\n':
|
|
sentence_start = i + 1
|
|
break
|
|
sentence_end = len(txt)
|
|
for i in range(pos, len(txt)):
|
|
if txt[i] in '.!?\n':
|
|
sentence_end = i
|
|
break
|
|
sentence = txt[sentence_start:sentence_end].strip()
|
|
if sentence.startswith(kw) or '!' in sentence:
|
|
return True
|
|
return False
|
|
|
|
self.assertFalse(_widerspruch_matches(kw, text.lower()))
|
|
|
|
def test_word_boundary_match_standalone(self):
|
|
"""'Nein, das gehört hier her!' → Widerspruch (eigenständiges Wort)."""
|
|
import re
|
|
text = "Nein, das gehört hier her!"
|
|
kw = "nein"
|
|
new_match = bool(re.search(r'\b' + re.escape(kw) + r'\b', text.lower()))
|
|
self.assertTrue(new_match)
|
|
|
|
def test_sentence_start_whitelist(self):
|
|
"""Keyword am Satzanfang → Widerspruch."""
|
|
text = "nein, das ist falsch. bitte zurück."
|
|
kw = "nein"
|
|
# Finde Satz mit dem Keyword
|
|
import re
|
|
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', text):
|
|
pos = m.start()
|
|
sentence_start = 0
|
|
for i in range(pos - 1, -1, -1):
|
|
if text[i] in '.!?\n':
|
|
sentence_start = i + 1
|
|
break
|
|
sentence = text[sentence_start:].split('.')[0].strip()
|
|
self.assertTrue(sentence.startswith(kw))
|
|
|
|
def test_exclamation_whitelist(self):
|
|
"""Keyword mit Ausrufezeichen im selben Satz → Widerspruch."""
|
|
text = "Das ist der falsche Raum! stop sofort"
|
|
kw = "stop"
|
|
import re
|
|
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', text):
|
|
pos = m.start()
|
|
sentence_end = len(text)
|
|
for i in range(pos, len(text)):
|
|
if text[i] in '.!?\n':
|
|
sentence_end = i
|
|
break
|
|
sentence = text[:sentence_end]
|
|
self.assertIn('!', sentence)
|
|
|
|
def test_no_widerspruch_without_recent_auto_route(self):
|
|
"""Widerspruch greift NUR wenn in den letzten 10 Min eine Auto-Route stattfand."""
|
|
# Kein _recent_auto_routes Eintrag → kein Widerspruch
|
|
recent_auto_routes = {}
|
|
room_id = "room-123"
|
|
self.assertNotIn(room_id, recent_auto_routes)
|
|
|
|
def test_widerspruch_within_10_min_window(self):
|
|
"""Widerspruch innerhalb 10 Min → aktiv."""
|
|
now = time.time()
|
|
route_time = now - 300 # 5 Min
|
|
self.assertLessEqual(now - route_time, 600)
|
|
|
|
def test_widerspruch_outside_10_min_ignored(self):
|
|
"""Widerspruch außerhalb 10 Min → ignoriert."""
|
|
now = time.time()
|
|
route_time = now - 700 # 11.6 Min
|
|
self.assertGreater(now - route_time, 600)
|
|
|
|
def test_normal_text_no_false_positive(self):
|
|
"""'Das ist nein nicht möglich' → KEIN Widerspruch (F2-Fix)."""
|
|
import re
|
|
text = "Das ist nein nicht möglich"
|
|
keywords = ['halt', 'bleib hier', 'gehört hier her', 'nein', 'stop',
|
|
'falscher raum', 'zurück', 'roll back', 'rollback']
|
|
|
|
def _widerspruch_matches(kw, txt):
|
|
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
|
|
pos = m.start()
|
|
sentence_start = 0
|
|
for i in range(pos - 1, -1, -1):
|
|
if txt[i] in '.!?\n':
|
|
sentence_start = i + 1
|
|
break
|
|
sentence_end = len(txt)
|
|
for i in range(pos, len(txt)):
|
|
if txt[i] in '.!?\n':
|
|
sentence_end = i
|
|
break
|
|
sentence = txt[sentence_start:sentence_end].strip()
|
|
if sentence.startswith(kw) or '!' in sentence:
|
|
return True
|
|
return False
|
|
|
|
is_widerspruch = any(
|
|
_widerspruch_matches(kw, text.lower()) for kw in keywords
|
|
)
|
|
self.assertFalse(is_widerspruch)
|
|
|
|
def test_real_widerspruch_detected(self):
|
|
"""'Nein, das gehört hier her!' → Widerspruch erkannt."""
|
|
import re
|
|
text = "Nein, das gehört hier her!"
|
|
keywords = ['halt', 'bleib hier', 'gehört hier her', 'nein', 'stop',
|
|
'falscher raum', 'zurück', 'roll back', 'rollback']
|
|
|
|
def _widerspruch_matches(kw, txt):
|
|
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
|
|
pos = m.start()
|
|
sentence_start = 0
|
|
for i in range(pos - 1, -1, -1):
|
|
if txt[i] in '.!?\n':
|
|
sentence_start = i + 1
|
|
break
|
|
sentence_end = len(txt)
|
|
for i in range(pos, len(txt)):
|
|
if txt[i] in '.!?\n':
|
|
sentence_end = i
|
|
break
|
|
sentence = txt[sentence_start:sentence_end].strip()
|
|
if sentence.startswith(kw) or '!' in sentence:
|
|
return True
|
|
return False
|
|
|
|
is_widerspruch = any(
|
|
_widerspruch_matches(kw, text.lower()) for kw in keywords
|
|
)
|
|
self.assertTrue(is_widerspruch)
|
|
|
|
|
|
# ── F3: Raumwechsel-Validierung ──────────────────────────────────────────
|
|
|
|
class TestF3RaumwechselValidation(unittest.TestCase):
|
|
"""F3: #-Pflicht, Negativ-Liste, room-map-Validierung."""
|
|
|
|
def test_hash_required_for_switch(self):
|
|
"""'lass uns in den Raum wechseln' (ohne #) → KEIN Switch."""
|
|
text = "lass uns in den Raum wechseln"
|
|
# Kein # im Text → kein expliziter Raumwechsel
|
|
self.assertNotIn('#', text)
|
|
|
|
def test_hash_present_triggers_switch(self):
|
|
"""'lass uns in #Rocketchat-Plugin wechseln' → Switch."""
|
|
text = "lass uns in #Rocketchat-Plugin wechseln"
|
|
self.assertIn('#', text)
|
|
|
|
def test_negativ_liste_blocks_switch(self):
|
|
"""'wechseln nach Hause' → KEIN Switch (Negativ-Liste)."""
|
|
text = "wechseln nach Hause"
|
|
negativ = ['in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank',
|
|
'nach hause', 'nach oben', 'nach unten', 'nach links',
|
|
'nach rechts', 'nach vorne', 'nach hinten', 'in die',
|
|
'in das', 'zum arzt']
|
|
is_blocked = any(neg in text.lower() for neg in negativ)
|
|
self.assertTrue(is_blocked)
|
|
|
|
def test_negativ_liste_allows_valid_switch(self):
|
|
"""'wechseln nach #BAT-Team' → Switch (nicht in Negativ-Liste)."""
|
|
text = "wechseln nach #BAT-Team"
|
|
negativ = ['in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank',
|
|
'nach hause', 'nach oben', 'nach unten', 'nach links',
|
|
'nach rechts', 'nach vorne', 'nach hinten', 'in die',
|
|
'in das', 'zum arzt']
|
|
is_blocked = any(neg in text.lower() for neg in negativ)
|
|
self.assertFalse(is_blocked)
|
|
|
|
def test_room_map_validation_required(self):
|
|
"""Raum muss in room-map.json existieren."""
|
|
room_map_rooms = {
|
|
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
|
|
"6a049d493a62ef8f1ead2320": "bat-team",
|
|
}
|
|
switch_room_name = "rocketchat-plugin"
|
|
# Raum existiert in room-map
|
|
found = any(
|
|
switch_room_name in name or name in switch_room_name
|
|
for name in room_map_rooms.values()
|
|
)
|
|
self.assertTrue(found)
|
|
|
|
def test_room_map_validation_rejects_unknown(self):
|
|
"""Unbekannter Raum → kein Switch."""
|
|
room_map_rooms = {
|
|
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
|
|
}
|
|
switch_room_name = "unbekannter-raum"
|
|
found = any(
|
|
switch_room_name in name or name in switch_room_name
|
|
for name in room_map_rooms.values()
|
|
)
|
|
self.assertFalse(found)
|
|
|
|
|
|
# ── F4: sticky_topic-Vergleich vereinheitlichen ──────────────────────────
|
|
|
|
class TestF4StickyTopicUnified(unittest.TestCase):
|
|
"""F4: sticky_topic immer via room_name_to_topic."""
|
|
|
|
def test_room_name_to_topic_consistent(self):
|
|
"""room_name_to_topic produziert konsistente Slugs."""
|
|
# Simuliere room_name_to_topic
|
|
def room_name_to_topic(name):
|
|
return name.lstrip('#').lower().replace(' ', '-')
|
|
|
|
self.assertEqual(room_name_to_topic("#Rocketchat-Plugin"), "rocketchat-plugin")
|
|
self.assertEqual(room_name_to_topic("#BAT-Team"), "bat-team")
|
|
self.assertEqual(room_name_to_topic("#LAN-Dokumentation"), "lan-dokumentation")
|
|
|
|
def test_sticky_topic_matches_current_topic(self):
|
|
"""Wenn beide via room_name_to_topic → konsistenter Vergleich."""
|
|
def room_name_to_topic(name):
|
|
return name.lstrip('#').lower().replace(' ', '-')
|
|
|
|
sticky_topic = room_name_to_topic("#Rocketchat-Plugin")
|
|
current_topic = room_name_to_topic("#Rocketchat-Plugin")
|
|
self.assertEqual(sticky_topic, current_topic)
|
|
|
|
def test_sticky_topic_mismatch_different_room(self):
|
|
"""Unterschiedliche Räume → unterschiedliche Topics."""
|
|
def room_name_to_topic(name):
|
|
return name.lstrip('#').lower().replace(' ', '-')
|
|
|
|
sticky_topic = room_name_to_topic("#Rocketchat-Plugin")
|
|
current_topic = room_name_to_topic("#BAT-Team")
|
|
self.assertNotEqual(sticky_topic, current_topic)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|