P0 Nachbesserungen + V7-1: Butler antwortet im Zielraum
Auflage 1: Unit-Tests für ConversationHistory (34 Tests)
- test_conversation_history.py: add/get, Ring-Buffer, topic_hint,
cleanup_orphaned_rooms (sync+async), Thread-safety, Edge cases
Auflage 2: Schritt-4.5 Stick-Check im Router
- router.py Zeile ~556: _check_never_route_topic VOR is_100_percent_match
in Schritt 4.5 (Keyword-Match vor LLM) eingefügt
Auflage 3: Topic-Extraktion zentralisieren
- router.py: room_name_to_topic als Module-Level-Alias exportiert
- adapter.py: importiert room_name_to_topic, ersetzt 2× inline
.lstrip('#').lower().replace(' ', '-') durch zentralen Aufruf
V7-1: Butler antwortet im Zielraum + Breadcrumb
- adapter.py _process_incoming: move_request_sent=True → return (kein Agent-Dispatch)
- adapter.py Move-Request-Handler: bei ✅Ja → Breadcrumb im Ursprungsraum,
_CURRENT_ORIGIN_ROOM + _THEMATIC_TARGET_ROOM auf Zielraum gesetzt,
_dispatch_agent() im Zielraum-Kontext
- adapter.py _dispatch_agent(): extrahierte Dispatch-Methode für V7-1-Pfad
Syntax-Check: alle .py bestehen py_compile
Tests: 99/100 passed (1 pre-existing env-var failure)
This commit is contained in:
@@ -0,0 +1,415 @@
|
||||
"""
|
||||
Unit-Tests für ConversationHistory (B5v6.5).
|
||||
|
||||
Testet:
|
||||
- add + get (Ring-Buffer Verhalten, älteste fällt raus)
|
||||
- topic_hint (set, get, clear)
|
||||
- cleanup_orphaned_rooms (sync + async)
|
||||
- Thread-safety (concurrent adds)
|
||||
- Edge cases: leerer Raum, nicht-existenter Raum
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from conversation_history import ConversationHistory, MessageEntry
|
||||
|
||||
|
||||
class TestConversationHistoryAddGet(unittest.TestCase):
|
||||
"""Tests für add() und get() — Ring-Buffer-Verhalten."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=5)
|
||||
|
||||
def test_add_and_get_single_message(self):
|
||||
"""Eine Nachricht hinzufügen und abrufen."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Hallo Welt")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["role"], "user")
|
||||
self.assertEqual(msgs[0]["text"], "Hallo Welt")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_and_get_multiple_messages(self):
|
||||
"""Mehrere Nachrichten — neueste zuletzt."""
|
||||
async def run():
|
||||
for i in range(3):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 3)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 0")
|
||||
self.assertEqual(msgs[2]["text"], "Msg 2")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_ring_buffer_overflow(self):
|
||||
"""Wenn max_size=5 überschritten, fällt die älteste Nachricht raus."""
|
||||
async def run():
|
||||
for i in range(7):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 5)
|
||||
# Älteste (Msg 0, Msg 1) sind rausgefallen
|
||||
self.assertEqual(msgs[0]["text"], "Msg 2")
|
||||
self.assertEqual(msgs[4]["text"], "Msg 6")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_ring_buffer_exact_max(self):
|
||||
"""Genau max_size Nachrichten — keine verworfen."""
|
||||
async def run():
|
||||
for i in range(5):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 5)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 0")
|
||||
self.assertEqual(msgs[4]["text"], "Msg 4")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_with_limit(self):
|
||||
"""get() mit limit-Parameter."""
|
||||
async def run():
|
||||
for i in range(10):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1", limit=3)
|
||||
self.assertEqual(len(msgs), 3)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 7")
|
||||
self.assertEqual(msgs[2]["text"], "Msg 9")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_limit_larger_than_buffer(self):
|
||||
"""limit > buffer size → alle Nachrichten."""
|
||||
async def run():
|
||||
for i in range(3):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1", limit=100)
|
||||
self.assertEqual(len(msgs), 3)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_nonexistent_room(self):
|
||||
"""get() für nicht-existierenden Raum → leere Liste."""
|
||||
async def run():
|
||||
msgs = await self.history.get("nonexistent")
|
||||
self.assertEqual(msgs, [])
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_empty_room_id(self):
|
||||
"""add() mit leerem room_id → no-op, kein Crash."""
|
||||
async def run():
|
||||
await self.history.add("", "user", "Test")
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_empty_text(self):
|
||||
"""add() mit leerem Text → no-op."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "")
|
||||
await self.history.add("room-1", "user", " ")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_multiple_rooms_independent(self):
|
||||
"""Verschiedene Räume haben unabhängige Buffer."""
|
||||
async def run():
|
||||
await self.history.add("room-A", "user", "A1")
|
||||
await self.history.add("room-B", "user", "B1")
|
||||
await self.history.add("room-A", "user", "A2")
|
||||
msgs_a = await self.history.get("room-A")
|
||||
msgs_b = await self.history.get("room-B")
|
||||
self.assertEqual(len(msgs_a), 2)
|
||||
self.assertEqual(len(msgs_b), 1)
|
||||
self.assertEqual(msgs_a[0]["text"], "A1")
|
||||
self.assertEqual(msgs_b[0]["text"], "B1")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_max_size_validation(self):
|
||||
"""max_size < 1 → ValueError."""
|
||||
with self.assertRaises(ValueError):
|
||||
ConversationHistory(max_size=0)
|
||||
with self.assertRaises(ValueError):
|
||||
ConversationHistory(max_size=-1)
|
||||
|
||||
def test_max_size_one(self):
|
||||
"""max_size=1: nur die letzte Nachricht bleibt."""
|
||||
async def run():
|
||||
hist = ConversationHistory(max_size=1)
|
||||
await hist.add("room-1", "user", "First")
|
||||
await hist.add("room-1", "user", "Second")
|
||||
msgs = await hist.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["text"], "Second")
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryTopicHint(unittest.TestCase):
|
||||
"""Tests für topic_hint (set, get, clear)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_set_and_get_topic_hint(self):
|
||||
"""Topic setzen und abrufen."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Deployment-Status")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertEqual(hint, "Deployment-Status")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_topic_hint_nonexistent(self):
|
||||
"""Topic für nicht-existierenden Raum → None."""
|
||||
async def run():
|
||||
hint = await self.history.get_topic_hint("nonexistent")
|
||||
self.assertIsNone(hint)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_set_topic_hint_overwrite(self):
|
||||
"""Zweites set_topic_hint überschreibt das erste."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Erstes Thema")
|
||||
await self.history.set_topic_hint("room-1", "Zweites Thema")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertEqual(hint, "Zweites Thema")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_set_topic_hint_empty(self):
|
||||
"""set_topic_hint mit leerem room_id oder topic → no-op."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("", "Thema")
|
||||
await self.history.set_topic_hint("room-1", "")
|
||||
self.assertIsNone(await self.history.get_topic_hint(""))
|
||||
self.assertIsNone(await self.history.get_topic_hint("room-1"))
|
||||
asyncio.run(run())
|
||||
|
||||
def test_clear_removes_topic_hint(self):
|
||||
"""clear() entfernt auch den topic_hint."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Thema")
|
||||
await self.history.clear("room-1")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertIsNone(hint)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_topic_hint_independent_per_room(self):
|
||||
"""Topic hints sind unabhängig pro Raum."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-A", "Thema A")
|
||||
await self.history.set_topic_hint("room-B", "Thema B")
|
||||
self.assertEqual(await self.history.get_topic_hint("room-A"), "Thema A")
|
||||
self.assertEqual(await self.history.get_topic_hint("room-B"), "Thema B")
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryCleanup(unittest.TestCase):
|
||||
"""Tests für cleanup_orphaned_rooms (sync + async)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_cleanup_sync_removes_orphaned(self):
|
||||
"""Sync-Cleanup entfernt Räume, die nicht in active_room_ids sind."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
await self.history.add("room-3", "user", "Msg")
|
||||
await self.history.set_topic_hint("room-1", "T1")
|
||||
await self.history.set_topic_hint("room-2", "T2")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync({"room-1"})
|
||||
self.assertEqual(removed, 2) # room-2 und room-3 entfernt
|
||||
|
||||
async def check():
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1) # room-1 bleibt
|
||||
msgs2 = await self.history.get("room-2")
|
||||
self.assertEqual(len(msgs2), 0) # room-2 entfernt
|
||||
hint = await self.history.get_topic_hint("room-2")
|
||||
self.assertIsNone(hint) # topic_hint auch entfernt
|
||||
asyncio.run(check())
|
||||
|
||||
def test_cleanup_sync_no_orphans(self):
|
||||
"""Sync-Cleanup wenn alle Räume aktiv sind → 0 entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync({"room-1", "room-2"})
|
||||
self.assertEqual(removed, 0)
|
||||
|
||||
def test_cleanup_sync_empty_active_set(self):
|
||||
"""Sync-Cleanup mit leerem active_room_ids → alle entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync(set())
|
||||
self.assertEqual(removed, 2)
|
||||
|
||||
def test_cleanup_async_removes_orphaned(self):
|
||||
"""Async-Cleanup (via Lock) entfernt verwaiste Räume."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
|
||||
self.assertEqual(removed, 1)
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
msgs2 = await self.history.get("room-2")
|
||||
self.assertEqual(len(msgs2), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_cleanup_async_no_orphans(self):
|
||||
"""Async-Cleanup wenn alle Räume aktiv → 0 entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
|
||||
self.assertEqual(removed, 0)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryThreadSafety(unittest.TestCase):
|
||||
"""Tests für Thread-safety (concurrent adds)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=100)
|
||||
|
||||
def test_concurrent_adds_same_room(self):
|
||||
"""Viele concurrent adds in denselben Raum — keine Korruption."""
|
||||
async def add_many(room_id, prefix, count):
|
||||
for i in range(count):
|
||||
await self.history.add(room_id, "user", f"{prefix}-{i}")
|
||||
|
||||
async def run():
|
||||
tasks = [
|
||||
add_many("room-1", "A", 50),
|
||||
add_many("room-1", "B", 50),
|
||||
add_many("room-1", "C", 50),
|
||||
]
|
||||
await asyncio.gather(*tasks)
|
||||
msgs = await self.history.get("room-1")
|
||||
# 150 adds, max_size=100 → 100 messages
|
||||
self.assertEqual(len(msgs), 100)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_concurrent_adds_different_rooms(self):
|
||||
"""Concurrent adds in verschiedene Räume — keine Cross-Contamination."""
|
||||
async def add_many(room_id, count):
|
||||
for i in range(count):
|
||||
await self.history.add(room_id, "user", f"msg-{i}")
|
||||
|
||||
async def run():
|
||||
tasks = [
|
||||
add_many("room-A", 30),
|
||||
add_many("room-B", 30),
|
||||
add_many("room-C", 30),
|
||||
]
|
||||
await asyncio.gather(*tasks)
|
||||
self.assertEqual(len(await self.history.get("room-A")), 30)
|
||||
self.assertEqual(len(await self.history.get("room-B")), 30)
|
||||
self.assertEqual(len(await self.history.get("room-C")), 30)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_concurrent_add_and_get(self):
|
||||
"""Gleichzeitiges add() und get() — keine Deadlocks."""
|
||||
async def adder():
|
||||
for i in range(50):
|
||||
await self.history.add("room-1", "user", f"msg-{i}")
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def reader():
|
||||
for _ in range(25):
|
||||
await self.history.get("room-1")
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def run():
|
||||
await asyncio.gather(adder(), reader())
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 50)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryEdgeCases(unittest.TestCase):
|
||||
"""Edge-Case-Tests."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_clear_nonexistent_room(self):
|
||||
"""clear() für nicht-existierenden Raum → no-op, kein Crash."""
|
||||
async def run():
|
||||
await self.history.clear("nonexistent")
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_clear_then_reuse_room(self):
|
||||
"""Nach clear() kann derselbe Raum wieder verwendet werden."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg 1")
|
||||
await self.history.clear("room-1")
|
||||
await self.history.add("room-1", "user", "Msg 2")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 2")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_room_count_property(self):
|
||||
"""room_count Property (nicht thread-safe, für Debug)."""
|
||||
async def run():
|
||||
self.assertEqual(self.history.room_count, 0)
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
self.assertEqual(self.history.room_count, 1)
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
self.assertEqual(self.history.room_count, 2)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_room_count_async(self):
|
||||
"""Thread-safe get_room_count()."""
|
||||
async def run():
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
self.assertEqual(await self.history.get_room_count(), 1)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_messageentry_to_dict(self):
|
||||
"""MessageEntry.to_dict() liefert korrekte Struktur."""
|
||||
from datetime import datetime, timezone
|
||||
ts = datetime(2026, 7, 13, 12, 0, 0, tzinfo=timezone.utc)
|
||||
entry = MessageEntry(role="user", text="Test", timestamp=ts)
|
||||
d = entry.to_dict()
|
||||
self.assertEqual(d["role"], "user")
|
||||
self.assertEqual(d["text"], "Test")
|
||||
self.assertTrue(d["timestamp"].startswith("2026-07-13"))
|
||||
|
||||
def test_messageentry_default_timestamp(self):
|
||||
"""MessageEntry ohne timestamp → jetzt UTC."""
|
||||
entry = MessageEntry(role="user", text="Test")
|
||||
self.assertIsNotNone(entry.timestamp)
|
||||
d = entry.to_dict()
|
||||
self.assertIn("timestamp", d)
|
||||
|
||||
def test_add_with_custom_timestamp(self):
|
||||
"""add() mit explizitem timestamp."""
|
||||
from datetime import datetime, timezone
|
||||
async def run():
|
||||
ts = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
||||
await self.history.add("room-1", "user", "Old msg", timestamp=ts)
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(msgs[0]["timestamp"], "2025-01-01T00:00:00+00:00")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_max_size_property(self):
|
||||
"""max_size Property."""
|
||||
self.assertEqual(self.history.max_size, 10)
|
||||
hist2 = ConversationHistory(max_size=3)
|
||||
self.assertEqual(hist2.max_size, 3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user