fix(P0): datetime UnboundLocalError in _process_incoming — local import shadows module-level import

This commit is contained in:
Bernd (Hermes)
2026-07-27 08:37:29 +02:00
parent 99fa42df33
commit 82c2713929
2 changed files with 215 additions and 12 deletions
+5 -12
View File
@@ -3370,8 +3370,6 @@ class RocketChatAdapter(BasePlatformAdapter):
# Dispatch to gateway handler via base-class handle_message
try:
from datetime import datetime
message_type = self._message_type_for(is_button_response)
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
target_room_id = _THEMATIC_TARGET_ROOM.get()
@@ -3422,7 +3420,7 @@ class RocketChatAdapter(BasePlatformAdapter):
text=contextualized_text,
message_type=message_type,
message_id=msg_id,
timestamp=datetime.fromtimestamp(time.time()),
timestamp=datetime.datetime.fromtimestamp(time.time()),
raw_message=msg_obj,
)
event.source = source
@@ -4590,8 +4588,6 @@ class RocketChatAdapter(BasePlatformAdapter):
# Dispatch to gateway handler via base-class handle_message
try:
from datetime import datetime
message_type = self._message_type_for(is_button_response)
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
target_room_id = _THEMATIC_TARGET_ROOM.get()
@@ -4625,7 +4621,7 @@ class RocketChatAdapter(BasePlatformAdapter):
text=contextualized_text,
message_type=message_type,
message_id=msg_id,
timestamp=datetime.fromtimestamp(time.time()),
timestamp=datetime.datetime.fromtimestamp(time.time()),
raw_message=msg_obj,
)
event.source = source
@@ -5295,7 +5291,6 @@ class RocketChatAdapter(BasePlatformAdapter):
create_and_verify_fact_store,
get_default_fact_store_path,
)
from datetime import datetime, timezone
# Option 1: Standard
if "Standard" in choice or "1️⃣" in choice or choice == "1":
@@ -5334,7 +5329,7 @@ class RocketChatAdapter(BasePlatformAdapter):
# Option 4: Keine Sammlung
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
strategy = "none"
now_iso = datetime.now(timezone.utc).isoformat()
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
self.archivar._room_map.set_fact_store_strategy(strategy)
self.archivar._room_map.set_fact_store_created_at(now_iso)
from archivar.room_map import RoomMap
@@ -5365,7 +5360,6 @@ class RocketChatAdapter(BasePlatformAdapter):
create_and_verify_fact_store,
verify_existing_fact_store,
)
from datetime import datetime, timezone
validation = validate_fact_store_path(single_line)
if not validation["valid"]:
@@ -5385,7 +5379,7 @@ class RocketChatAdapter(BasePlatformAdapter):
return
strategy = "manual"
now_iso = datetime.now(timezone.utc).isoformat()
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
self.archivar._room_map.set_fact_store_strategy(strategy)
self.archivar._room_map.set_fact_store_created_at(now_iso)
from archivar.room_map import RoomMap
@@ -5409,8 +5403,7 @@ class RocketChatAdapter(BasePlatformAdapter):
def _save_fakt_store(self, strategy: str, path: str, operator_room_id: str) -> None:
"""Hilfsfunktion: FAKT-Store in room-map.json speichern + doc_store aktualisieren."""
from datetime import datetime, timezone
now_iso = datetime.now(timezone.utc).isoformat()
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
self.archivar._room_map.set_fact_store_strategy(strategy)
self.archivar._room_map.set_fact_store_created_at(now_iso)
from archivar.room_map import RoomMap
+210
View File
@@ -0,0 +1,210 @@
"""
P0: Test that _process_incoming() does not crash with UnboundLocalError.
Root cause: local `from datetime import datetime` inside _process_incoming()
shadowed the module-level `import datetime`. Python's scoping rules treat
`datetime` as a local variable for the ENTIRE function, so any use of
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
This test verifies that _process_incoming() can be called with a minimal
mock message without hitting the UnboundLocalError.
"""
from __future__ import annotations
import asyncio
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
def _build_minimal_adapter():
"""Build a RocketChatAdapter with minimal mocks for _process_incoming."""
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = "/tmp/test_p0_datetime_room_map.json"
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/test_p0_datetime_state.json"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
from plugin.archivar.conversation_history import ConversationHistory
from plugin.archivar.multiroom_context import MultiRoomContextRing
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from plugin.archivar.room_map import RoomMap
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
adapter.archivar = ArchivarMessageHandler(
send_callback=lambda *a, **kw: None,
button_send_callback=lambda *a, **kw: None,
conversation_history=adapter._conversation_history,
)
# Create a minimal room-map.json
tmpdir = tempfile.mkdtemp()
room_map_path = Path(tmpdir) / "room-map.json"
import json
room_map_data = {
"version": 5,
"rooms": {
"room_test": {
"name": "#Test-Room",
"theme": "Test Room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
},
"excluded_rooms": [],
"butler_mode": "cognitive",
"fact_store_path": str(Path(tmpdir) / "docs"),
}
room_map_path.write_text(json.dumps(room_map_data))
adapter.archivar._room_map = RoomMap.load(room_map_path)
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {}
adapter._onboarding_state = {}
adapter._room_map_summary = ""
# Mock the REST client
mock_rest = MagicMock(spec=RocketChatREST)
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
mock_rest.get_rooms = MagicMock(return_value=[
{"id": "room_test", "name": "Test-Room", "type": "c"},
])
adapter.rest = mock_rest
adapter._room_info = {
"room_test": {"name": "Test-Room", "type": "c"},
}
# Mock _dispatch_agent and handle_message
adapter._dispatch_agent = AsyncMock()
adapter.handle_message = AsyncMock()
# Initialize Archivar
asyncio.run(adapter.archivar.initialize())
# Mock gateway types
import plugin.adapter as _adapter_mod
_adapter_mod.MessageType = type('MessageType', (), {
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
})
_adapter_mod.MessageEvent = type('MessageEvent', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
_adapter_mod.SessionSource = type('SessionSource', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
_adapter_mod.Platform = str
_adapter_mod.PlatformConfig = type('PlatformConfig', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
return adapter
class TestP0DatetimeUnboundLocalError(unittest.TestCase):
"""P0: _process_incoming() must not crash with UnboundLocalError.
The bug: local `from datetime import datetime` inside _process_incoming()
shadowed the module-level `import datetime`. Python treats `datetime` as
a local variable for the ENTIRE function scope, so any use of
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
This test calls _process_incoming() with a minimal mock message and
verifies no UnboundLocalError is raised.
"""
@classmethod
def setUpClass(cls):
cls.adapter = _build_minimal_adapter()
def test_process_incoming_no_unbound_local_error(self):
"""_process_incoming() should not raise UnboundLocalError for datetime."""
msg_obj = {
"_id": "msg_test_001",
"rid": "room_test",
"msg": "Hallo, das ist eine Test-Nachricht",
"u": {"username": "andreas", "_id": "user_andreas"},
}
# This should NOT raise UnboundLocalError
try:
asyncio.run(self.adapter._process_incoming(msg_obj))
except UnboundLocalError as e:
self.fail(
f"_process_incoming() raised UnboundLocalError: {e}\n"
"Root cause: local 'from datetime import datetime' shadows "
"module-level 'import datetime'."
)
def test_process_incoming_with_button_response_no_unbound_local_error(self):
"""Button response path should also not raise UnboundLocalError."""
msg_obj = {
"_id": "msg_btn_001",
"rid": "room_test",
"msg": "FAKT::1",
"u": {"username": "andreas", "_id": "user_andreas"},
}
try:
asyncio.run(self.adapter._process_incoming(msg_obj))
except UnboundLocalError as e:
self.fail(
f"_process_incoming() raised UnboundLocalError on button path: {e}"
)
def test_datetime_module_still_accessible(self):
"""Verify that datetime.datetime.now() works (module-level import intact)."""
import datetime
result = datetime.datetime.now(datetime.timezone.utc)
self.assertIsNotNone(result)
# Verify it's a datetime object, not a module
self.assertTrue(hasattr(result, 'isoformat'))
if __name__ == "__main__":
unittest.main()