"""End-to-end tests of the adapter: meshcore_message event -> reply service call. Uses small stubs for hass/config entry/storage so the real event handling, allowlist, reply routing and reminder firing paths run without a full HA. """ import asyncio from datetime import datetime, timedelta, timezone from types import SimpleNamespace import pytest from homeassistant.core import Event from homeassistant.util import dt as dt_util from custom_components.meshcore_agent import MeshCoreAgent from custom_components.meshcore_agent.core.store import TodoStore UTC = timezone.utc class FakeBus: def __init__(self): self.listeners = [] def async_listen(self, event_type, callback): self.listeners.append((event_type, callback)) return lambda: None class FakeServices: def __init__(self): self.calls = [] async def async_call(self, domain, service, data, blocking=False): self.calls.append((domain, service, data)) class FakeHass: def __init__(self): self.bus = FakeBus() self.services = FakeServices() self.data = {} self.loop = asyncio.get_running_loop() def async_create_task(self, coro): return asyncio.get_running_loop().create_task(coro) def verify_event_loop_thread(self, *_args, **_kwargs): """Stub for homeassistant.helpers.dispatcher.""" class FakeAgentStore: def __init__(self): self.todo_store = TodoStore() self.saved = 0 async def async_save(self): self.saved += 1 def make_event(data): return Event("meshcore_message", data) @pytest.fixture(autouse=True) def _utc_tz(): previous = None try: previous = dt_util.get_default_time_zone() except ValueError: pass dt_util.set_default_time_zone(UTC) yield if previous is not None: dt_util.set_default_time_zone(previous) def make_agent(allowlist="aabbcc,10bb", allow_all=False, data=None, options=None): hass = FakeHass() entry = SimpleNamespace( entry_id="test_entry", title="Agent", data=data if data is not None else {"allowlist": allowlist, "allow_all": allow_all}, options=options if options is not None else {}, ) agent_store = FakeAgentStore() agent = MeshCoreAgent(hass, entry, agent_store) return agent, hass async def deliver(agent, data): await agent._handle_event(make_event(data)) async def test_direct_message_roundtrip(): agent, hass = make_agent() await deliver( agent, { "message_type": "direct", "outgoing": False, "pubkey_prefix": "aabbcc", "sender_name": "Phone", "message": "todo add Buy milk", }, ) assert hass.services.calls == [ ("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Added #1: Buy milk"}) ] assert agent.todo_store.items[0].text == "Buy milk" assert agent.agent_store.saved == 1 async def test_ignores_outgoing_and_non_allowlisted(): agent, hass = make_agent() await deliver( agent, {"message_type": "direct", "outgoing": True, "pubkey_prefix": "aabbcc", "message": "todo"}, ) await deliver( agent, {"message_type": "direct", "outgoing": False, "pubkey_prefix": "ffff00", "message": "todo"}, ) await deliver( agent, {"message_type": "direct", "outgoing": False, "pubkey_prefix": "aabbcc", "message": "hello"}, ) assert hass.services.calls == [] assert agent.todo_store.items == [] async def test_allow_all_option(): agent, hass = make_agent(allow_all=True) await deliver( agent, {"message_type": "direct", "pubkey_prefix": "ffff00", "message": "todo"}, ) assert len(hass.services.calls) == 1 assert "No todos" in hass.services.calls[0][2]["message"] async def test_channel_message_replies_to_channel(): agent, hass = make_agent(allowlist="groupchat") await deliver( agent, { "message_type": "channel", "channel_idx": 1, "sender_name": "groupchat", "message": "agent todo add From channel", }, ) assert hass.services.calls == [ ("meshcore", "send_channel_message", {"channel_idx": 1, "message": "Added #1: From channel"}) ] # The reminder target from a channel message is the channel itself. await deliver( agent, { "message_type": "channel", "channel_idx": 1, "sender_name": "groupchat", "message": "remind 1 in 30m", }, ) reminder = agent.todo_store.items[0].reminder assert reminder.kind == "channel" assert reminder.target == "1" async def test_reminder_firing(): agent, hass = make_agent() await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "todo add Buy milk", }, ) await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "remind 1 in 1h", }, ) item = agent.todo_store.items[0] from custom_components.meshcore_agent.core.store import Reminder # Simulate the scheduler reaching the reminder time. agent.todo_store.set_reminder( item, Reminder(at=(dt_util.now() - timedelta(seconds=1)).isoformat(), kind="direct", target="aabbcc"), ) hass.services.calls.clear() await agent._fire_reminder(item.id) assert hass.services.calls == [ ("meshcore", "send_message", {"pubkey_prefix": "aabbcc", "message": "Reminder: Buy milk"}) ] assert item.reminder is None async def test_reminder_scheduling_starts_and_cancels(): agent, hass = make_agent() await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "todo add Buy milk", }, ) await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "remind 1 in 1h", }, ) assert set(agent._reminder_unsubs) == {agent.todo_store.items[0].id} # Clearing the reminder removes the scheduled job. await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "remind off 1", }, ) assert agent._reminder_unsubs == {} async def test_long_reply_is_truncated(): agent, hass = make_agent() await deliver( agent, { "message_type": "direct", "pubkey_prefix": "aabbcc", "message": "todo add " + "x " * 100, }, ) reply = hass.services.calls[0][2]["message"] assert len(reply) <= 200 assert reply.endswith("...")