fix(P0): datetime UnboundLocalError — cherry-pick from 82c2713
This commit is contained in:
+5
-12
@@ -3338,8 +3338,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
# Dispatch to gateway handler via base-class handle_message
|
# Dispatch to gateway handler via base-class handle_message
|
||||||
try:
|
try:
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
message_type = self._message_type_for(is_button_response)
|
message_type = self._message_type_for(is_button_response)
|
||||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||||
@@ -3390,7 +3388,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
text=contextualized_text,
|
text=contextualized_text,
|
||||||
message_type=message_type,
|
message_type=message_type,
|
||||||
message_id=msg_id,
|
message_id=msg_id,
|
||||||
timestamp=datetime.fromtimestamp(time.time()),
|
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||||||
raw_message=msg_obj,
|
raw_message=msg_obj,
|
||||||
)
|
)
|
||||||
event.source = source
|
event.source = source
|
||||||
@@ -4558,8 +4556,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
# Dispatch to gateway handler via base-class handle_message
|
# Dispatch to gateway handler via base-class handle_message
|
||||||
try:
|
try:
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
message_type = self._message_type_for(is_button_response)
|
message_type = self._message_type_for(is_button_response)
|
||||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||||
@@ -4593,7 +4589,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
text=contextualized_text,
|
text=contextualized_text,
|
||||||
message_type=message_type,
|
message_type=message_type,
|
||||||
message_id=msg_id,
|
message_id=msg_id,
|
||||||
timestamp=datetime.fromtimestamp(time.time()),
|
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||||||
raw_message=msg_obj,
|
raw_message=msg_obj,
|
||||||
)
|
)
|
||||||
event.source = source
|
event.source = source
|
||||||
@@ -5263,7 +5259,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
create_and_verify_fact_store,
|
create_and_verify_fact_store,
|
||||||
get_default_fact_store_path,
|
get_default_fact_store_path,
|
||||||
)
|
)
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
# Option 1: Standard
|
# Option 1: Standard
|
||||||
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||||||
@@ -5302,7 +5297,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Option 4: Keine Sammlung
|
# Option 4: Keine Sammlung
|
||||||
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
|
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
|
||||||
strategy = "none"
|
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_strategy(strategy)
|
||||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
from archivar.room_map import RoomMap
|
from archivar.room_map import RoomMap
|
||||||
@@ -5333,7 +5328,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
create_and_verify_fact_store,
|
create_and_verify_fact_store,
|
||||||
verify_existing_fact_store,
|
verify_existing_fact_store,
|
||||||
)
|
)
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
validation = validate_fact_store_path(single_line)
|
validation = validate_fact_store_path(single_line)
|
||||||
if not validation["valid"]:
|
if not validation["valid"]:
|
||||||
@@ -5353,7 +5347,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return
|
return
|
||||||
|
|
||||||
strategy = "manual"
|
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_strategy(strategy)
|
||||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
from archivar.room_map import RoomMap
|
from archivar.room_map import RoomMap
|
||||||
@@ -5377,8 +5371,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
def _save_fakt_store(self, strategy: str, path: str, operator_room_id: str) -> None:
|
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."""
|
"""Hilfsfunktion: FAKT-Store in room-map.json speichern + doc_store aktualisieren."""
|
||||||
from datetime import datetime, timezone
|
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||||
now_iso = datetime.now(timezone.utc).isoformat()
|
|
||||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
from archivar.room_map import RoomMap
|
from archivar.room_map import RoomMap
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user