Feature 18: HA Integration as API Client (#173)
Co-authored-by: dev_agent <17+dev_agent@code.cubecraftcreations.com> Co-committed-by: dev_agent <17+dev_agent@code.cubecraftcreations.com>
This commit was merged in pull request #173.
This commit is contained in:
+216
-43
@@ -22,7 +22,6 @@ pytest -q``); it is never meant to run against a real HA install.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import importlib.util
|
||||
import inspect
|
||||
import sys
|
||||
@@ -52,6 +51,7 @@ _HA_MODULES = (
|
||||
"homeassistant.helpers.entity",
|
||||
"homeassistant.helpers.event",
|
||||
"homeassistant.helpers.update_coordinator",
|
||||
"homeassistant.helpers.aiohttp_client",
|
||||
"homeassistant.components",
|
||||
"homeassistant.components.sensor",
|
||||
"homeassistant.components.binary_sensor",
|
||||
@@ -99,6 +99,7 @@ for _parent, _child in (
|
||||
("homeassistant.helpers", "entity"),
|
||||
("homeassistant.helpers", "event"),
|
||||
("homeassistant.helpers", "update_coordinator"),
|
||||
("homeassistant.helpers", "aiohttp_client"),
|
||||
("homeassistant", "components"),
|
||||
("homeassistant.components", "sensor"),
|
||||
("homeassistant.components", "binary_sensor"),
|
||||
@@ -365,6 +366,15 @@ class BinarySensorEntity(Entity):
|
||||
return self._attr_device_class
|
||||
|
||||
|
||||
class UpdateFailed(HomeAssistantError):
|
||||
"""Stand-in mirroring homeassistant.helpers.update_coordinator.UpdateFailed.
|
||||
|
||||
The exception an update pass raises to report a failed fetch: the
|
||||
coordinator records ``last_update_success = False`` instead of
|
||||
propagating it out of the refresh.
|
||||
"""
|
||||
|
||||
|
||||
class DataUpdateCoordinator:
|
||||
"""Functional stand-in for HA's DataUpdateCoordinator.
|
||||
|
||||
@@ -373,8 +383,20 @@ class DataUpdateCoordinator:
|
||||
``async_add_listener``/``async_update_listeners`` for entity
|
||||
subscription, ``async_refresh``/``async_config_entry_first_refresh``
|
||||
driving the subclass's ``_async_update_data``, ``last_update_success``,
|
||||
and ``data``. Interval scheduling is NOT simulated (no real clock
|
||||
ticks in tests) — tests drive refreshes directly.
|
||||
``last_exception``, and ``data``. Interval scheduling is NOT
|
||||
simulated (no real clock ticks in tests) — tests drive refreshes
|
||||
directly.
|
||||
|
||||
The failure contract mirrors real HA exactly (it is the trap this
|
||||
harness once hid): an update failure NEVER propagates out of
|
||||
``async_refresh`` — the coordinator records
|
||||
``last_update_success = False``, keeps its last good ``data``, and
|
||||
still notifies listeners so entities re-render unavailable — and
|
||||
``async_config_entry_first_refresh`` wraps ANY failed pass in
|
||||
:class:`ConfigEntryNotReady`, with the original error only
|
||||
surviving as ``__cause__``. A stand-in that re-raised the raw
|
||||
update error would let setup code key on the original exception
|
||||
type — a clause real HA can never reach.
|
||||
"""
|
||||
|
||||
def __init__(self, hass, logger, *, name=None, update_interval=None):
|
||||
@@ -384,6 +406,7 @@ class DataUpdateCoordinator:
|
||||
self.update_interval = update_interval
|
||||
self.data = None
|
||||
self.last_update_success = False
|
||||
self.last_exception = None
|
||||
self._listeners = []
|
||||
|
||||
def async_add_listener(self, update_callback, context=None):
|
||||
@@ -403,18 +426,35 @@ class DataUpdateCoordinator:
|
||||
callback()
|
||||
|
||||
async def async_refresh(self):
|
||||
"""Run one update pass and notify listeners."""
|
||||
"""Run one update pass and notify listeners.
|
||||
|
||||
Mirrors HA: a failed update pass is RECORDED, never raised —
|
||||
``last_update_success`` goes False, the exception lands on
|
||||
``last_exception``, and listeners still fire; only cancellation
|
||||
propagates.
|
||||
"""
|
||||
try:
|
||||
self.data = await self._async_update_data()
|
||||
self.last_update_success = True
|
||||
except BaseException:
|
||||
except Exception as err:
|
||||
self.last_update_success = False
|
||||
raise
|
||||
self.last_exception = err
|
||||
self.async_update_listeners()
|
||||
|
||||
async def async_config_entry_first_refresh(self):
|
||||
"""First refresh at config-entry setup (alias of refresh)."""
|
||||
"""First refresh at config-entry setup, per HA's real contract.
|
||||
|
||||
HA's real ``async_config_entry_first_refresh`` wraps ANY failed
|
||||
update pass in ``ConfigEntryNotReady`` — the original error
|
||||
survives only as ``__cause__`` — so setup code that must
|
||||
tolerate a failed first refresh keys on ConfigEntryNotReady,
|
||||
never on the original exception type.
|
||||
"""
|
||||
await self.async_refresh()
|
||||
if not self.last_update_success:
|
||||
raise ConfigEntryNotReady(
|
||||
f"error fetching {self.name} data: {self.last_exception}"
|
||||
) from self.last_exception
|
||||
|
||||
async def async_shutdown(self):
|
||||
"""Release listeners on teardown."""
|
||||
@@ -424,6 +464,7 @@ class DataUpdateCoordinator:
|
||||
_update_coordinator_mock = _ha_mock("homeassistant.helpers.update_coordinator")
|
||||
_update_coordinator_mock.DataUpdateCoordinator = DataUpdateCoordinator
|
||||
_update_coordinator_mock.CoordinatorEntity = CoordinatorEntity
|
||||
_update_coordinator_mock.UpdateFailed = UpdateFailed
|
||||
|
||||
_entity_mock = _ha_mock("homeassistant.helpers.entity")
|
||||
_entity_mock.DeviceInfo = DeviceInfo
|
||||
@@ -700,6 +741,174 @@ def wire_entry_to_registry(entry, registry: ListenerRegistry):
|
||||
return entry
|
||||
|
||||
|
||||
class StubSnapshotClient:
|
||||
"""A no-network stand-in for the API client's snapshot surface.
|
||||
|
||||
Answers ``get_snapshot()`` from a scripted queue of outcomes — a
|
||||
payload dict or an exception per call, consumed in order — and
|
||||
records every call. When the queue is exhausted it re-serves the
|
||||
last outcome, so setup's first refresh and a test's explicit
|
||||
refreshes poll the same scripted state. Register it (or any
|
||||
scripted client) with :func:`set_coordinator_client` BEFORE setup.
|
||||
"""
|
||||
|
||||
def __init__(self, *outcomes) -> None:
|
||||
self.calls = 0
|
||||
self._outcomes = list(outcomes)
|
||||
self._last = outcomes[-1] if outcomes else None
|
||||
#: The SSE frames the stand-in "published" (the API service's
|
||||
# stream content), drained by :func:`refire_api_transitions`.
|
||||
self.published_frames = []
|
||||
|
||||
async def get_snapshot(self):
|
||||
self.calls += 1
|
||||
if not self._outcomes:
|
||||
# Re-serve the last outcome: setup's first refresh and the
|
||||
# test's explicit pass both poll the same scripted state.
|
||||
outcome = self._last
|
||||
else:
|
||||
outcome = self._outcomes.pop(0)
|
||||
self._last = outcome
|
||||
if isinstance(outcome, BaseException):
|
||||
raise outcome
|
||||
return outcome
|
||||
|
||||
|
||||
class ScriptedPanelClient(StubSnapshotClient):
|
||||
"""Snapshot + completion stand-in for the API service's panel plane.
|
||||
|
||||
Serves the scripted snapshot outcomes (like
|
||||
:class:`StubSnapshotClient`), records ``complete_instance`` calls
|
||||
the way the panel route receives them, optionally fails them the
|
||||
way the client types the failure, and carries the SSE frames the
|
||||
API "published" in ``published_frames`` for
|
||||
:func:`refire_api_transitions` to deliver. Everything the
|
||||
integration reads over the wire, no network.
|
||||
"""
|
||||
|
||||
def __init__(self, *outcomes) -> None:
|
||||
super().__init__(*outcomes)
|
||||
self.complete_calls: list[tuple[int, int]] = []
|
||||
self.published_frames: list[tuple[str, dict]] = []
|
||||
#: When set, the next ``complete_instance`` raises this instead
|
||||
# of succeeding (a typed NestQuestApiError in production).
|
||||
self.fail_complete_with: BaseException | None = None
|
||||
|
||||
async def complete_instance(
|
||||
self, instance_id: int, actor_child_id: int
|
||||
) -> dict:
|
||||
self.complete_calls.append((instance_id, actor_child_id))
|
||||
if self.fail_complete_with is not None:
|
||||
raise self.fail_complete_with
|
||||
return {"status": "done"}
|
||||
|
||||
|
||||
def set_coordinator_client(entry, client):
|
||||
"""Register a scripted client for ``entry``'s coordinator factory."""
|
||||
import custom_components.nestquest.coordinator as coordinator_module
|
||||
|
||||
coordinator_module._COORDINATOR_CLIENT_OVERRIDES[entry.entry_id] = client
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def coordinator_client_from_test_override():
|
||||
"""Resolve every entry's coordinator client through the test seam.
|
||||
|
||||
The integration's setup builds its API client through
|
||||
``coordinator_client_from_entry``; this fixture swaps that factory
|
||||
for a test one handing out the client registered with
|
||||
:func:`set_coordinator_client`, or — for an entry with no scripted
|
||||
client — a stub serving an EMPTY but valid household snapshot (the
|
||||
shape the API's panel route returns before any child exists; the
|
||||
real client would need aiohttp, which this mock-only harness does
|
||||
not provide).
|
||||
"""
|
||||
import datetime
|
||||
import unittest.mock as mock
|
||||
|
||||
import custom_components.nestquest as nq_mod
|
||||
import custom_components.nestquest.coordinator as coordinator_module
|
||||
|
||||
_COORDINATOR_CLIENT_OVERRIDES = (
|
||||
coordinator_module._COORDINATOR_CLIENT_OVERRIDES
|
||||
)
|
||||
|
||||
def _factory(hass, entry, **kwargs):
|
||||
override = _COORDINATOR_CLIENT_OVERRIDES.get(entry.entry_id)
|
||||
if override is not None:
|
||||
return override
|
||||
return StubSnapshotClient(
|
||||
{
|
||||
"today_iso": datetime.date.today().isoformat(),
|
||||
"cycle_day": 0,
|
||||
"children": [],
|
||||
}
|
||||
)
|
||||
|
||||
_COORDINATOR_CLIENT_OVERRIDES.clear()
|
||||
patcher = mock.patch.object(
|
||||
nq_mod, "coordinator_client_from_entry", _factory
|
||||
)
|
||||
patcher.start()
|
||||
yield
|
||||
patcher.stop()
|
||||
_COORDINATOR_CLIENT_OVERRIDES.clear()
|
||||
|
||||
|
||||
async def refire_api_transitions(hass, entry, client):
|
||||
"""Deliver the SSE frames the stand-in client has published so far
|
||||
through the integration's SSE subscription — the production event
|
||||
path.
|
||||
|
||||
Since Feature 18 the ``complete_quest`` service fires no local
|
||||
bus event: the API service builds and publishes the transition
|
||||
frames on its SSE stream, and the integration's subscription
|
||||
(:mod:`custom_components.nestquest.sse`) re-fires each frame on
|
||||
the bus. This helper streams the frames the stand-in client
|
||||
published (``client.published_frames``) through a real
|
||||
:class:`~custom_components.nestquest.sse.NestQuestEventStream`
|
||||
and waits (bounded) until the bus has re-fired every one of them.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from custom_components.nestquest.sse import NestQuestEventStream
|
||||
|
||||
frames, client.published_frames = client.published_frames, []
|
||||
|
||||
class _ScriptedStream:
|
||||
"""A healthy stream: the frames, then it stays open."""
|
||||
|
||||
def __init__(self, frames) -> None:
|
||||
self._frames = frames
|
||||
|
||||
def stream_events(self):
|
||||
async def _gen():
|
||||
for frame in self._frames:
|
||||
yield frame
|
||||
await asyncio.Event().wait()
|
||||
|
||||
return _gen()
|
||||
|
||||
before = {etype: len(hass.bus.fired(etype)) for etype, _ in frames}
|
||||
expected = len(frames)
|
||||
manager = NestQuestEventStream(hass, _ScriptedStream(frames))
|
||||
manager.start()
|
||||
try:
|
||||
async with asyncio.timeout(2):
|
||||
while True:
|
||||
delivered = sum(
|
||||
len(hass.bus.fired(etype)) - before[etype]
|
||||
for etype, _ in frames
|
||||
)
|
||||
if delivered >= expected:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
finally:
|
||||
await manager.stop()
|
||||
return frames
|
||||
|
||||
|
||||
class _HassNamespace(SimpleNamespace):
|
||||
"""SimpleNamespace subclass so the hass stub can hold weak references."""
|
||||
|
||||
@@ -923,42 +1132,6 @@ def make_config_flow_entry():
|
||||
return _factory
|
||||
|
||||
|
||||
def freeze_nestquest_clock(
|
||||
monkeypatch, instant: datetime.datetime
|
||||
) -> tuple[datetime.datetime, list]:
|
||||
"""Freeze the integration's ``datetime`` clock to a fixed aware instant.
|
||||
|
||||
Only ``custom_components.nestquest``'s ``datetime`` binding is patched,
|
||||
so the generation path's ``datetime.datetime.now`` reads this instant
|
||||
(localized to whatever time zone it asks for) while every other module
|
||||
and the test harness keep the real clock. Returns ``(frozen, requested)``
|
||||
where ``frozen`` is the instant normalized to UTC and ``requested`` is
|
||||
the list of ``tzinfo`` objects the code under test passed to ``now`` —
|
||||
so a caller can prove the generation path actually requested the
|
||||
configured HA time zone rather than silently reading UTC.
|
||||
"""
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
frozen = instant.astimezone(datetime.timezone.utc)
|
||||
requested: list = []
|
||||
|
||||
class _FrozenDatetime(datetime.datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
requested.append(tz)
|
||||
if tz is None:
|
||||
return frozen.replace(tzinfo=None)
|
||||
return frozen.astimezone(tz)
|
||||
|
||||
fake_module = SimpleNamespace(
|
||||
datetime=_FrozenDatetime,
|
||||
timedelta=datetime.timedelta,
|
||||
date=datetime.date,
|
||||
)
|
||||
monkeypatch.setattr(nestquest, "datetime", fake_module)
|
||||
return frozen, requested
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Admin-plane API fixtures (shared by the admin-plane test modules).
|
||||
#
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
"""Tests for admin_allowlist.py: the Feature 03 allowlist business layer."""
|
||||
"""Tests for the Feature 03 admin allowlist business layer (core.admin_allowlist)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
from custom_components.nestquest.core.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
seed_setup_admin,
|
||||
set_admin_ids,
|
||||
)
|
||||
from custom_components.nestquest.dao_children import AdminUsersDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -193,165 +190,6 @@ def test_seed_rejects_malformed_candidates(tmp_path) -> None:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Setup wiring: async_setup_entry seeds automatically
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _setup_entry(hass, entry, registry):
|
||||
from tests.test_lifecycle import _wire
|
||||
|
||||
entry = _wire(entry, registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
return entry
|
||||
|
||||
|
||||
async def test_setup_seeds_allowlist_from_entry_context(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = await _setup_entry(
|
||||
hass,
|
||||
make_entry(context={"user_id": "ha-owner"}),
|
||||
hass.registry,
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database) == ["ha-owner"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_seeds_allowlist_from_stored_entry_data(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A lost database re-seeded from the entry's stored admin copy."""
|
||||
from custom_components.nestquest.const import CONF_ADMIN_USER_IDS
|
||||
|
||||
entry = await _setup_entry(
|
||||
hass,
|
||||
make_entry(data={CONF_ADMIN_USER_IDS: ["user-a", "user-b"]}),
|
||||
hass.registry,
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database) == ["user-a", "user-b"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_without_context_leaves_allowlist_empty(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Fail closed: no context user and no stored copy means an empty
|
||||
allowlist — nobody is admin until the owner configures it."""
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database) == []
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_does_not_reseed_narrowed_allowlist(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
from custom_components.nestquest import async_unload_entry
|
||||
from custom_components.nestquest.const import CONF_ADMIN_USER_IDS
|
||||
|
||||
entry = await _setup_entry(
|
||||
hass, make_entry(context={"user_id": "ha-owner"}), hass.registry
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
await set_admin_ids(database, ["user-parent"])
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
# Reload with the SAME context: the narrowed list survives.
|
||||
entry_reloaded = await _setup_entry(
|
||||
hass, make_entry(context={"user_id": "ha-owner"}), hass.registry
|
||||
)
|
||||
database_b = entry_reloaded.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database_b) == ["user-parent"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry_reloaded) is True
|
||||
|
||||
|
||||
async def test_setup_seed_prefers_options_over_entry_data(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Seed precedence on a fresh database: the options flow's saved
|
||||
list (the current one) beats the config flow's original copy."""
|
||||
from custom_components.nestquest.const import CONF_ADMIN_USER_IDS
|
||||
|
||||
entry = await _setup_entry(
|
||||
hass,
|
||||
make_entry(
|
||||
options={CONF_ADMIN_USER_IDS: ["user-current"]},
|
||||
data={CONF_ADMIN_USER_IDS: ["ha-owner"]},
|
||||
context={"user_id": "ha-owner"},
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database) == ["user-current"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_owner_fallback_seeds_owner_accounts(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Last-resort seed: with no persisted copy and no flow-context
|
||||
user, HA owner accounts are seeded so first setup is never
|
||||
ownerless (the real flow may lose the context; owners can already
|
||||
do everything in HA)."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
hass.auth.async_get_users = AsyncMock(
|
||||
return_value=[
|
||||
SimpleNamespace(id="owner-1", is_owner=True),
|
||||
SimpleNamespace(id="member-1", is_owner=False),
|
||||
SimpleNamespace(id="owner-2", is_owner=True),
|
||||
]
|
||||
)
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert sorted(await list_admin_ids(database)) == ["owner-1", "owner-2"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_owner_fallback_not_used_when_context_present(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The context user (flow caller) wins over the owner fallback:
|
||||
a non-owner parent configuring the integration becomes the admin."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
hass.auth.async_get_users = AsyncMock(
|
||||
return_value=[SimpleNamespace(id="owner-1", is_owner=True)]
|
||||
)
|
||||
entry = await _setup_entry(
|
||||
hass,
|
||||
make_entry(context={"user_id": "parent-configured"}),
|
||||
hass.registry,
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
assert await list_admin_ids(database) == ["parent-configured"]
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
def test_seed_owner_ids_argument(tmp_path) -> None:
|
||||
async def _body(database):
|
||||
# Malformed owner lists are rejected like any other candidate —
|
||||
@@ -377,54 +215,13 @@ def test_seed_owner_ids_argument(tmp_path) -> None:
|
||||
_with_db(tmp_path, "seed-owner-arg.db")(_body)
|
||||
|
||||
|
||||
async def test_reopened_setup_failure_closes_database(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""A seeding failure on the reopened-record path closes the just-
|
||||
opened connection before re-raising (no leaked handles across HA's
|
||||
setup retries)."""
|
||||
import pytest as pytest_module
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import custom_components.nestquest as nestquest_module
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
|
||||
# First: a successful setup to create the runtime record and file.
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
await async_unload_entry(hass, entry)
|
||||
|
||||
# Now a re-setup whose seeding fails after the reopen.
|
||||
async def _failing_seed(database, **kwargs):
|
||||
raise RuntimeError("seed boom")
|
||||
|
||||
monkeypatch.setattr(
|
||||
nestquest_module, "seed_setup_admin", _failing_seed, raising=True
|
||||
)
|
||||
|
||||
close_calls: list[bool] = []
|
||||
original_close = NestQuestDatabase.close
|
||||
|
||||
async def _spy_close(self):
|
||||
close_calls.append(True)
|
||||
return await original_close(self)
|
||||
|
||||
monkeypatch.setattr(NestQuestDatabase, "close", _spy_close)
|
||||
|
||||
with pytest_module.raises(RuntimeError, match="seed boom"):
|
||||
await _setup_entry(hass, entry, hass.registry)
|
||||
# The reopen path opened AND closed a connection; the failure is
|
||||
# the last thing observed.
|
||||
assert close_calls[-1] is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# is_admin: the fail-closed resolver (Feature 09's verdict function)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_is_admin_verdict_matrix(tmp_path) -> None:
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.admin_allowlist import is_admin
|
||||
from custom_components.nestquest.core.admin_allowlist import is_admin
|
||||
|
||||
await set_admin_ids(database, ["user-owner"])
|
||||
assert await is_admin(database, "user-owner") is True
|
||||
@@ -447,7 +244,7 @@ def test_is_admin_verdict_matrix(tmp_path) -> None:
|
||||
def test_is_admin_empty_allowlist_fails_closed(tmp_path) -> None:
|
||||
"""An empty allowlist returns False for EVERYONE, not True."""
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.admin_allowlist import is_admin
|
||||
from custom_components.nestquest.core.admin_allowlist import is_admin
|
||||
|
||||
for candidate in ("user-owner", "", None, 1):
|
||||
assert await is_admin(database, candidate) is False
|
||||
@@ -460,7 +257,7 @@ def test_is_admin_false_after_last_admin_removal_attempt(tmp_path) -> None:
|
||||
"""The refusal keeps the verdict sound: a refused removal leaves
|
||||
the admin in place, so is_admin still resolves True."""
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.admin_allowlist import is_admin
|
||||
from custom_components.nestquest.core.admin_allowlist import is_admin
|
||||
|
||||
await set_admin_ids(database, ["user-owner"])
|
||||
with pytest.raises(ValueError, match="at least one admin"):
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
"""Tests for the panel-plane API client (Feature 18).
|
||||
|
||||
The client is exercised against a STUB transport only — no network, no
|
||||
aiohttp, no homeassistant: the injected session is a fake that speaks
|
||||
the same ``request(...)`` surface aiohttp's ``ClientSession`` exposes
|
||||
and records every call, so the tests assert exactly what the client
|
||||
puts on the wire (method, URL, Bearer header, JSON body) and how every
|
||||
failure mode (non-2xx, connection failure, timeout, malformed JSON)
|
||||
surfaces as the typed :class:`NestQuestApiError`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from conftest import make_config_entry
|
||||
|
||||
from custom_components.nestquest import api_client
|
||||
from custom_components.nestquest.api_client import (
|
||||
NestQuestApiClient,
|
||||
NestQuestApiError,
|
||||
is_valid_base_url,
|
||||
resolve_api_config,
|
||||
)
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_API_BASE_URL,
|
||||
CONF_PANEL_TOKEN,
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
)
|
||||
|
||||
BASE_URL = "http://api.test:8000"
|
||||
TOKEN = "test-panel-token"
|
||||
|
||||
#: A realistic panel snapshot payload (the documented shape of the
|
||||
#: Feature 16 snapshot route).
|
||||
SNAPSHOT_PAYLOAD = {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 2,
|
||||
"children": [
|
||||
{
|
||||
"child_id": 1,
|
||||
"child_name": "Ada",
|
||||
"present": False,
|
||||
"next_present": "2026-09-24",
|
||||
"due_today": 1,
|
||||
"completed_today": 0,
|
||||
"remaining_today": 1,
|
||||
"completion_pct": 0,
|
||||
"instances": [
|
||||
{
|
||||
"id": 7,
|
||||
"definition_id": 3,
|
||||
"child_id": 1,
|
||||
"title": "Pack bag",
|
||||
"icon": None,
|
||||
"window": "morning",
|
||||
"due_time": "10:00",
|
||||
"state": "open",
|
||||
"overdue": True,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class StubResponse:
|
||||
"""A fake aiohttp response: ``status`` plus ``await text()``."""
|
||||
|
||||
def __init__(self, status: int, body: str) -> None:
|
||||
self.status = status
|
||||
self._body = body
|
||||
|
||||
async def text(self) -> str:
|
||||
return self._body
|
||||
|
||||
|
||||
class _OutcomeContext:
|
||||
"""Async context manager yielding one scripted outcome.
|
||||
|
||||
Mirrors aiohttp's ``session.request(...)`` return value: entering
|
||||
the context performs the request, so a scripted transport error
|
||||
raises THERE — before any response object exists, exactly where
|
||||
aiohttp's connector raises on a refused connection.
|
||||
"""
|
||||
|
||||
def __init__(self, response, error) -> None:
|
||||
self._response = response
|
||||
self._error = error
|
||||
|
||||
async def __aenter__(self):
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._response
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class StubTransport:
|
||||
"""A no-network stand-in for aiohttp's ``ClientSession``.
|
||||
|
||||
Records every ``request(...)`` call as a dict (method, url, headers,
|
||||
json body) and answers from a scripted queue of outcomes — a
|
||||
:class:`StubResponse` or an exception per call, consumed in order —
|
||||
so each test drives exactly one exchange.
|
||||
"""
|
||||
|
||||
def __init__(self, *outcomes) -> None:
|
||||
self.calls: list[dict] = []
|
||||
self._outcomes = list(outcomes)
|
||||
|
||||
def request(self, method: str, url: str, **kwargs):
|
||||
self.calls.append(
|
||||
{
|
||||
"method": method,
|
||||
"url": url,
|
||||
"headers": kwargs.get("headers"),
|
||||
"json": kwargs.get("json"),
|
||||
}
|
||||
)
|
||||
if not self._outcomes:
|
||||
raise AssertionError("StubTransport ran out of scripted outcomes")
|
||||
outcome = self._outcomes.pop(0)
|
||||
if isinstance(outcome, BaseException):
|
||||
return _OutcomeContext(None, outcome)
|
||||
return _OutcomeContext(outcome, None)
|
||||
|
||||
|
||||
class HangingTransport:
|
||||
"""A transport whose request never answers (for the timeout test)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def request(self, method: str, url: str, **kwargs):
|
||||
self.calls.append({"method": method, "url": url})
|
||||
return _HangingContext()
|
||||
|
||||
|
||||
class _HangingContext:
|
||||
async def __aenter__(self):
|
||||
await asyncio.sleep(5)
|
||||
raise AssertionError("hanging transport was never cancelled")
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def make_client(transport, *, timeout_seconds: float = 5.0) -> NestQuestApiClient:
|
||||
"""Build a client over the stub transport with the test credentials."""
|
||||
return NestQuestApiClient(
|
||||
BASE_URL, TOKEN, transport, timeout_seconds=timeout_seconds
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Success paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_get_snapshot_parses_payload_and_sends_bearer() -> None:
|
||||
transport = StubTransport(
|
||||
StubResponse(200, json.dumps(SNAPSHOT_PAYLOAD))
|
||||
)
|
||||
client = make_client(transport)
|
||||
|
||||
snapshot = await client.get_snapshot()
|
||||
|
||||
assert snapshot == SNAPSHOT_PAYLOAD
|
||||
call = transport.calls[0]
|
||||
assert call["method"] == "GET"
|
||||
assert call["url"] == f"{BASE_URL}/api/v1/panel/snapshot"
|
||||
assert call["headers"] == {"Authorization": f"Bearer {TOKEN}"}
|
||||
assert call["json"] is None
|
||||
|
||||
|
||||
async def test_complete_instance_posts_body_and_headers() -> None:
|
||||
transport = StubTransport(StubResponse(200, '{"status": "done"}'))
|
||||
client = make_client(transport)
|
||||
|
||||
result = await client.complete_instance(42, 3)
|
||||
|
||||
assert result == {"status": "done"}
|
||||
call = transport.calls[0]
|
||||
assert call["method"] == "POST"
|
||||
assert call["url"] == f"{BASE_URL}/api/v1/panel/instances/42/complete"
|
||||
assert call["json"] == {"actor_child_id": 3}
|
||||
assert call["headers"]["Authorization"] == f"Bearer {TOKEN}"
|
||||
|
||||
|
||||
async def test_base_url_trailing_slash_is_normalized() -> None:
|
||||
"""A base URL with a trailing slash must not double the path slash."""
|
||||
transport = StubTransport(StubResponse(200, "{}"))
|
||||
client = NestQuestApiClient(
|
||||
f"{BASE_URL}/", TOKEN, transport, timeout_seconds=5.0
|
||||
)
|
||||
await client.get_snapshot()
|
||||
assert transport.calls[0]["url"] == f"{BASE_URL}/api/v1/panel/snapshot"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP failures: the typed error carries the status
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_snapshot_401_raises_typed_error() -> None:
|
||||
"""A wrong/missing token answers 401 and surfaces with that status."""
|
||||
transport = StubTransport(
|
||||
StubResponse(401, '{"detail": "Missing or invalid panel service token"}')
|
||||
)
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.get_snapshot()
|
||||
|
||||
error = excinfo.value
|
||||
assert error.status == 401
|
||||
assert not error.is_transport_error
|
||||
assert error.__cause__ is None
|
||||
# The token is a secret: it never reaches the raised message.
|
||||
assert TOKEN not in str(error)
|
||||
|
||||
|
||||
async def test_complete_unknown_instance_404_raises_typed_error() -> None:
|
||||
transport = StubTransport(
|
||||
StubResponse(404, '{"detail": "Quest instance not found"}')
|
||||
)
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.complete_instance(999999, 1)
|
||||
|
||||
assert excinfo.value.status == 404
|
||||
assert not excinfo.value.is_transport_error
|
||||
|
||||
|
||||
async def test_snapshot_500_raises_typed_error() -> None:
|
||||
"""Any non-2xx response is typed, whatever the status."""
|
||||
transport = StubTransport(StubResponse(500, "{}"))
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.get_snapshot()
|
||||
|
||||
assert excinfo.value.status == 500
|
||||
|
||||
|
||||
async def test_malformed_2xx_body_raises_typed_with_status() -> None:
|
||||
"""A 2xx body that is not JSON is a protocol failure, carrying its status."""
|
||||
transport = StubTransport(StubResponse(200, "<html>not json</html>"))
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.get_snapshot()
|
||||
|
||||
assert excinfo.value.status == 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transport failures: the typed error carries no status and chains the cause
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_connection_failure_raises_transport_error() -> None:
|
||||
transport = StubTransport(OSError("connection refused"))
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.get_snapshot()
|
||||
|
||||
error = excinfo.value
|
||||
assert error.status is None
|
||||
assert error.is_transport_error
|
||||
assert isinstance(error.__cause__, OSError)
|
||||
|
||||
|
||||
async def test_connection_failure_on_complete_is_typed() -> None:
|
||||
transport = StubTransport(OSError("connection refused"))
|
||||
client = make_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.complete_instance(7, 1)
|
||||
|
||||
assert excinfo.value.status is None
|
||||
assert excinfo.value.is_transport_error
|
||||
|
||||
|
||||
async def test_request_timeout_raises_transport_error() -> None:
|
||||
"""A hung API call surfaces as a typed transport error, once, with
|
||||
no retry: the one request is cancelled by the client's timeout."""
|
||||
transport = HangingTransport()
|
||||
client = make_client(transport, timeout_seconds=0.05)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
await client.get_snapshot()
|
||||
|
||||
assert excinfo.value.status is None
|
||||
assert excinfo.value.is_transport_error
|
||||
assert len(transport.calls) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Construction and config resolution
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_constructor_requires_full_base_url() -> None:
|
||||
for bad_url in (None, "", " ", "api.lan:8000", "http://", "ftp://x"):
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestApiClient(bad_url, TOKEN, StubTransport())
|
||||
|
||||
|
||||
def test_constructor_requires_non_empty_token() -> None:
|
||||
for bad_token in (None, "", " "):
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestApiClient(BASE_URL, bad_token, StubTransport())
|
||||
|
||||
|
||||
def test_constructor_requires_positive_timeout() -> None:
|
||||
for bad_timeout in (0, -1, "5", True, None):
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestApiClient(
|
||||
BASE_URL, TOKEN, StubTransport(), timeout_seconds=bad_timeout
|
||||
)
|
||||
|
||||
|
||||
def test_is_valid_base_url_accepts_full_http_urls() -> None:
|
||||
assert is_valid_base_url("http://127.0.0.1:8000")
|
||||
assert is_valid_base_url("https://nestquest.lan")
|
||||
assert is_valid_base_url(" http://127.0.0.1:8000 ")
|
||||
assert not is_valid_base_url("api.lan:8000")
|
||||
assert not is_valid_base_url("http://")
|
||||
assert not is_valid_base_url("")
|
||||
assert not is_valid_base_url(None)
|
||||
assert not is_valid_base_url(42)
|
||||
|
||||
|
||||
def test_resolve_api_config_prefers_options_then_data_then_defaults() -> None:
|
||||
options_only = make_config_entry(
|
||||
options={CONF_API_BASE_URL: "http://from-options:1"}
|
||||
)
|
||||
assert resolve_api_config(options_only) == (
|
||||
"http://from-options:1",
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
)
|
||||
|
||||
data_only = make_config_entry(
|
||||
data={
|
||||
CONF_API_BASE_URL: "http://from-data:2",
|
||||
CONF_PANEL_TOKEN: "from-data",
|
||||
}
|
||||
)
|
||||
assert resolve_api_config(data_only) == ("http://from-data:2", "from-data")
|
||||
|
||||
both = make_config_entry(
|
||||
options={CONF_API_BASE_URL: "http://from-options:3"},
|
||||
data={
|
||||
CONF_API_BASE_URL: "http://from-data:4",
|
||||
CONF_PANEL_TOKEN: "from-data",
|
||||
},
|
||||
)
|
||||
assert resolve_api_config(both) == (
|
||||
"http://from-options:3",
|
||||
"from-data",
|
||||
)
|
||||
|
||||
bare = make_config_entry()
|
||||
assert resolve_api_config(bare) == (DEFAULT_API_BASE_URL, DEFAULT_PANEL_TOKEN)
|
||||
|
||||
|
||||
def test_client_from_entry_reads_config_and_shared_session(monkeypatch) -> None:
|
||||
"""The production factory resolves the entry config and hands in HA's
|
||||
shared aiohttp session (stubbed module — no real HA, no network)."""
|
||||
fake_module = types.ModuleType("homeassistant.helpers.aiohttp_client")
|
||||
shared_session = object()
|
||||
fake_module.async_get_clientsession = lambda hass: shared_session
|
||||
monkeypatch.setitem(
|
||||
sys.modules, "homeassistant.helpers.aiohttp_client", fake_module
|
||||
)
|
||||
entry = make_config_entry(
|
||||
options={
|
||||
CONF_API_BASE_URL: "http://panel.lan:8443",
|
||||
CONF_PANEL_TOKEN: "entry-token",
|
||||
}
|
||||
)
|
||||
|
||||
client = api_client.client_from_entry(object(), entry)
|
||||
|
||||
assert client._session is shared_session
|
||||
assert client._base_url == "http://panel.lan:8443"
|
||||
assert client._panel_token == "entry-token"
|
||||
|
||||
|
||||
def test_client_from_entry_unconfigured_token_raises_at_construction(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
"""An entry with NO configured token (the shipped default) raises
|
||||
ValueError AT CONSTRUCTION — the client's fail-fast guard — rather
|
||||
than silently building a client that can only 401 (the documented
|
||||
contract: the options flow's non-empty validation is the user-facing
|
||||
guard; the coordinator must ensure a token is configured first or
|
||||
handle the construction error as "API not configured")."""
|
||||
fake_module = types.ModuleType("homeassistant.helpers.aiohttp_client")
|
||||
fake_module.async_get_clientsession = lambda hass: object()
|
||||
monkeypatch.setitem(
|
||||
sys.modules, "homeassistant.helpers.aiohttp_client", fake_module
|
||||
)
|
||||
entry = make_config_entry(
|
||||
options={CONF_API_BASE_URL: DEFAULT_API_BASE_URL},
|
||||
)
|
||||
assert resolve_api_config(entry)[1] == DEFAULT_PANEL_TOKEN == ""
|
||||
|
||||
with pytest.raises(ValueError, match="panel_token must be a non-empty"):
|
||||
api_client.client_from_entry(object(), entry)
|
||||
|
||||
# Same for a whitespace-only stored token: whitespace is not a token.
|
||||
entry_ws = make_config_entry(options={CONF_PANEL_TOKEN: " "})
|
||||
with pytest.raises(ValueError, match="panel_token must be a non-empty"):
|
||||
api_client.client_from_entry(object(), entry_ws)
|
||||
|
||||
|
||||
async def test_client_logs_nothing() -> None:
|
||||
"""The client emits no log records at all (the token must never
|
||||
reach a log line), success or failure."""
|
||||
import logging
|
||||
|
||||
records: list[logging.LogRecord] = []
|
||||
|
||||
class _Capture(logging.Handler):
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
records.append(record)
|
||||
|
||||
handler = _Capture()
|
||||
logging.getLogger().addHandler(handler)
|
||||
try:
|
||||
transport = StubTransport(StubResponse(401, "{}"))
|
||||
client = make_client(transport)
|
||||
with pytest.raises(NestQuestApiError):
|
||||
await client.get_snapshot()
|
||||
finally:
|
||||
logging.getLogger().removeHandler(handler)
|
||||
assert records == []
|
||||
+131
-120
@@ -1,50 +1,85 @@
|
||||
"""Tests for the per-child binary sensors (Feature 10, task 4)."""
|
||||
"""Tests for the per-child binary sensors (Feature 10, task 4).
|
||||
|
||||
The snapshot comes from the API service's panel route (the presence
|
||||
engine resolves server-side), so these tests script the route's
|
||||
payload through :class:`conftest.StubSnapshotClient` instead of
|
||||
seeding a local database.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
from conftest import StubSnapshotClient, set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import create_child, list_children
|
||||
from custom_components.nestquest.const import DOMAIN
|
||||
from custom_components.nestquest.dao_presence import PresenceSchedulesDao
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
from custom_components.nestquest.completion import complete_instance
|
||||
|
||||
SEED_HORIZON_DAYS = 3
|
||||
|
||||
|
||||
def _binary(hass, child_id: int, kind: str):
|
||||
return hass.entities[f"{DOMAIN}_child_{child_id}_{kind}"]
|
||||
|
||||
|
||||
async def _setup_entry(hass, make_entry):
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry
|
||||
def _child(
|
||||
child_id: int,
|
||||
name: str,
|
||||
*,
|
||||
present=True,
|
||||
next_present=None,
|
||||
instances=(),
|
||||
):
|
||||
completed = sum(1 for i in instances if i["state"] == "completed")
|
||||
due = len(instances)
|
||||
return {
|
||||
"child_id": child_id,
|
||||
"child_name": name,
|
||||
"present": present,
|
||||
"next_present": next_present,
|
||||
"due_today": due,
|
||||
"completed_today": completed,
|
||||
"remaining_today": due - completed,
|
||||
"completion_pct": 100 if due == 0 else round(completed / due * 100),
|
||||
"instances": list(instances),
|
||||
}
|
||||
|
||||
|
||||
async def _seed_two_children(database) -> tuple:
|
||||
ada = await create_child(database, "Ada")
|
||||
bo = await create_child(database, "Bo")
|
||||
today = datetime.date.today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
def _instance(instance_id: int, child_id: int, *, state="open") -> dict:
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": 3,
|
||||
"child_id": child_id,
|
||||
"title": "Brush teeth",
|
||||
"icon": "🦷",
|
||||
"window": "morning",
|
||||
"due_time": "08:00",
|
||||
"state": state,
|
||||
"overdue": False,
|
||||
"completed_at": None if state == "open" else "2026-09-23T07:55:00+00:00",
|
||||
"on_time": None if state == "open" else True,
|
||||
}
|
||||
|
||||
|
||||
def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
ADA = 1
|
||||
BO = 2
|
||||
CORY = 3
|
||||
|
||||
|
||||
async def _setup_entry(hass, make_entry, *payloads):
|
||||
"""Set up the integration with a scripted snapshot client."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
data={"api_base_url": "http://api.test:8000", "panel_token": "tok"}
|
||||
),
|
||||
[ada.id, bo.id],
|
||||
["morning"],
|
||||
hass.registry,
|
||||
)
|
||||
end = (today + datetime.timedelta(days=SEED_HORIZON_DAYS)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
return ada, bo
|
||||
set_coordinator_client(entry, StubSnapshotClient(*payloads))
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry, entry.runtime_data.coordinator
|
||||
|
||||
|
||||
async def test_all_done_off_with_open_quests_and_zero_quests(
|
||||
@@ -52,88 +87,76 @@ async def test_all_done_off_with_open_quests_and_zero_quests(
|
||||
) -> None:
|
||||
"""all_done is OFF while quests are owed AND on a zero-quest day;
|
||||
a child with no quests never fires the celebration automation."""
|
||||
entry = await _setup_entry(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, _bo = await _seed_two_children(database)
|
||||
await create_child(database, "Cory") # zero quests
|
||||
await coordinator.async_refresh()
|
||||
_entry, coordinator = await _setup_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
_payload(
|
||||
[
|
||||
_child(ADA, "Ada", instances=[_instance(7, ADA)]),
|
||||
_child(BO, "Bo", instances=[_instance(8, BO)]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
assert _binary(hass, ada.id, "all_done").is_on is False
|
||||
cory = [
|
||||
child for child in coordinator.data.children
|
||||
if child.child_name == "Cory"
|
||||
][0]
|
||||
assert _binary(hass, cory.child_id, "all_done").is_on is False
|
||||
assert _binary(hass, ADA, "all_done").is_on is False
|
||||
assert _binary(hass, BO, "all_done").is_on is False
|
||||
assert _binary(hass, CORY, "all_done").is_on is False
|
||||
|
||||
|
||||
async def test_all_done_on_only_when_day_clear(hass, make_entry) -> None:
|
||||
entry = await _setup_entry(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, _bo = await _seed_two_children(database)
|
||||
await coordinator.async_refresh()
|
||||
snapshot_ada = [
|
||||
child for child in coordinator.data.children
|
||||
if child.child_id == ada.id
|
||||
][0]
|
||||
instance_id = snapshot_ada.instances[0].instance_id
|
||||
await complete_instance(
|
||||
database,
|
||||
instance_id,
|
||||
actor_source="panel",
|
||||
actor_child_id=ada.id,
|
||||
_entry, coordinator = await _setup_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
_payload([_child(ADA, "Ada", instances=[_instance(7, ADA)])]),
|
||||
_payload(
|
||||
[
|
||||
_child(
|
||||
ADA,
|
||||
"Ada",
|
||||
instances=[_instance(7, ADA, state="completed")],
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
assert _binary(hass, ada.id, "all_done").is_on is True
|
||||
assert _binary(hass, ADA, "all_done").is_on is True
|
||||
|
||||
|
||||
async def test_present_today_on_without_schedule_off_when_absent(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""No schedule means present every day; an all-absent pattern
|
||||
today reports OFF."""
|
||||
entry = await _setup_entry(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, _bo = await _seed_two_children(database)
|
||||
await create_child(database, "Cory")
|
||||
today = datetime.date.today()
|
||||
await coordinator.async_refresh()
|
||||
cory = [
|
||||
child for child in coordinator.data.children
|
||||
if child.child_name == "Cory"
|
||||
][0]
|
||||
await PresenceSchedulesDao(database).upsert_by_child(
|
||||
cory.child_id, 1, today.isoformat(), ""
|
||||
"""Presence is resolved by the API's presence engine: present=True
|
||||
renders ON, present=False renders OFF."""
|
||||
_entry, _coordinator = await _setup_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
_payload([_child(ADA, "Ada"), _child(CORY, "Cory", present=False)]),
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
assert _binary(hass, ada.id, "present_today").is_on is True
|
||||
assert _binary(hass, cory.child_id, "present_today").is_on is False
|
||||
assert _binary(hass, ADA, "present_today").is_on is True
|
||||
assert _binary(hass, CORY, "present_today").is_on is False
|
||||
|
||||
|
||||
async def test_binary_sensor_identity_and_attributes(hass, make_entry) -> None:
|
||||
entry = await _setup_entry(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, _bo = await _seed_two_children(database)
|
||||
await coordinator.async_refresh()
|
||||
_entry, _coordinator = await _setup_entry(
|
||||
hass, make_entry, _payload([_child(ADA, "Ada")])
|
||||
)
|
||||
|
||||
all_done = _binary(hass, ada.id, "all_done")
|
||||
present = _binary(hass, ada.id, "present_today")
|
||||
assert all_done.unique_id == f"nestquest_child_{ada.id}_all_done"
|
||||
assert present.unique_id == f"nestquest_child_{ada.id}_present_today"
|
||||
all_done = _binary(hass, ADA, "all_done")
|
||||
present = _binary(hass, ADA, "present_today")
|
||||
assert all_done.unique_id == f"nestquest_child_{ADA}_all_done"
|
||||
assert present.unique_id == f"nestquest_child_{ADA}_present_today"
|
||||
assert all_done.name == "NestQuest Ada all done"
|
||||
assert present.name == "NestQuest Ada present today"
|
||||
for entity in (all_done, present):
|
||||
assert entity.device_info.name == "NestQuest Ada"
|
||||
assert all_done.extra_state_attributes == {
|
||||
"child_id": ada.id,
|
||||
"child_id": ADA,
|
||||
"child_name": "Ada",
|
||||
}
|
||||
assert present.extra_state_attributes == {
|
||||
"child_id": ada.id,
|
||||
"child_id": ADA,
|
||||
"child_name": "Ada",
|
||||
"next_present": None,
|
||||
}
|
||||
@@ -145,40 +168,28 @@ async def test_present_today_carries_next_present_when_away(
|
||||
"""A child away today carries the ISO date of their next present
|
||||
day (the panel's away plate renders ``Returns <weekday>, <Mon D>``
|
||||
from it); an always-absent pattern carries ``None``."""
|
||||
entry = await _setup_entry(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, _bo = await _seed_two_children(database)
|
||||
await create_child(database, "Cory")
|
||||
today = datetime.date.today()
|
||||
pattern = ",".join(
|
||||
str(day) for day in range(7) if day != today.weekday()
|
||||
_entry, _coordinator = await _setup_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
_payload(
|
||||
[
|
||||
_child(
|
||||
ADA,
|
||||
"Ada",
|
||||
present=False,
|
||||
next_present="2026-09-24",
|
||||
),
|
||||
_child(CORY, "Cory", present=False, next_present=None),
|
||||
]
|
||||
),
|
||||
)
|
||||
await PresenceSchedulesDao(database).upsert_by_child(
|
||||
ada.id, 1, today.isoformat(), pattern
|
||||
)
|
||||
await PresenceSchedulesDao(database).upsert_by_child(
|
||||
await _cory_id(database), 1, today.isoformat(), ""
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
assert _binary(hass, ada.id, "present_today").is_on is False
|
||||
assert _binary(hass, ada.id, "present_today").extra_state_attributes[
|
||||
assert _binary(hass, ADA, "present_today").is_on is False
|
||||
assert _binary(hass, ADA, "present_today").extra_state_attributes[
|
||||
"next_present"
|
||||
] == (today + datetime.timedelta(days=1)).isoformat()
|
||||
] == "2026-09-24"
|
||||
|
||||
cory = [
|
||||
child for child in coordinator.data.children
|
||||
if child.child_name == "Cory"
|
||||
][0]
|
||||
assert _binary(hass, cory.child_id, "present_today").is_on is False
|
||||
assert _binary(hass, cory.child_id, "present_today").extra_state_attributes[
|
||||
assert _binary(hass, CORY, "present_today").is_on is False
|
||||
assert _binary(hass, CORY, "present_today").extra_state_attributes[
|
||||
"next_present"
|
||||
] is None
|
||||
|
||||
|
||||
async def _cory_id(database) -> int:
|
||||
for child in await list_children(database):
|
||||
if child.display_name == "Cory":
|
||||
return child.id
|
||||
raise AssertionError("Cory was not created")
|
||||
|
||||
@@ -8,16 +8,16 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.children import (
|
||||
from custom_components.nestquest.core.children import (
|
||||
create_child,
|
||||
edit_child,
|
||||
list_children,
|
||||
reorder_children,
|
||||
set_child_active,
|
||||
)
|
||||
from custom_components.nestquest.dao_children import ChildRecord, ChildrenDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.dao_children import ChildRecord, ChildrenDao
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -739,12 +739,12 @@ def test_deactivating_child_preserves_definitions_instances_events(
|
||||
async def _body(database):
|
||||
from datetime import date, timedelta
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
QuestDefinitionsDao,
|
||||
ScheduleRulesDao,
|
||||
)
|
||||
@@ -831,7 +831,7 @@ def test_no_code_path_deletes_a_child_row() -> None:
|
||||
|
||||
import inspect
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
|
||||
methods = {
|
||||
name
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""The ``nestquest.complete_quest`` proxy to the API client (Feature 18).
|
||||
|
||||
The service is a thin proxy: a panel tap must reach the API's panel
|
||||
complete route through the entry's ONE shared API client (the same
|
||||
instance the coordinator polls and the SSE subscription reads), with
|
||||
exactly the payload contract the panel cards send (``instance_id``,
|
||||
``actor=panel``, ``actor_child_id``). The service performs NO local
|
||||
completion and fires NO local bus event — the API service emits the
|
||||
transition on its SSE stream and the integration's subscription
|
||||
re-fires it (firing it locally too would double-fire) — and it
|
||||
refreshes the coordinator after a successful call so the sensors
|
||||
reflect the completion immediately. Every failure (a typed
|
||||
:class:`NestQuestApiError`, an unconfigured client, a non-panel actor)
|
||||
surfaces as a :class:`HomeAssistantError`, token-free.
|
||||
|
||||
The scripted clients here stand in for the API service: recording and
|
||||
failing ``complete_instance`` implementations, no network, no aiohttp.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from conftest import ScriptedPanelClient, set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.api_client import NestQuestApiError
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_PANEL_TOKEN,
|
||||
DOMAIN,
|
||||
EVENT_CHILD_DAY_COMPLETE,
|
||||
EVENT_QUEST_COMPLETED,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
)
|
||||
|
||||
|
||||
class _RecordingApiClient(ScriptedPanelClient):
|
||||
"""Snapshot-only stand-in that RECORDS completion calls.
|
||||
|
||||
``complete_instance`` deliberately performs NO local write: the
|
||||
API service is remote, and the assertions below must be able to
|
||||
prove the service handler itself completed nothing locally.
|
||||
"""
|
||||
|
||||
|
||||
class _FailingApiClient(_RecordingApiClient):
|
||||
"""A stand-in whose completion fails the way the client types it."""
|
||||
|
||||
def __init__(self, error: NestQuestApiError, *outcomes) -> None:
|
||||
super().__init__(*outcomes)
|
||||
self.fail_complete_with = error
|
||||
|
||||
|
||||
def _empty_snapshot() -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"children": [],
|
||||
}
|
||||
|
||||
|
||||
async def _setup_entry(hass, make_entry, client):
|
||||
"""Wire, script, and set up an entry against the scripted client."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(data={CONF_PANEL_TOKEN: "secret-panel-token"}),
|
||||
hass.registry,
|
||||
)
|
||||
set_coordinator_client(entry, client)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry
|
||||
|
||||
|
||||
def _record_refreshes(entry) -> list[bool]:
|
||||
"""Replace the coordinator's refresh with a recording stand-in."""
|
||||
refreshes: list[bool] = []
|
||||
|
||||
async def _fake_refresh():
|
||||
refreshes.append(True)
|
||||
|
||||
entry.runtime_data.coordinator.async_refresh = _fake_refresh
|
||||
return refreshes
|
||||
|
||||
|
||||
async def test_complete_quest_reaches_the_shared_api_client(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A panel tap calls ``complete_instance`` on the entry's shared
|
||||
client with the tapped child, fires NO local event, and refreshes
|
||||
the coordinator immediately."""
|
||||
client = _RecordingApiClient(_empty_snapshot())
|
||||
entry = await _setup_entry(hass, make_entry, client)
|
||||
assert entry.runtime_data.coordinator.api_client is client, (
|
||||
"the service must proxy through the entry's ONE shared client"
|
||||
)
|
||||
refreshes = _record_refreshes(entry)
|
||||
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": 7,
|
||||
"actor": "panel",
|
||||
"actor_child_id": 1,
|
||||
},
|
||||
)
|
||||
|
||||
assert client.complete_calls == [(7, 1)]
|
||||
# No local firing: the completed (and day-complete) events arrive
|
||||
# over the SSE stream, re-fired by the subscription — never from
|
||||
# this handler.
|
||||
assert hass.bus.fired(EVENT_QUEST_COMPLETED) == []
|
||||
assert hass.bus.fired(EVENT_CHILD_DAY_COMPLETE) == []
|
||||
# The old immediate-update behaviour: the sensors' coordinator
|
||||
# refresh runs before the service call returns.
|
||||
assert refreshes == [True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "fragment"),
|
||||
[
|
||||
(
|
||||
NestQuestApiError(
|
||||
"NestQuest API POST /api/v1/panel/instances/7/complete "
|
||||
"failed with HTTP 401",
|
||||
status=401,
|
||||
),
|
||||
"failed with HTTP 401",
|
||||
),
|
||||
(
|
||||
NestQuestApiError(
|
||||
"NestQuest API POST /api/v1/panel/instances/7/complete "
|
||||
"transport failure: connection refused",
|
||||
status=None,
|
||||
),
|
||||
"transport failure",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_api_failure_surfaces_as_a_service_error(
|
||||
hass, make_entry, error, fragment
|
||||
) -> None:
|
||||
"""A typed API failure (non-2xx or transport) raises
|
||||
``HomeAssistantError`` carrying the typed message — which never
|
||||
includes the panel token — with nothing fired locally, and no
|
||||
refresh for a mutation that never happened."""
|
||||
client = _FailingApiClient(error, _empty_snapshot())
|
||||
entry = await _setup_entry(hass, make_entry, client)
|
||||
refreshes = _record_refreshes(entry)
|
||||
|
||||
with pytest.raises(HomeAssistantError, match=fragment) as excinfo:
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": 7,
|
||||
"actor": "panel",
|
||||
"actor_child_id": 1,
|
||||
},
|
||||
)
|
||||
# The typed error is chained, and the service error carries the
|
||||
# typed message only — never the panel token.
|
||||
assert excinfo.value.__cause__ is error
|
||||
assert "secret-panel-token" not in str(excinfo.value)
|
||||
assert client.complete_calls == [(7, 1)]
|
||||
assert hass.bus.fired(EVENT_QUEST_COMPLETED) == []
|
||||
assert hass.bus.fired(EVENT_CHILD_DAY_COMPLETE) == []
|
||||
assert refreshes == []
|
||||
|
||||
|
||||
async def test_unconfigured_api_client_surfaces_as_a_service_error(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""An entry with no completion surface (the unconfigured-token
|
||||
stub the coordinator swaps in) fails the service clearly instead
|
||||
of reaching an attribute error."""
|
||||
from custom_components.nestquest.coordinator import _UnconfiguredApiClient
|
||||
|
||||
await _setup_entry(hass, make_entry, _UnconfiguredApiClient())
|
||||
|
||||
with pytest.raises(
|
||||
HomeAssistantError, match="NestQuest API is not configured"
|
||||
):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": 7,
|
||||
"actor": "panel",
|
||||
"actor_child_id": 1,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def test_non_panel_actor_is_rejected_before_the_client(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The API's panel route completes as the tapped child only: a
|
||||
user-actor call fails fast with a clear error and never reaches
|
||||
the client."""
|
||||
client = _RecordingApiClient(_empty_snapshot())
|
||||
await _setup_entry(hass, make_entry, client)
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="actor must be 'panel'"):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": 7,
|
||||
"actor": "user",
|
||||
"actor_user_id": "admin-1",
|
||||
},
|
||||
context={"user_id": "admin-1"},
|
||||
)
|
||||
assert client.complete_calls == []
|
||||
@@ -8,27 +8,27 @@ import re
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.completion import (
|
||||
from custom_components.nestquest.core.completion import (
|
||||
append_event,
|
||||
complete_instance,
|
||||
instance_state,
|
||||
list_missed_for_child,
|
||||
uncomplete_instance,
|
||||
)
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
EVENT_COMPLETED,
|
||||
EVENT_UNCOMPLETED,
|
||||
CompletionEventRecord,
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
QuestDefinitionsDao,
|
||||
ScheduleRulesDao,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -311,7 +311,7 @@ def test_now_pins_occurred_at_utc(tmp_path) -> None:
|
||||
|
||||
|
||||
def test_module_never_exposes_update_or_delete() -> None:
|
||||
import custom_components.nestquest.completion as completion
|
||||
import custom_components.nestquest.core.completion as completion
|
||||
|
||||
public = {
|
||||
name
|
||||
|
||||
@@ -156,23 +156,13 @@ def test_no_hardcoded_domain_or_db_filename_in_new_modules() -> None:
|
||||
f"Found hard-coded database filename in {py_file.name}:{node.lineno}"
|
||||
)
|
||||
|
||||
async def test_flow_persists_flow_user_as_initial_admin(hass, make_flow) -> None:
|
||||
"""The HA user completing the flow lands in entry data as the
|
||||
initial admin copy: entry.context is not persisted by real HA, so
|
||||
the durable record must carry the owner."""
|
||||
from custom_components.nestquest.const import CONF_ADMIN_USER_IDS
|
||||
|
||||
flow = make_flow(hass)
|
||||
flow.context = {"user_id": "ha-owner"}
|
||||
result = await flow.async_step_user({})
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"] == {CONF_ADMIN_USER_IDS: ["ha-owner"]}
|
||||
|
||||
|
||||
async def test_flow_without_context_user_keeps_data_untouched(
|
||||
hass, make_flow
|
||||
) -> None:
|
||||
"""A submit with user input stores it as-is; no admin copy is
|
||||
invented (the allowlist lives in the API service's own store since
|
||||
the DB removal)."""
|
||||
flow = make_flow(hass)
|
||||
result = await flow.async_step_user({"horizon_days": 7})
|
||||
result = await flow.async_step_user({"update_interval": 60})
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"] == {"horizon_days": 7}
|
||||
assert result["data"] == {"update_interval": 60}
|
||||
|
||||
+684
-232
File diff suppressed because it is too large
Load Diff
@@ -14,9 +14,9 @@ Covers the contracts from task 4dd8f870 plus the review fixes:
|
||||
test feeds the scanner each bypass shape and asserts it flags them.
|
||||
- A settings object constructed with NON-default ``horizon_days`` and
|
||||
``day_rollover_time`` drives a materialization whose resulting window
|
||||
matches the non-default horizon — via BOTH the core ``materialize``
|
||||
path and the INTEGRATION path (``_run_horizon_materialization`` +
|
||||
``_register_day_rollover_listener``).
|
||||
matches the non-default horizon — via the core ``materialize`` path
|
||||
(the integration path it used to share is gone with the integration's
|
||||
database).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -29,7 +29,6 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
import custom_components.nestquest.core as _core_mod
|
||||
from conftest import freeze_nestquest_clock
|
||||
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_AFTERNOON_REMINDER_ENABLED,
|
||||
@@ -741,7 +740,7 @@ def test_settings_module_has_no_ha_imports() -> None:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Materialization over a non-default horizon: core path + integration path.
|
||||
# Materialization over a non-default horizon (core path).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -828,85 +827,3 @@ async def test_materialize_over_non_default_horizon(hass, tmp_path) -> None:
|
||||
) == []
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
async def test_integration_path_threads_settings(
|
||||
hass, tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""The integration path threads ``settings`` through horizon_window + rollover.
|
||||
|
||||
``_run_horizon_materialization`` calls
|
||||
``settings.horizon_window(today)`` (so the helper is real and shared,
|
||||
not recomputed inline), and ``_register_day_rollover_listener``
|
||||
registers at ``settings.day_rollover_hour_minute``. This runs the
|
||||
INTEGRATION path with ``horizon_days=3`` and
|
||||
``day_rollover_time='03:30'`` and asserts the resulting instance
|
||||
window matches [today, today+3] AND the registered hour/minute are 3/30.
|
||||
"""
|
||||
import custom_components.nestquest as nestquest
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
ScheduleRule,
|
||||
)
|
||||
|
||||
# Freeze the integration clock so "today" is deterministic (the
|
||||
# hass fixture's config.time_zone is UTC, so 2026-03-01 12:00 UTC
|
||||
# localizes to 2026-03-01).
|
||||
freeze_nestquest_clock(
|
||||
monkeypatch, datetime.datetime(2026, 3, 1, 12, 0, tzinfo=datetime.timezone.utc)
|
||||
)
|
||||
|
||||
database = await _prepare(tmp_path / "nq.db", hass.async_add_executor_job)
|
||||
try:
|
||||
settings = NestQuestSettings(horizon_days=3, day_rollover_time="03:30")
|
||||
today = datetime.date(2026, 3, 1)
|
||||
|
||||
NOW = "2026-03-01T12:00:00+00:00"
|
||||
child = await ChildrenDao(database).create("Ada", NOW)
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Daily chore",
|
||||
ScheduleRule(
|
||||
rule_type=RuleType.DAILY, start_date=today.isoformat()
|
||||
),
|
||||
[child.id],
|
||||
["morning"],
|
||||
)
|
||||
|
||||
# Integration path: the window comes from settings.horizon_window.
|
||||
await nestquest._run_horizon_materialization(hass, database, settings)
|
||||
|
||||
end = today + datetime.timedelta(days=3)
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child.id, today.isoformat(), end.isoformat()
|
||||
)
|
||||
dates = sorted({r.due_date for r in records})
|
||||
assert dates == [
|
||||
(today + datetime.timedelta(days=i)).isoformat()
|
||||
for i in range(4)
|
||||
]
|
||||
beyond = (end + datetime.timedelta(days=1)).isoformat()
|
||||
far = (end + datetime.timedelta(days=10)).isoformat()
|
||||
assert await QuestInstancesDao(database).list_by_date_range(
|
||||
child.id, beyond, far
|
||||
) == []
|
||||
|
||||
# The rollover listener registers at the configured hour/minute.
|
||||
remove = nestquest._register_day_rollover_listener(
|
||||
hass, database, settings
|
||||
)
|
||||
try:
|
||||
reg = hass.time_change.registrations[-1]
|
||||
assert reg["hour"] == 3
|
||||
assert reg["minute"] == 30
|
||||
finally:
|
||||
remove()
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
+65
-25
@@ -10,17 +10,22 @@ child's ``next_present``, a due-timed quest's ``overdue`` under a
|
||||
pinned ``now``, the custody ``cycle_day`` (> 1), and the panel payload
|
||||
dict shape (``done`` -> ``completed``, ``on_time`` passthrough, and
|
||||
``missed`` omission) are all exercised as literals.
|
||||
|
||||
The database is a standalone core one (the integration owns no
|
||||
database since Feature 18's DB removal); the closing round-trip pins
|
||||
that the integration's coordinator reconstructs the SAME dataclasses
|
||||
from the route's payload.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
from conftest import set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import create_child
|
||||
from custom_components.nestquest.completion import complete_instance
|
||||
from custom_components.nestquest.core.children import create_child
|
||||
from custom_components.nestquest.core.completion import complete_instance
|
||||
from custom_components.nestquest.core.snapshot import (
|
||||
ChildDaySnapshot,
|
||||
NestQuestSnapshot,
|
||||
@@ -28,14 +33,17 @@ from custom_components.nestquest.core.snapshot import (
|
||||
build_snapshot,
|
||||
instance_payload,
|
||||
)
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
PresenceSchedulesDao,
|
||||
)
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import create_quest_definition
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.materialize import materialize
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.quest_definitions import create_quest_definition
|
||||
from custom_components.nestquest.core.recurrence import ScheduleRule
|
||||
from custom_components.nestquest.core.settings import NestQuestSettings
|
||||
|
||||
|
||||
async def test_instance_payload_shape_and_missed_omission() -> None:
|
||||
@@ -105,7 +113,7 @@ async def test_instance_payload_shape_and_missed_omission() -> None:
|
||||
)
|
||||
|
||||
|
||||
async def test_build_snapshot_explicit_values(hass, make_entry, monkeypatch) -> None:
|
||||
async def test_build_snapshot_explicit_values(hass, make_entry, tmp_path) -> None:
|
||||
"""The builder produces the documented shape as literals, pinned in time.
|
||||
|
||||
Ada is AWAY today (a 2-week schedule whose absent week 0 covers today,
|
||||
@@ -117,15 +125,18 @@ async def test_build_snapshot_explicit_values(hass, make_entry, monkeypatch) ->
|
||||
scheduled active child is Ada, whose 2-week cycle anchored one day
|
||||
before today puts ``cycle_day`` at 2.
|
||||
"""
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
settings = entry.runtime_data.settings
|
||||
# A standalone core database (the integration owns none): the
|
||||
# builder and its seed run against it through the executor.
|
||||
database = NestQuestDatabase(hass.async_add_executor_job)
|
||||
await database.open(tmp_path / "snapshot.db")
|
||||
await apply_migrations(database)
|
||||
settings = NestQuestSettings()
|
||||
|
||||
# Single clock read for the seed/snapshot anchor (no midnight skew).
|
||||
today = coordinator._local_now().date()
|
||||
# Single clock read for the seed/snapshot anchor (no midnight skew);
|
||||
# the coordinator no longer owns a clock read (the API serves the
|
||||
# snapshot), so the test resolves the HA-local zone directly.
|
||||
time_zone = ZoneInfo(hass.config.time_zone)
|
||||
today = datetime.datetime.now(time_zone).date()
|
||||
# Pin the build instant at 12:00 local: past Ada's 10:00 due time
|
||||
# (overdue) and before Bo's 17:00, and the completion moment for Bo.
|
||||
pinned_now = datetime.datetime(
|
||||
@@ -294,13 +305,42 @@ async def test_build_snapshot_explicit_values(hass, make_entry, monkeypatch) ->
|
||||
== "missed"
|
||||
)
|
||||
|
||||
# REQUIRED wrapper tie-in: the coordinator's _async_update_data is a
|
||||
# thin WRAPPER over build_snapshot, so pinning its clock to the SAME
|
||||
# pinned_now the builder was called with must reproduce the builder's
|
||||
# snapshot byte-for-byte. The dataclasses are frozen, so == is a full
|
||||
# deep compare — a wrapper that mis-passed today vs now, or stopped
|
||||
# calling the builder, would diverge here even though the literal
|
||||
# assertions above still pass.
|
||||
monkeypatch.setattr(coordinator, "_local_now", lambda: pinned_now)
|
||||
await coordinator.async_refresh()
|
||||
# REQUIRED wrapper tie-in: since Feature 18 the coordinator's
|
||||
# refresh polls the snapshot through its API client, so pinning the
|
||||
# client to serve the payload of the SAME snapshot built with
|
||||
# pinned_now must reproduce the builder's snapshot byte-for-byte.
|
||||
# The dataclasses are frozen, so == is a full deep compare — a
|
||||
# reconstruction that dropped or reshaped a field would diverge
|
||||
# here even though the literal assertions above still pass.
|
||||
class _PinnedPayloadClient:
|
||||
async def get_snapshot(self):
|
||||
return {
|
||||
"today_iso": built.today_iso,
|
||||
"cycle_day": built.cycle_day,
|
||||
"children": [
|
||||
{
|
||||
"child_id": child.child_id,
|
||||
"child_name": child.child_name,
|
||||
"present": child.present,
|
||||
"next_present": child.next_present,
|
||||
"due_today": child.due_today,
|
||||
"completed_today": child.completed_today,
|
||||
"remaining_today": child.remaining_today,
|
||||
"completion_pct": child.completion_pct,
|
||||
"instances": instance_payload(
|
||||
child.instances, include_missed=False
|
||||
),
|
||||
}
|
||||
for child in built.children
|
||||
],
|
||||
}
|
||||
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(data={"api_base_url": "http://api.test:8000", "panel_token": "tok"}),
|
||||
hass.registry,
|
||||
)
|
||||
set_coordinator_client(entry, _PinnedPayloadClient())
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
assert coordinator.data == built
|
||||
await database.close()
|
||||
|
||||
@@ -6,15 +6,15 @@ import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import (
|
||||
from custom_components.nestquest.core.dao_children import (
|
||||
AdminUserRecord,
|
||||
AdminUsersDao,
|
||||
ChildRecord,
|
||||
ChildrenDao,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.schema import SCHEMA_V1_STATEMENTS
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.schema import SCHEMA_V1_STATEMENTS
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -504,9 +504,6 @@ def test_children_and_admin_sql_lives_only_in_dao_module() -> None:
|
||||
"tests/test_dao_rules.py", # rules/definitions guard, own scope
|
||||
"tests/test_dao_presence.py", # presence guard, own scope
|
||||
"tests/test_dao_instances.py", # instances guard, own scope
|
||||
"tests/test_startup_db.py", # row-count probe of the children
|
||||
# table only (proving a fresh setup loads); guard below covers
|
||||
# everything else
|
||||
}
|
||||
sql_pattern = re.compile(
|
||||
r"(FROM|INTO|UPDATE|DELETE\s+FROM|JOIN)\s+"
|
||||
@@ -558,32 +555,6 @@ def _strip_function_spans(text: str, names: set[str]) -> str:
|
||||
for number, line in enumerate(lines, start=1)
|
||||
if number not in excluded
|
||||
)
|
||||
|
||||
|
||||
def test_startup_db_test_file_uses_dao_elsewhere() -> None:
|
||||
"""Compensating self-scan for the startup-test exemption: outside
|
||||
the single sanctioned COUNT(*) probe, test_startup_db.py must go
|
||||
through the DAO for children/admin_users data access.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
startup_test = Path(__file__).parent / "test_startup_db.py"
|
||||
stripped = _strip_function_spans(
|
||||
startup_test.read_text(),
|
||||
{"test_setup_with_valid_file_preserves_rows"},
|
||||
)
|
||||
sql_pattern = re.compile(
|
||||
r"(SELECT\s[^\"']*?FROM|INSERT\s+INTO|UPDATE|DELETE\s+FROM|"
|
||||
r"FROM|JOIN)\s+[`'\"]*(\[)?(children|admin_users)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
assert sql_pattern.search(stripped) is None, (
|
||||
"test_startup_db.py must go through the DAO for these tables "
|
||||
"outside its sanctioned row-count probe"
|
||||
)
|
||||
|
||||
|
||||
def test_dao_matrix_test_file_raw_probes_are_only_constraint_probes() -> None:
|
||||
"""Compensating self-scan for the matrix-file exemption, structurally
|
||||
exact: parse the two sanctioned functions' ASTs and require that
|
||||
|
||||
@@ -7,16 +7,16 @@ import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
CompletionEventRecord,
|
||||
CompletionEventsDao,
|
||||
QuestInstanceRecord,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import ScheduleRulesDao, QuestDefinitionsDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.dao_rules import ScheduleRulesDao, QuestDefinitionsDao
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
|
||||
@@ -21,24 +21,24 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import (
|
||||
from custom_components.nestquest.core.dao_children import (
|
||||
AdminUsersDao,
|
||||
ChildrenDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
PresenceSchedulesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
ScheduleRulesDao,
|
||||
QuestDefinitionsDao,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
|
||||
@@ -6,15 +6,15 @@ import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverrideRecord,
|
||||
PresenceOverridesDao,
|
||||
PresenceScheduleRecord,
|
||||
PresenceSchedulesDao,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -741,12 +741,12 @@ def test_override_create_racing_conflicts_serialize(tmp_path) -> None:
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
async def _main():
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
|
||||
armed = {"active": False, "gated": False}
|
||||
gate_open = asyncio_module.Event()
|
||||
|
||||
@@ -6,8 +6,8 @@ import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
ScheduleRuleRecord,
|
||||
ScheduleRuleStorage,
|
||||
ScheduleRulesDao,
|
||||
@@ -17,9 +17,9 @@ from custom_components.nestquest.dao_rules import (
|
||||
schedule_rule_from_storage,
|
||||
schedule_rule_to_storage,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
@@ -341,7 +341,7 @@ def test_rule_delete_concurrent_with_definition_create_is_safe(
|
||||
# delete task has been scheduled, so the create holds
|
||||
# the connection lock while the delete queues behind
|
||||
# it — then the create proceeds and wins.
|
||||
import custom_components.nestquest.dao_rules as dao_rules
|
||||
import custom_components.nestquest.core.dao_rules as dao_rules
|
||||
|
||||
original_validate = (
|
||||
dao_rules.QuestDefinitionsDao._validate_rule_exists
|
||||
|
||||
+1
-66
@@ -14,7 +14,7 @@ import pytest
|
||||
from conftest import executor_for, make_hass
|
||||
|
||||
import custom_components.nestquest.core.db as db_module
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -933,68 +933,3 @@ def test_execute_many_exposes_rowcount(tmp_path) -> None:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle wiring: opened once per entry, closed on unload
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_setup_entry_opens_database_in_runtime_data(hass, make_entry) -> None:
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
runtime = entry.runtime_data
|
||||
assert runtime.database is not None
|
||||
assert runtime.database.connected is True
|
||||
await async_unload_entry(hass, entry)
|
||||
|
||||
|
||||
async def test_unload_entry_closes_database(hass, make_entry) -> None:
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
database = entry.runtime_data.database
|
||||
assert database.connected is True
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert database.connected is False
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
await database.fetch_one("SELECT 1")
|
||||
|
||||
|
||||
async def test_second_setup_does_not_open_second_connection(hass, make_entry) -> None:
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
first = entry.runtime_data.database
|
||||
|
||||
await async_setup_entry(hass, entry)
|
||||
second = entry.runtime_data.database
|
||||
|
||||
assert first is second
|
||||
assert first.connected is True
|
||||
await async_unload_entry(hass, entry)
|
||||
|
||||
|
||||
async def test_setup_unload_cycles_reopen_fresh_connection(hass, make_entry) -> None:
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
seen: list[NestQuestDatabase] = []
|
||||
for _ in range(3):
|
||||
await async_setup_entry(hass, entry)
|
||||
runtime = entry.runtime_data
|
||||
assert runtime.database.connected is True
|
||||
seen.append(runtime.database)
|
||||
await async_unload_entry(hass, entry)
|
||||
assert runtime.database.connected is False
|
||||
assert len(set(seen)) == 3
|
||||
assert hass.data == {}
|
||||
+121
-106
@@ -1,24 +1,16 @@
|
||||
"""Entity lifecycle across child add/deactivate/reactivate (Feature 10, task 8)."""
|
||||
"""Entity lifecycle across child add/deactivate/reactivate (Feature 10, task 8).
|
||||
|
||||
The household state the entities mirror comes from the API service's
|
||||
panel route, so a deactivate/reactivate/add is scripted as a payload
|
||||
change served by :class:`conftest.StubSnapshotClient`; the reload
|
||||
(unload + setup) re-polls it, exactly as production does.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
from conftest import StubSnapshotClient, set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
from custom_components.nestquest.children import (
|
||||
create_child,
|
||||
list_children,
|
||||
set_child_active,
|
||||
)
|
||||
from custom_components.nestquest.const import DOMAIN
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
|
||||
SEED_HORIZON_DAYS = 3
|
||||
PER_CHILD_KINDS = (
|
||||
"quests_due_today",
|
||||
"quests_completed_today",
|
||||
@@ -34,6 +26,78 @@ HOUSEHOLD_UNIQUE_IDS = (
|
||||
"nestquest_cycle_day",
|
||||
)
|
||||
|
||||
ADA = 1
|
||||
BO = 2
|
||||
CORY_ID = 4
|
||||
|
||||
|
||||
def _child(child_id: int, name: str, *, present=True, instances=()):
|
||||
completed = sum(1 for i in instances if i["state"] == "completed")
|
||||
due = len(instances)
|
||||
return {
|
||||
"child_id": child_id,
|
||||
"child_name": name,
|
||||
"present": present,
|
||||
"next_present": None,
|
||||
"due_today": due,
|
||||
"completed_today": completed,
|
||||
"remaining_today": due - completed,
|
||||
"completion_pct": 100 if due == 0 else round(completed / due * 100),
|
||||
"instances": list(instances),
|
||||
}
|
||||
|
||||
|
||||
def _instance(instance_id: int, child_id: int, *, state="open") -> dict:
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": 3,
|
||||
"child_id": child_id,
|
||||
"title": "Brush teeth",
|
||||
"icon": "🦷",
|
||||
"window": "morning",
|
||||
"due_time": "08:00",
|
||||
"state": state,
|
||||
"overdue": False,
|
||||
"completed_at": None if state == "open" else "2026-09-23T07:55:00+00:00",
|
||||
"on_time": None if state == "open" else True,
|
||||
}
|
||||
|
||||
|
||||
def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
#: The full household (Ada + Bo, one daily quest each) and the states
|
||||
#: the lifecycle walks through: Bo deactivated, reactivated, completed.
|
||||
_BOTH = _payload(
|
||||
[
|
||||
_child(ADA, "Ada", instances=[_instance(7, ADA)]),
|
||||
_child(BO, "Bo", instances=[_instance(8, BO)]),
|
||||
]
|
||||
)
|
||||
_BO_GONE = _payload([_child(ADA, "Ada", instances=[_instance(7, ADA)])])
|
||||
_BO_DONE = _payload(
|
||||
[
|
||||
_child(ADA, "Ada", instances=[_instance(7, ADA)]),
|
||||
_child(BO, "Bo", instances=[_instance(8, BO, state="completed")]),
|
||||
]
|
||||
)
|
||||
_ADA_ONLY = _payload([_child(ADA, "Ada", instances=[_instance(7, ADA)])])
|
||||
_ADA_AND_CORY = _payload(
|
||||
[
|
||||
_child(ADA, "Ada", instances=[_instance(7, ADA)]),
|
||||
_child(CORY_ID, "Cory"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _child_unique_ids(child_id: int) -> set[str]:
|
||||
return {f"nestquest_child_{child_id}_{kind}" for kind in PER_CHILD_KINDS}
|
||||
|
||||
|
||||
async def _reload(hass, entry) -> None:
|
||||
"""Unload then set up: the harness's restart/reload equivalent."""
|
||||
@@ -41,46 +105,36 @@ async def _reload(hass, entry) -> None:
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
|
||||
def _child_unique_ids(child_id: int) -> set[str]:
|
||||
return {f"nestquest_child_{child_id}_{kind}" for kind in PER_CHILD_KINDS}
|
||||
|
||||
|
||||
async def _setup_and_seed(hass, make_entry):
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
ada = await create_child(database, "Ada")
|
||||
bo = await create_child(database, "Bo")
|
||||
today = datetime.date.today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
async def _setup_with_household(hass, make_entry, *payloads):
|
||||
"""Set up the entry with a scripted, ordered snapshot history."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
data={"api_base_url": "http://api.test:8000", "panel_token": "tok"}
|
||||
),
|
||||
[ada.id, bo.id],
|
||||
["morning"],
|
||||
hass.registry,
|
||||
)
|
||||
end = (today + datetime.timedelta(days=SEED_HORIZON_DAYS)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
await entry.runtime_data.coordinator.async_refresh()
|
||||
return entry, ada, bo
|
||||
client = set_coordinator_client(entry, StubSnapshotClient(*payloads))
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry, entry.runtime_data.coordinator, client
|
||||
|
||||
|
||||
async def test_deactivated_child_entities_removed_on_reload(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, bo = await _setup_and_seed(hass, make_entry)
|
||||
assert _child_unique_ids(ada.id) <= set(hass.entities)
|
||||
assert _child_unique_ids(bo.id) <= set(hass.entities)
|
||||
"""A child absent from the API's snapshot loses its entities on
|
||||
reload; the surviving child's entities are untouched."""
|
||||
entry, _coordinator, _client = await _setup_with_household(
|
||||
hass, make_entry, _BOTH, _BO_GONE
|
||||
)
|
||||
assert _child_unique_ids(ADA) <= set(hass.entities)
|
||||
assert _child_unique_ids(BO) <= set(hass.entities)
|
||||
|
||||
await set_child_active(entry.runtime_data.database, bo.id, False)
|
||||
await _reload(hass, entry)
|
||||
|
||||
assert _child_unique_ids(ada.id) <= set(hass.entities), (
|
||||
assert _child_unique_ids(ADA) <= set(hass.entities), (
|
||||
"the surviving child's entities must be untouched"
|
||||
)
|
||||
assert not (_child_unique_ids(bo.id) & set(hass.entities)), (
|
||||
assert not (_child_unique_ids(BO) & set(hass.entities)), (
|
||||
"the deactivated child's entities must be gone after reload"
|
||||
)
|
||||
|
||||
@@ -88,100 +142,61 @@ async def test_deactivated_child_entities_removed_on_reload(
|
||||
async def test_reactivation_restores_entities_with_original_unique_ids(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, bo = await _setup_and_seed(hass, make_entry)
|
||||
original = _child_unique_ids(bo.id)
|
||||
await set_child_active(entry.runtime_data.database, bo.id, False)
|
||||
original = _child_unique_ids(BO)
|
||||
entry, _coordinator, _client = await _setup_with_household(
|
||||
hass, make_entry, _BOTH, _BO_GONE, _BOTH
|
||||
)
|
||||
await _reload(hass, entry)
|
||||
assert not (original & set(hass.entities))
|
||||
|
||||
await set_child_active(entry.runtime_data.database, bo.id, True)
|
||||
await _reload(hass, entry)
|
||||
|
||||
assert original <= set(hass.entities), (
|
||||
"reactivation must restore the exact original unique_ids"
|
||||
)
|
||||
bo_due = hass.entities[f"nestquest_child_{bo.id}_quests_due_today"]
|
||||
bo_due = hass.entities[f"nestquest_child_{BO}_quests_due_today"]
|
||||
assert bo_due.native_value == 1, "restored entities carry live state"
|
||||
|
||||
|
||||
async def test_new_child_gets_entities_without_disturbing_existing(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, bo = await _setup_and_seed(hass, make_entry)
|
||||
before_ada = set(hass.entities) & _child_unique_ids(ada.id)
|
||||
"""A child ADDED to the API's snapshot gains its entities on
|
||||
reload; the existing children's entities are untouched."""
|
||||
entry, _coordinator, _client = await _setup_with_household(
|
||||
hass, make_entry, _ADA_ONLY, _ADA_AND_CORY
|
||||
)
|
||||
before_ada = set(hass.entities) & _child_unique_ids(ADA)
|
||||
|
||||
cory = await create_child(entry.runtime_data.database, "Cory")
|
||||
await _reload(hass, entry)
|
||||
|
||||
assert before_ada <= set(hass.entities), "existing entities untouched"
|
||||
assert _child_unique_ids(cory.id) <= set(hass.entities), (
|
||||
assert _child_unique_ids(CORY_ID) <= set(hass.entities), (
|
||||
"the new child's entities appear after reload"
|
||||
)
|
||||
assert hass.entities[f"nestquest_child_{cory.id}_quests_due_today"].native_value == 0
|
||||
assert hass.entities[
|
||||
f"nestquest_child_{CORY_ID}_quests_due_today"
|
||||
].native_value == 0
|
||||
|
||||
|
||||
async def test_restart_equivalent_restores_all_entity_states(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Unload + setup (the restart equivalent) restores every active
|
||||
child's entities with correct states and the household rollups."""
|
||||
from custom_components.nestquest.completion import complete_instance
|
||||
|
||||
entry, ada, bo = await _setup_and_seed(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
snapshot_ada = next(
|
||||
child
|
||||
for child in coordinator.data.children
|
||||
if child.child_id == ada.id
|
||||
child's entities with the API's current states and the household
|
||||
rollups."""
|
||||
entry, _coordinator, _client = await _setup_with_household(
|
||||
hass, make_entry, _BOTH, _BO_DONE
|
||||
)
|
||||
await complete_instance(
|
||||
entry.runtime_data.database,
|
||||
snapshot_ada.instances[0].instance_id,
|
||||
actor_source="panel",
|
||||
actor_child_id=ada.id,
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
assert hass.entities[
|
||||
f"nestquest_child_{ada.id}_quests_completed_today"
|
||||
].native_value == 1
|
||||
|
||||
await _reload(hass, entry)
|
||||
|
||||
assert hass.entities[
|
||||
f"nestquest_child_{ada.id}_quests_completed_today"
|
||||
].native_value == 1, "completed count survives the restart"
|
||||
assert hass.entities[
|
||||
f"nestquest_child_{bo.id}_quests_completed_today"
|
||||
f"nestquest_child_{ADA}_quests_completed_today"
|
||||
].native_value == 0
|
||||
assert hass.entities[
|
||||
f"nestquest_child_{BO}_quests_completed_today"
|
||||
].native_value == 1, "the API's recorded completion survives the restart"
|
||||
assert set(HOUSEHOLD_UNIQUE_IDS) <= set(hass.entities)
|
||||
assert hass.entities[
|
||||
"nestquest_household_quests_completed_today"
|
||||
].native_value == 1
|
||||
|
||||
|
||||
async def test_unload_shuts_coordinator_before_closing_database(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The coordinator's listeners are cleared while the database is
|
||||
still connected: a scheduled refresh must never race the close."""
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
seen_connected = []
|
||||
|
||||
async def _probe_shutdown():
|
||||
seen_connected.append(database.connected)
|
||||
|
||||
original_close = database.close
|
||||
|
||||
async def _recording_close():
|
||||
seen_connected.append("closing")
|
||||
await original_close()
|
||||
|
||||
coordinator.async_shutdown = _probe_shutdown
|
||||
database.close = _recording_close
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert seen_connected == [True, "closing"], (
|
||||
"coordinator shutdown must precede the database close"
|
||||
)
|
||||
|
||||
+217
-128
@@ -2,72 +2,156 @@
|
||||
|
||||
One fixture drives every assertion the done-condition names: correct
|
||||
values for every sensor and binary sensor (including the zero-quest
|
||||
child and the 255-character state limit), the three events firing
|
||||
exactly once with schema-valid payloads, the instances payload
|
||||
omitting missed instances while admin_instances includes them, and no
|
||||
entities for an inactive child. The per-task test files cover each
|
||||
behavior in depth; this file is the single pass that proves them all
|
||||
against ONE fixture, so a regression in any contract fails here too.
|
||||
child and the 255-character state limit), the completed/uncompleted/
|
||||
day-complete events re-fired exactly once from the API's SSE frames,
|
||||
the panel payload omitting missed instances while admin_instances
|
||||
equals it, and no entities for a child the API does not report. The
|
||||
per-task test files cover each behavior in depth; this file is the
|
||||
single pass that proves them all against ONE fixture, so a regression
|
||||
in any contract fails here too.
|
||||
|
||||
Since the DB removal the household state and every transition come
|
||||
from the API service, so the fixture scripts the panel route's
|
||||
payloads and completion surface (:class:`conftest.ScriptedPanelClient`)
|
||||
and delivers the transition frames through the SSE subscription — the
|
||||
production event path.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import re
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
from conftest import ScriptedPanelClient, set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import (
|
||||
create_child,
|
||||
list_children,
|
||||
set_child_active,
|
||||
)
|
||||
from custom_components.nestquest.completion import derive_state
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
DOMAIN,
|
||||
EVENT_CHILD_DAY_COMPLETE,
|
||||
EVENT_QUEST_COMPLETED,
|
||||
EVENT_QUEST_UNCOMPLETED,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
)
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
|
||||
_TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$")
|
||||
|
||||
ADA = 1
|
||||
BO = 2
|
||||
CORY = 3
|
||||
|
||||
_OCCURRED = "2026-09-23T07:55:00+00:00"
|
||||
|
||||
|
||||
def _instance(instance_id: int, child_id: int, *, window="morning", state="open"):
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": 3,
|
||||
"child_id": child_id,
|
||||
"title": "Brush teeth",
|
||||
"icon": "🦷",
|
||||
"window": window,
|
||||
"due_time": "08:00" if window == "morning" else "19:00",
|
||||
"state": state,
|
||||
"overdue": False,
|
||||
"completed_at": None if state == "open" else _OCCURRED,
|
||||
"on_time": None if state == "open" else True,
|
||||
}
|
||||
|
||||
|
||||
def _child(child_id: int, name: str, instances=()):
|
||||
completed = sum(1 for i in instances if i["state"] == "completed")
|
||||
due = len(instances)
|
||||
return {
|
||||
"child_id": child_id,
|
||||
"child_name": name,
|
||||
"present": True,
|
||||
"next_present": None,
|
||||
"due_today": due,
|
||||
"completed_today": completed,
|
||||
"remaining_today": due - completed,
|
||||
"completion_pct": 100 if due == 0 else round(completed / due * 100),
|
||||
"instances": list(instances),
|
||||
}
|
||||
|
||||
|
||||
def _payload(children, cycle_day=0) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": cycle_day,
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
def _completed_frame(instance_id: int, child_id: int, child_name: str, window: str):
|
||||
"""The completed-event frame the API service publishes for one
|
||||
panel completion (the day-complete rule is the API's; its payload
|
||||
shape is pinned by tests/test_api_sse.py on the production
|
||||
plane)."""
|
||||
return (
|
||||
EVENT_QUEST_COMPLETED,
|
||||
{
|
||||
"child_id": child_id,
|
||||
"child_name": child_name,
|
||||
"instance_id": instance_id,
|
||||
"quest_title": "Brush teeth",
|
||||
"window": window,
|
||||
"due_date": "2026-09-23",
|
||||
"due_time": "08:00" if window == "morning" else "19:00",
|
||||
"occurred_at": _OCCURRED,
|
||||
"was_on_time": True,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _day_complete_frame(child_id: int, child_name: str):
|
||||
"""The day-complete frame the API publishes once a child's day
|
||||
clears (after the LAST completion of the day)."""
|
||||
return (
|
||||
EVENT_CHILD_DAY_COMPLETE,
|
||||
{
|
||||
"child_id": child_id,
|
||||
"child_name": child_name,
|
||||
"quests_due": 2,
|
||||
"quests_completed": 2,
|
||||
"occurred_at": _OCCURRED,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _fixture(hass, make_entry):
|
||||
"""Two quest children, one zero-quest child, one inactive child."""
|
||||
"""Two quest children, one zero-quest child; the inactive child is
|
||||
simply ABSENT from the API's snapshot (the API only reports active
|
||||
children, so the integration can never create its entities)."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(data={CONF_ADMIN_USER_IDS: ["admin-1"]}), hass.registry
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
ada = await create_child(database, "Ada")
|
||||
bo = await create_child(database, "Bo")
|
||||
cory = await create_child(database, "Cory")
|
||||
ghost = await create_child(database, "Ghost")
|
||||
await set_child_active(database, ghost.id, False)
|
||||
today = datetime.date.today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
make_entry(
|
||||
data={"api_base_url": "http://api.test:8000", "panel_token": "tok"}
|
||||
),
|
||||
[ada.id, bo.id],
|
||||
["morning", "evening"],
|
||||
hass.registry,
|
||||
)
|
||||
end = (today + datetime.timedelta(days=3)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
await entry.runtime_data.coordinator.async_refresh()
|
||||
return entry, (ada, bo, cory, ghost)
|
||||
client = ScriptedPanelClient(
|
||||
_payload(
|
||||
[
|
||||
_child(ADA, "Ada", [_instance(7, ADA), _instance(8, ADA, window="evening")]),
|
||||
_child(BO, "Bo", [_instance(9, BO), _instance(10, BO, window="evening")]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
),
|
||||
_payload(
|
||||
[
|
||||
_child(
|
||||
ADA,
|
||||
"Ada",
|
||||
[
|
||||
_instance(7, ADA, state="completed"),
|
||||
_instance(8, ADA, window="evening", state="completed"),
|
||||
],
|
||||
),
|
||||
_child(BO, "Bo", [_instance(9, BO), _instance(10, BO, window="evening")]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
),
|
||||
)
|
||||
set_coordinator_client(entry, client)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry, client
|
||||
|
||||
|
||||
def _sensor(hass, child_id, kind):
|
||||
@@ -75,11 +159,11 @@ def _sensor(hass, child_id, kind):
|
||||
|
||||
|
||||
async def test_entity_and_event_matrix(hass, make_entry) -> None:
|
||||
entry, (ada, bo, cory, ghost) = await _fixture(hass, make_entry)
|
||||
entry, client = await _fixture(hass, make_entry)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
|
||||
# --- Every active child has the full entity set; the inactive
|
||||
# child has none.
|
||||
# --- Every reported child has the full entity set; the child the
|
||||
# API does not report has none.
|
||||
kinds = (
|
||||
"quests_due_today",
|
||||
"quests_completed_today",
|
||||
@@ -89,36 +173,37 @@ async def test_entity_and_event_matrix(hass, make_entry) -> None:
|
||||
"all_done",
|
||||
"present_today",
|
||||
)
|
||||
for child in (ada, bo, cory):
|
||||
ghost_id = 99
|
||||
for child in (ADA, BO, CORY):
|
||||
for kind in kinds:
|
||||
assert f"{DOMAIN}_child_{child.id}_{kind}" in hass.entities, kind
|
||||
assert f"{DOMAIN}_child_{child}_{kind}" in hass.entities, kind
|
||||
for kind in kinds:
|
||||
assert f"{DOMAIN}_child_{ghost.id}_{kind}" not in hass.entities, (
|
||||
"inactive children must have no entities"
|
||||
assert f"{DOMAIN}_child_{ghost_id}_{kind}" not in hass.entities, (
|
||||
"children absent from the API snapshot must have no entities"
|
||||
)
|
||||
|
||||
# --- Correct values against the fixture: Ada and Bo owe two
|
||||
# quests (morning + evening), Cory owes none and is still 100%.
|
||||
for child in (ada, bo):
|
||||
assert _sensor(hass, child.id, "quests_due_today").native_value == 2
|
||||
for child in (ADA, BO):
|
||||
assert _sensor(hass, child, "quests_due_today").native_value == 2
|
||||
assert (
|
||||
_sensor(hass, child.id, "quests_completed_today").native_value == 0
|
||||
_sensor(hass, child, "quests_completed_today").native_value == 0
|
||||
)
|
||||
assert (
|
||||
_sensor(hass, child.id, "quests_remaining_today").native_value == 2
|
||||
_sensor(hass, child, "quests_remaining_today").native_value == 2
|
||||
)
|
||||
assert (
|
||||
_sensor(hass, child.id, "completion_pct_today").native_value == 0
|
||||
_sensor(hass, child, "completion_pct_today").native_value == 0
|
||||
)
|
||||
assert _sensor(hass, child.id, "next_quest").native_value == (
|
||||
assert _sensor(hass, child, "next_quest").native_value == (
|
||||
"Brush teeth"
|
||||
)
|
||||
assert _sensor(hass, child.id, "all_done").is_on is False
|
||||
assert _sensor(hass, child.id, "present_today").is_on is True
|
||||
assert _sensor(hass, cory.id, "quests_due_today").native_value == 0
|
||||
assert _sensor(hass, cory.id, "completion_pct_today").native_value == 100
|
||||
assert _sensor(hass, cory.id, "all_done").is_on is False
|
||||
assert _sensor(hass, cory.id, "next_quest").native_value == "none"
|
||||
assert _sensor(hass, child, "all_done").is_on is False
|
||||
assert _sensor(hass, child, "present_today").is_on is True
|
||||
assert _sensor(hass, CORY, "quests_due_today").native_value == 0
|
||||
assert _sensor(hass, CORY, "completion_pct_today").native_value == 100
|
||||
assert _sensor(hass, CORY, "all_done").is_on is False
|
||||
assert _sensor(hass, CORY, "next_quest").native_value == "none"
|
||||
|
||||
# --- Household rollups equal the per-child sums.
|
||||
assert hass.entities[
|
||||
@@ -138,22 +223,31 @@ async def test_entity_and_event_matrix(hass, make_entry) -> None:
|
||||
), unique_id
|
||||
|
||||
# --- Completing both of Ada's quests fires the events exactly
|
||||
# once each and flips her entities immediately.
|
||||
instances = await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(
|
||||
ada.id, datetime.date.today().isoformat(), datetime.date.today().isoformat()
|
||||
# once each and flips her entities immediately. The transition
|
||||
# events arrive over the API's SSE stream (the subscription
|
||||
# re-fires them), never from the service handler.
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": 7, "actor": "panel", "actor_child_id": ADA},
|
||||
)
|
||||
for instance in instances:
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": ada.id,
|
||||
},
|
||||
)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": 8, "actor": "panel", "actor_child_id": ADA},
|
||||
)
|
||||
client.published_frames.extend(
|
||||
[
|
||||
_completed_frame(7, ADA, "Ada", "morning"),
|
||||
_completed_frame(8, ADA, "Ada", "evening"),
|
||||
# The API publishes the day-complete frame only when the
|
||||
# day clears — after the LAST completion of the day.
|
||||
_day_complete_frame(ADA, "Ada"),
|
||||
]
|
||||
)
|
||||
from conftest import refire_api_transitions
|
||||
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
assert len(hass.bus.fired(EVENT_QUEST_COMPLETED)) == 2
|
||||
for payload in hass.bus.fired(EVENT_QUEST_COMPLETED):
|
||||
assert _TIMESTAMP.match(payload["occurred_at"])
|
||||
@@ -162,53 +256,53 @@ async def test_entity_and_event_matrix(hass, make_entry) -> None:
|
||||
assert payload["quest_title"] == "Brush teeth"
|
||||
assert isinstance(payload["instance_id"], int)
|
||||
assert len(hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)) == 1
|
||||
assert _sensor(hass, ada.id, "all_done").is_on is True
|
||||
assert _sensor(hass, ada.id, "quests_remaining_today").native_value == 0
|
||||
# The next scripted snapshot reflects both completions.
|
||||
await coordinator.async_refresh()
|
||||
assert _sensor(hass, ADA, "all_done").is_on is True
|
||||
assert _sensor(hass, ADA, "quests_remaining_today").native_value == 0
|
||||
assert (
|
||||
_sensor(hass, ada.id, "completion_pct_today").native_value == 100
|
||||
_sensor(hass, ADA, "completion_pct_today").native_value == 100
|
||||
)
|
||||
|
||||
# --- Reversing one quest fires the uncompleted event exactly once
|
||||
# and restores the owed counts.
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
{"instance_id": instances[0].id, "actor": "user"},
|
||||
context={"user_id": "admin-1"},
|
||||
# --- Reversing one quest fires the uncompleted event exactly once.
|
||||
# The HA ``uncomplete_quest`` service is gone (the API service's
|
||||
# admin route is the reversal path), so the reversal is the API's:
|
||||
# it publishes the uncompleted frame and the integration re-fires
|
||||
# it; the coordinator's next poll picks the restored counts up.
|
||||
client.published_frames.append(
|
||||
(
|
||||
EVENT_QUEST_UNCOMPLETED,
|
||||
{
|
||||
"child_id": ADA,
|
||||
"child_name": "Ada",
|
||||
"instance_id": 7,
|
||||
"quest_title": "Brush teeth",
|
||||
"window": "morning",
|
||||
"due_date": "2026-09-23",
|
||||
"due_time": "08:00",
|
||||
"occurred_at": _OCCURRED,
|
||||
},
|
||||
)
|
||||
)
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
assert len(hass.bus.fired(EVENT_QUEST_UNCOMPLETED)) == 1
|
||||
assert _sensor(hass, ada.id, "all_done").is_on is False
|
||||
assert _sensor(hass, ada.id, "quests_remaining_today").native_value == 1
|
||||
|
||||
# --- The instances payload omits missed instances while
|
||||
# admin_instances includes them (D-009): pin the derive clock
|
||||
# forward in the TEST ONLY so today's open instances read missed.
|
||||
original_refresh = coordinator._async_update_data
|
||||
|
||||
async def _future_dated_refresh():
|
||||
import custom_components.nestquest.core.snapshot as snapshot_module
|
||||
|
||||
real_derive = snapshot_module.derive_state
|
||||
|
||||
def _derive(instance, latest, today):
|
||||
return real_derive(instance, latest, today + datetime.timedelta(days=1))
|
||||
|
||||
snapshot_module.derive_state = _derive
|
||||
try:
|
||||
return await original_refresh()
|
||||
finally:
|
||||
snapshot_module.derive_state = real_derive
|
||||
|
||||
coordinator._async_update_data = _future_dated_refresh
|
||||
# --- The panel payload omits missed instances (D-009) — the API
|
||||
# panel route omits missed rows ENTIRELY, so admin_instances
|
||||
# cannot carry them either (the admin surface for missed quests is
|
||||
# the PWA, reading the API directly). A snapshot built from the
|
||||
# payload can only ever hold open and completed rows: pin that
|
||||
# the payload round-trips verbatim.
|
||||
await coordinator.async_refresh()
|
||||
attributes = _sensor(hass, bo.id, "quests_due_today").extra_state_attributes
|
||||
assert attributes["instances"] == [], "panel payload omits missed"
|
||||
assert len(attributes["admin_instances"]) == 2
|
||||
assert all(
|
||||
entry["state"] == "missed" for entry in attributes["admin_instances"]
|
||||
attributes = _sensor(hass, BO, "quests_due_today").extra_state_attributes
|
||||
assert attributes["instances"] == [
|
||||
dict(_instance(9, BO)),
|
||||
dict(_instance(10, BO, window="evening")),
|
||||
], "the panel payload round-trips the API's open rows verbatim"
|
||||
assert attributes["admin_instances"] == attributes["instances"], (
|
||||
"the API payload omits missed rows, so the admin payload "
|
||||
"carries none either (the PWA is the admin surface now)"
|
||||
)
|
||||
coordinator._async_update_data = original_refresh
|
||||
await coordinator.async_refresh()
|
||||
|
||||
|
||||
async def test_payload_schema_matches_the_documented_contract(
|
||||
@@ -216,21 +310,16 @@ async def test_payload_schema_matches_the_documented_contract(
|
||||
) -> None:
|
||||
"""Every fired payload carries the documented fields with the
|
||||
documented types."""
|
||||
entry, (ada, _bo, _cory, _ghost) = await _fixture(hass, make_entry)
|
||||
instances = await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(
|
||||
ada.id, datetime.date.today().isoformat(), datetime.date.today().isoformat()
|
||||
)
|
||||
entry, client = await _fixture(hass, make_entry)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instances[0].id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": ada.id,
|
||||
},
|
||||
{"instance_id": 7, "actor": "panel", "actor_child_id": ADA},
|
||||
)
|
||||
client.published_frames.append(_completed_frame(7, ADA, "Ada", "morning"))
|
||||
from conftest import refire_api_transitions
|
||||
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
payload = hass.bus.fired(EVENT_QUEST_COMPLETED)[0]
|
||||
for key, check in (
|
||||
("child_id", lambda v: isinstance(v, int)),
|
||||
|
||||
+236
-658
File diff suppressed because it is too large
Load Diff
+45
-521
@@ -9,22 +9,10 @@ from conftest import make_config_entry, make_hass, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import DOMAIN, async_setup_entry, async_unload_entry
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
CONF_DAY_ROLLOVER_TIME,
|
||||
CONF_HORIZON_DAYS,
|
||||
CONF_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
SERVICE_REGENERATE,
|
||||
DOMAIN as DOMAIN_CONST,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
)
|
||||
|
||||
ADMIN_ID = "admin-1"
|
||||
ADMIN_CTX = {"user_id": ADMIN_ID}
|
||||
|
||||
|
||||
def _admin_data():
|
||||
return {CONF_ADMIN_USER_IDS: [ADMIN_ID]}
|
||||
|
||||
|
||||
def _wire(entry, registry):
|
||||
return wire_entry_to_registry(entry, registry)
|
||||
@@ -37,15 +25,25 @@ async def test_setup_stores_runtime_data_in_hass_data(hass, make_entry) -> None:
|
||||
assert hass.data[DOMAIN][entry.entry_id] is entry.runtime_data
|
||||
|
||||
|
||||
async def test_setup_runtime_data_has_entry_id_and_settings(hass, make_entry) -> None:
|
||||
entry = _wire(make_entry(options={"horizon_days": 7}), hass.registry)
|
||||
async def test_setup_runtime_data_has_entry_id_and_coordinator(hass, make_entry) -> None:
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
runtime = entry.runtime_data
|
||||
assert runtime.entry_id == entry.entry_id
|
||||
assert runtime.settings.horizon_days == 7
|
||||
assert runtime.coordinator is not None
|
||||
assert callable(runtime.remove_update_listener)
|
||||
|
||||
|
||||
async def test_setup_registers_no_time_change_listener(hass, make_entry) -> None:
|
||||
"""The integration owns no database any more: the daily
|
||||
day-rollover/materialization listener is gone (the API service
|
||||
owns the horizon), so setup registers NOTHING against the
|
||||
time-change listener bookkeeping."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
assert hass.time_change.size == 0
|
||||
|
||||
|
||||
async def test_unload_returns_true_and_removes_hass_data(hass, make_entry) -> None:
|
||||
registry = hass.registry
|
||||
entry = _wire(make_entry(), registry)
|
||||
@@ -120,7 +118,7 @@ async def test_options_update_triggers_reload_once(hass, make_entry) -> None:
|
||||
registry = hass.registry
|
||||
entry = _wire(make_entry(), registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
entry.options = {"horizon_days": 30}
|
||||
entry.options = {"update_interval": 60}
|
||||
await registry.async_dispatch_options_update(entry)
|
||||
assert hass.config_entries.async_reload.call_count == 1
|
||||
assert registry.reloaded == [entry.entry_id]
|
||||
@@ -198,6 +196,16 @@ async def test_setup_entry_uses_domain_constant(hass, make_entry) -> None:
|
||||
assert set(hass.data) == {DOMAIN_CONST}
|
||||
|
||||
|
||||
async def test_setup_registers_the_completion_service(hass, make_entry) -> None:
|
||||
"""The one domain-global service registers with setup and deregisters
|
||||
on the last unload."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_COMPLETE_QUEST)
|
||||
await async_unload_entry(hass, entry)
|
||||
assert not hass.services.has_service(DOMAIN, SERVICE_COMPLETE_QUEST)
|
||||
|
||||
|
||||
async def test_setup_awaitable_listener_removal_supported() -> None:
|
||||
"""A coroutine-returning remover is awaited during unload."""
|
||||
removed = []
|
||||
@@ -216,9 +224,9 @@ async def test_setup_awaitable_listener_removal_supported() -> None:
|
||||
assert entry.runtime_data is None
|
||||
|
||||
|
||||
async def test_setup_closes_database_when_listener_registration_fails() -> None:
|
||||
"""A listener-registration failure must not leak the opened database."""
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
async def test_setup_unwinds_when_listener_registration_fails() -> None:
|
||||
"""A listener-registration failure must not leak partial setup state."""
|
||||
from custom_components.nestquest.const import DOMAIN as DOMAIN_CONST
|
||||
|
||||
class _Boom(Exception):
|
||||
pass
|
||||
@@ -228,13 +236,16 @@ async def test_setup_closes_database_when_listener_registration_fails() -> None:
|
||||
hass, _registry = make_hass()
|
||||
with pytest.raises(_Boom):
|
||||
await async_setup_entry(hass, entry)
|
||||
assert hass.data.get(DOMAIN, {}) == {}
|
||||
assert hass.data.get(DOMAIN_CONST, {}) == {}
|
||||
assert not hasattr(entry, "runtime_data")
|
||||
assert not hass.services.has_service(DOMAIN_CONST, SERVICE_COMPLETE_QUEST)
|
||||
|
||||
|
||||
async def test_unload_closes_database_even_when_listener_removal_raises() -> None:
|
||||
"""Unload removes the listener, closes the DB in a finally, then raises."""
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
async def test_unload_shuts_coordinator_even_when_listener_removal_raises() -> None:
|
||||
"""A raising update-listener remover must not skip the coordinator
|
||||
shutdown: the retained error is re-raised only after the teardown
|
||||
ran and the runtime record was cleared."""
|
||||
from custom_components.nestquest.const import DOMAIN as DOMAIN_CONST
|
||||
|
||||
class _RemoveBoom(Exception):
|
||||
pass
|
||||
@@ -246,504 +257,17 @@ async def test_unload_closes_database_even_when_listener_removal_raises() -> Non
|
||||
entry.add_update_listener = lambda listener: _remover
|
||||
hass, _registry = make_hass()
|
||||
await async_setup_entry(hass, entry)
|
||||
database = entry.runtime_data.database
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
seen = []
|
||||
|
||||
async def _shutdown():
|
||||
seen.append("shutdown")
|
||||
|
||||
coordinator.async_shutdown = _shutdown
|
||||
|
||||
with pytest.raises(_RemoveBoom):
|
||||
await async_unload_entry(hass, entry)
|
||||
assert database.connected is False, "database leaked despite remover error"
|
||||
assert seen == ["shutdown"], "coordinator shutdown must have run"
|
||||
assert entry.runtime_data is None
|
||||
assert DOMAIN not in hass.data
|
||||
assert hass.time_change.size == 0, "time-change listener leaked"
|
||||
|
||||
|
||||
async def test_unload_cancels_time_listener_even_when_update_remover_raises() -> None:
|
||||
"""A raising update-listener remover must not skip the time-change cancel.
|
||||
|
||||
Both removers are independent: the update-listener remover raising must
|
||||
still cancel the daily time-change callback, whose action would otherwise
|
||||
fire after unload against a closed database.
|
||||
"""
|
||||
|
||||
class _RemoveBoom(Exception):
|
||||
pass
|
||||
|
||||
def _remover():
|
||||
raise _RemoveBoom()
|
||||
|
||||
entry = make_config_entry(entry_id="update-boom-time-cancel")
|
||||
entry.add_update_listener = lambda listener: _remover
|
||||
hass, _registry = make_hass()
|
||||
await async_setup_entry(hass, entry)
|
||||
assert hass.time_change.size == 1
|
||||
with pytest.raises(_RemoveBoom):
|
||||
await async_unload_entry(hass, entry)
|
||||
assert hass.time_change.size == 0, "time-change listener not cancelled"
|
||||
assert entry.runtime_data is None
|
||||
assert DOMAIN not in hass.data
|
||||
|
||||
|
||||
async def test_setup_registers_day_rollover_listener(hass, make_entry) -> None:
|
||||
"""Setup registers a daily rollover listener and stores its cancel fn."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert hass.time_change.size == 1
|
||||
registration = hass.time_change.registrations[0]
|
||||
assert registration["hour"] == 0
|
||||
assert registration["minute"] == 0
|
||||
assert callable(entry.runtime_data.remove_time_change_listener)
|
||||
|
||||
|
||||
async def test_setup_registers_day_rollover_at_configured_time(hass, make_entry) -> None:
|
||||
"""The listener fires at the entry option's rollover time, not the default."""
|
||||
entry = _wire(make_entry(options={CONF_DAY_ROLLOVER_TIME: "06:30"}), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
registration = hass.time_change.registrations[0]
|
||||
assert registration["hour"] == 6
|
||||
assert registration["minute"] == 30
|
||||
|
||||
|
||||
async def test_unload_cancels_day_rollover_listener(hass, make_entry) -> None:
|
||||
"""Unload removes the time-change listener alongside the update listener."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
assert hass.time_change.size == 1
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert DOMAIN_CONST not in hass.data
|
||||
assert hass.time_change.size == 0
|
||||
|
||||
|
||||
async def test_rollover_time_change_reregisters_listener_at_new_time(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A rollover-time options change re-registers the listener at the new time."""
|
||||
entry = _wire(
|
||||
make_entry(options={CONF_DAY_ROLLOVER_TIME: "00:00"}), hass.registry
|
||||
)
|
||||
await async_setup_entry(hass, entry)
|
||||
assert (hass.time_change.registrations[0]["hour"], hass.time_change.registrations[0]["minute"]) == (0, 0)
|
||||
|
||||
# The options flow writes the new rollover time, then HA reloads the
|
||||
# entry: unload tears down the old listener, setup re-registers it.
|
||||
entry.options = {CONF_DAY_ROLLOVER_TIME: "06:30"}
|
||||
await async_unload_entry(hass, entry)
|
||||
assert hass.time_change.size == 0
|
||||
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert hass.time_change.size == 1
|
||||
registration = hass.time_change.registrations[0]
|
||||
assert (registration["hour"], registration["minute"]) == (6, 30)
|
||||
|
||||
|
||||
async def test_day_rollover_listener_materializes_ha_local_horizon(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""Firing the listener materializes today..today+horizon in HA local time."""
|
||||
import datetime
|
||||
from unittest.mock import AsyncMock
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
database = entry.runtime_data.database
|
||||
|
||||
fake = AsyncMock()
|
||||
monkeypatch.setattr(nestquest, "_materialize_run", fake)
|
||||
|
||||
time_zone = ZoneInfo(hass.config.time_zone)
|
||||
today = datetime.datetime.now(time_zone).date()
|
||||
expected_start = today.isoformat()
|
||||
expected_end = (today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat()
|
||||
|
||||
await hass.time_change.fire()
|
||||
|
||||
fake.assert_awaited_once_with(
|
||||
database, expected_start, expected_end, today=today
|
||||
)
|
||||
|
||||
|
||||
async def test_day_rollover_uses_configured_horizon_days(hass, make_entry) -> None:
|
||||
"""The daily run materializes only the configured horizon window."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(make_entry(options={CONF_HORIZON_DAYS: 5}), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
|
||||
# A definition created AFTER setup has no instances yet (create does not
|
||||
# materialize); firing the daily listener must generate only the horizon.
|
||||
child_id = await _seed_daily_child_and_definition(
|
||||
database, _local_today(hass)
|
||||
)
|
||||
await hass.time_change.fire()
|
||||
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=5)).isoformat()
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id, today.isoformat(), end
|
||||
)
|
||||
assert len(records) == 6
|
||||
|
||||
beyond = (today + datetime.timedelta(days=6)).isoformat()
|
||||
beyond_end = (
|
||||
today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
assert await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id, beyond, beyond_end
|
||||
) == []
|
||||
|
||||
|
||||
def test_day_rollover_time_change_tracker_rejects_local_kwarg() -> None:
|
||||
"""The fake async_track_time_change mirrors HA 2024.6 (no ``local`` kwarg).
|
||||
|
||||
Setup drives the local-time wrapper directly, so passing ``local=`` must
|
||||
raise TypeError — otherwise a regression in the production call would be
|
||||
silently masked by the fake.
|
||||
"""
|
||||
import inspect as _inspect
|
||||
|
||||
from homeassistant.helpers.event import async_track_time_change
|
||||
|
||||
params = _inspect.signature(async_track_time_change).parameters
|
||||
assert list(params) == ["hass", "action", "hour", "minute", "second"]
|
||||
with pytest.raises(TypeError):
|
||||
async_track_time_change(None, lambda _now: None, hour=0, minute=0, local=True)
|
||||
|
||||
|
||||
async def test_setup_applies_all_v1_tables(hass, make_entry) -> None:
|
||||
"""Setup applies the full v1 DDL: all four v1 tables exist afterwards."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
rows = await database.fetch_all(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' "
|
||||
"AND name IN ('children', 'admin_users', 'schedule_rules', "
|
||||
"'quest_definitions') ORDER BY name"
|
||||
)
|
||||
assert [row[0] for row in rows] == [
|
||||
"admin_users",
|
||||
"children",
|
||||
"quest_definitions",
|
||||
"schedule_rules",
|
||||
]
|
||||
await async_unload_entry(hass, entry)
|
||||
|
||||
|
||||
async def _seed_daily_child_and_definition(database, today) -> int:
|
||||
"""Create one always-present child + a daily definition starting today.
|
||||
|
||||
Returns the child's id. No presence schedule means the child is present
|
||||
every day, so the daily rule yields exactly one instance per horizon day.
|
||||
"""
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import RuleType, ScheduleRule
|
||||
|
||||
NOW = "2026-09-14T12:00:00+00:00"
|
||||
child = await ChildrenDao(database).create("Ada", NOW)
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Daily chore",
|
||||
ScheduleRule(rule_type=RuleType.DAILY, start_date=today.isoformat()),
|
||||
[child.id],
|
||||
["morning"],
|
||||
)
|
||||
return child.id
|
||||
|
||||
|
||||
def _local_today(hass) -> "datetime.date":
|
||||
import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
return datetime.datetime.now(ZoneInfo(hass.config.time_zone)).date()
|
||||
|
||||
|
||||
async def test_setup_backfills_instances_over_horizon(hass, make_entry) -> None:
|
||||
"""Setup materializes once so a restart backfills any missed days."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.store import async_get_db_path
|
||||
|
||||
# Seed the database BEFORE setup: a restart reopens an existing file that
|
||||
# already holds definitions. The startup backfill must pick them up.
|
||||
db_path = await async_get_db_path(hass)
|
||||
pre = NestQuestDatabase(hass.async_add_executor_job)
|
||||
await pre.open(db_path)
|
||||
await apply_migrations(pre)
|
||||
child_id = await _seed_daily_child_and_definition(pre, _local_today(hass))
|
||||
await pre.close()
|
||||
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat()
|
||||
records = await QuestInstancesDao(entry.runtime_data.database).list_by_date_range(
|
||||
child_id, today.isoformat(), end
|
||||
)
|
||||
assert len(records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
async def test_setup_backfills_configured_horizon_days(hass, make_entry) -> None:
|
||||
"""Setup backfills only the configured (non-default) horizon window."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.store import async_get_db_path
|
||||
|
||||
db_path = await async_get_db_path(hass)
|
||||
pre = NestQuestDatabase(hass.async_add_executor_job)
|
||||
await pre.open(db_path)
|
||||
await apply_migrations(pre)
|
||||
child_id = await _seed_daily_child_and_definition(pre, _local_today(hass))
|
||||
await pre.close()
|
||||
|
||||
entry = _wire(
|
||||
make_entry(options={CONF_HORIZON_DAYS: 5}), hass.registry
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=5)).isoformat()
|
||||
records = await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(child_id, today.isoformat(), end)
|
||||
assert len(records) == 6
|
||||
|
||||
beyond = (today + datetime.timedelta(days=6)).isoformat()
|
||||
beyond_end = (
|
||||
today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
assert await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(child_id, beyond, beyond_end) == []
|
||||
|
||||
|
||||
async def test_setup_succeeds_with_fully_malformed_options(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A fully malformed options dict falls back per field and setup succeeds.
|
||||
|
||||
``horizon_days=True``, ``day_rollover_time='99:99'`` and
|
||||
``morning_summary_time='25:00'`` are all invalid; the integration's
|
||||
``from_options_resilient`` falls each back to its default, so setup
|
||||
SUCCEEDS, the day-rollover listener registers at the default hour 0
|
||||
minute 0, and the startup backfill materializes the default horizon
|
||||
window.
|
||||
"""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.store import async_get_db_path
|
||||
|
||||
db_path = await async_get_db_path(hass)
|
||||
pre = NestQuestDatabase(hass.async_add_executor_job)
|
||||
await pre.open(db_path)
|
||||
await apply_migrations(pre)
|
||||
child_id = await _seed_daily_child_and_definition(pre, _local_today(hass))
|
||||
await pre.close()
|
||||
|
||||
entry = _wire(
|
||||
make_entry(
|
||||
options={
|
||||
CONF_HORIZON_DAYS: True,
|
||||
CONF_DAY_ROLLOVER_TIME: "99:99",
|
||||
CONF_MORNING_SUMMARY_TIME: "25:00",
|
||||
}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
# The day-rollover listener fell back to the default 00:00.
|
||||
registration = hass.time_change.registrations[0]
|
||||
assert registration["hour"] == 0
|
||||
assert registration["minute"] == 0
|
||||
|
||||
# The startup backfill used the default horizon window.
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat()
|
||||
records = await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(child_id, today.isoformat(), end)
|
||||
assert len(records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
async def test_setup_keeps_horizon_when_sibling_option_is_bad(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A malformed sibling option does not reset the configured horizon.
|
||||
|
||||
``horizon_days=5`` is valid while ``morning_summary_time='25:00'`` is
|
||||
invalid; ``from_options_resilient`` falls back ONLY the bad sibling,
|
||||
so the entry's resolved settings keep ``horizon_days == 5``.
|
||||
"""
|
||||
entry = _wire(
|
||||
make_entry(
|
||||
options={
|
||||
CONF_HORIZON_DAYS: 5,
|
||||
CONF_MORNING_SUMMARY_TIME: "25:00",
|
||||
}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert entry.runtime_data.settings.horizon_days == 5
|
||||
|
||||
|
||||
async def test_regenerate_service_registered_and_materializes(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""``nestquest.regenerate`` is registered and calling it regenerates."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(make_entry(data=_admin_data()), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
# A definition created AFTER setup has no instances yet (create does not
|
||||
# materialize); the service must generate them on demand.
|
||||
database = entry.runtime_data.database
|
||||
child_id = await _seed_daily_child_and_definition(database, _local_today(hass))
|
||||
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat()
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id, today.isoformat(), end
|
||||
)
|
||||
assert len(records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
async def test_regenerate_service_uses_configured_horizon_days(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""``nestquest.regenerate`` regenerates only the configured horizon."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(
|
||||
make_entry(options={CONF_HORIZON_DAYS: 5}, data=_admin_data()),
|
||||
hass.registry,
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
|
||||
database = entry.runtime_data.database
|
||||
child_id = await _seed_daily_child_and_definition(database, _local_today(hass))
|
||||
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=5)).isoformat()
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id, today.isoformat(), end
|
||||
)
|
||||
assert len(records) == 6
|
||||
|
||||
beyond = (today + datetime.timedelta(days=6)).isoformat()
|
||||
beyond_end = (
|
||||
today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
assert await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id, beyond, beyond_end
|
||||
) == []
|
||||
|
||||
|
||||
async def test_unload_deregisters_regenerate_service(hass, make_entry) -> None:
|
||||
"""Unload removes the ``regenerate`` service so no stale entry leaks."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert not hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
|
||||
async def test_regenerate_service_is_domain_scoped_across_entries(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The ``regenerate`` service is domain-global, not per-entry.
|
||||
|
||||
With two loaded entries the service must be registered and functional;
|
||||
unloading one entry must keep it registered and functional for the
|
||||
remaining entry; unloading the final entry must remove it.
|
||||
"""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry_a = _wire(
|
||||
make_entry(entry_id="entry_a", data=_admin_data()), hass.registry
|
||||
)
|
||||
entry_b = _wire(
|
||||
make_entry(entry_id="entry_b", data=_admin_data()), hass.registry
|
||||
)
|
||||
|
||||
assert await async_setup_entry(hass, entry_a) is True
|
||||
assert await async_setup_entry(hass, entry_b) is True
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
# The domain-global handler resolves a live database from any entry.
|
||||
database_b = entry_b.runtime_data.database
|
||||
child_id = await _seed_daily_child_and_definition(
|
||||
database_b, _local_today(hass)
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
today = _local_today(hass)
|
||||
end = (today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat()
|
||||
records = await QuestInstancesDao(database_b).list_by_date_range(
|
||||
child_id, today.isoformat(), end
|
||||
)
|
||||
assert len(records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
# Unloading one entry must not tear down the shared service.
|
||||
assert await async_unload_entry(hass, entry_a) is True
|
||||
assert hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
# It still works for the remaining entry.
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
|
||||
# Unloading the final entry removes the domain-global service.
|
||||
assert await async_unload_entry(hass, entry_b) is True
|
||||
assert not hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
|
||||
|
||||
async def test_setup_cleans_listeners_when_materialization_raises(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""A startup-materialization failure rolls back every registered listener.
|
||||
|
||||
The daily and update listeners are installed before the startup
|
||||
materialization runs; when that walk raises, the database is closed but
|
||||
the remover callables must also be invoked so no listener survives
|
||||
firing against a closed database.
|
||||
"""
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
async def _boom(*_args, **_kwargs):
|
||||
raise RuntimeError("materialization failed")
|
||||
|
||||
monkeypatch.setattr(nestquest, "_materialize_run", _boom)
|
||||
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
with pytest.raises(RuntimeError, match="materialization failed"):
|
||||
await async_setup_entry(hass, entry)
|
||||
|
||||
assert hass.time_change.size == 0
|
||||
assert hass.registry.size == 0
|
||||
assert not hass.services.has_service(DOMAIN, SERVICE_REGENERATE)
|
||||
assert not hasattr(entry, "runtime_data")
|
||||
+16
-16
@@ -6,29 +6,29 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_presence import PresenceSchedulesDao
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_presence import PresenceSchedulesDao
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
QuestDefinitionsDao,
|
||||
schedule_rule_to_storage,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.materialize import (
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.materialize import (
|
||||
materialize,
|
||||
regenerate_for_child,
|
||||
regenerate_for_definition,
|
||||
)
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
create_quest_definition,
|
||||
edit_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
ScheduleRule,
|
||||
occurs_on,
|
||||
@@ -505,7 +505,7 @@ def test_materialize_skips_deactivated_child_mid_walk(tmp_path) -> None:
|
||||
|
||||
def test_materialize_uses_single_presence_snapshot_mid_walk(tmp_path) -> None:
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
|
||||
@@ -628,7 +628,7 @@ def test_materialize_does_not_overwrite_regenerated_due_time(tmp_path) -> None:
|
||||
|
||||
def test_materialize_honours_overrides(tmp_path) -> None:
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
|
||||
@@ -758,7 +758,7 @@ def test_materialize_clamps_past_start_to_today(tmp_path) -> None:
|
||||
|
||||
def test_materialize_skips_inactive_definitions(tmp_path) -> None:
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
set_quest_definition_active,
|
||||
)
|
||||
|
||||
@@ -906,7 +906,7 @@ def test_regenerate_for_child_rebuilds_horizon_preserves_history(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
|
||||
@@ -1091,7 +1091,7 @@ def test_regenerate_for_child_uses_single_anchor_across_midnight(
|
||||
def test_regenerate_for_child_is_child_scoped(tmp_path) -> None:
|
||||
"""Regenerating one child must never touch another child's rows."""
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
|
||||
@@ -1493,10 +1493,10 @@ def test_materialize_end_to_end_six_rule_types(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr(materialize_module, "_now_stamp", _distinct_stamp)
|
||||
|
||||
async def _body(database):
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
from custom_components.nestquest.core.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
from custom_components.nestquest.presence import PresenceSchedule
|
||||
from custom_components.nestquest.core.presence import PresenceSchedule
|
||||
|
||||
children = ChildrenDao(database)
|
||||
schedules = PresenceSchedulesDao(database)
|
||||
|
||||
+4
-134
@@ -9,16 +9,16 @@ from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.schema import SCHEMA_V7_META_STATE_DDL
|
||||
from custom_components.nestquest.migrations import (
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.schema import SCHEMA_V7_META_STATE_DDL
|
||||
from custom_components.nestquest.core.migrations import (
|
||||
MIGRATIONS,
|
||||
VERSION_TABLE,
|
||||
VERSION_TABLE_DDL,
|
||||
apply_migrations,
|
||||
read_schema_version,
|
||||
)
|
||||
from custom_components.nestquest.schema import (
|
||||
from custom_components.nestquest.core.schema import (
|
||||
SCHEMA_V1_STATEMENTS,
|
||||
SCHEMA_V1_QUEST_DEFINITION_WINDOWS_DDL,
|
||||
)
|
||||
@@ -1064,133 +1064,3 @@ def test_partial_pending_migrations_resume_from_current_version(
|
||||
assert "step_b" in _tables(database)
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Startup wiring: setup runs the migration runner, not raw DDL
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _setup_entry(hass, entry, registry) -> object:
|
||||
from tests.test_lifecycle import _wire # reuse the established wiring
|
||||
|
||||
entry = _wire(entry, registry)
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
|
||||
await async_setup_entry(hass, entry)
|
||||
return entry
|
||||
|
||||
|
||||
async def test_setup_entry_migrates_fresh_database(hass, make_entry) -> None:
|
||||
import sqlite3 as sqlite3_mod
|
||||
|
||||
from custom_components.nestquest.migrations import read_schema_version
|
||||
from custom_components.nestquest.store import async_get_db_path
|
||||
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database = entry.runtime_data.database
|
||||
assert await read_schema_version(database) == len(MIGRATIONS)
|
||||
# The v1 tables exist because the runner applied migration 1.
|
||||
names = {
|
||||
row[0]
|
||||
for row in await database.fetch_all(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' "
|
||||
"AND name NOT LIKE 'sqlite_%'"
|
||||
)
|
||||
}
|
||||
assert "children" in names and "completion_events" in names
|
||||
# The version table exists with its singleton row stamped.
|
||||
columns = await database.fetch_all(f"PRAGMA table_info({VERSION_TABLE})")
|
||||
assert [(row[1], row[3]) for row in columns] == [("id", 1), ("version", 1)]
|
||||
db_path = await async_get_db_path(hass)
|
||||
conn = sqlite3_mod.connect(db_path)
|
||||
try:
|
||||
conn.execute(f"INSERT INTO {VERSION_TABLE} (id, version) VALUES (2, 1)")
|
||||
violated = False
|
||||
except sqlite3_mod.IntegrityError:
|
||||
violated = True
|
||||
finally:
|
||||
conn.close()
|
||||
assert violated, "singleton-row CHECK must be live in the setup-created DB"
|
||||
await database.close()
|
||||
|
||||
|
||||
async def test_options_reload_reopens_and_rechecks_version(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A listener-triggered reload re-runs setup against the same file.
|
||||
|
||||
Unload then setup is the reload lifecycle: the old connection is
|
||||
closed, apply_migrations runs again on the persisted file, keeps
|
||||
version and rows intact, and the reopened connection is live.
|
||||
"""
|
||||
from custom_components.nestquest import async_unload_entry
|
||||
from custom_components.nestquest.migrations import read_schema_version
|
||||
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database_a = entry.runtime_data.database
|
||||
await database_a.execute(
|
||||
"INSERT INTO children (display_name, created_at) VALUES (?, ?)",
|
||||
("Ada", "2026-09-13T00:00:00+00:00"),
|
||||
)
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert not database_a.connected
|
||||
|
||||
entry_reloaded = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database_b = entry_reloaded.runtime_data.database
|
||||
assert database_b is not database_a
|
||||
try:
|
||||
assert await read_schema_version(database_b) == len(MIGRATIONS)
|
||||
row = await database_b.fetch_one("SELECT COUNT(*) FROM children")
|
||||
assert row == (1,)
|
||||
finally:
|
||||
await database_b.close()
|
||||
|
||||
|
||||
async def test_setup_entry_failure_closes_database(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""A failing migration closes the opened connection before re-raising.
|
||||
|
||||
A migration failure surfaces as ConfigEntryNotReady (HA retries
|
||||
setup) with the original error preserved as __cause__. Spies on
|
||||
the real wrapper instance: records whether close() ran, rather
|
||||
than inferring from hass.data (a failed setup never stores a
|
||||
runtime record).
|
||||
"""
|
||||
import pytest as pytest_module
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
|
||||
import custom_components.nestquest as nestquest_module
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import (
|
||||
MIGRATIONS as _MIGRATIONS,
|
||||
)
|
||||
|
||||
async def _failing(database, migrations=_MIGRATIONS):
|
||||
raise RuntimeError("boom")
|
||||
|
||||
monkeypatch.setattr(
|
||||
nestquest_module, "apply_migrations", _failing, raising=True
|
||||
)
|
||||
|
||||
close_calls: list[bool] = []
|
||||
original_close = NestQuestDatabase.close
|
||||
|
||||
async def _spy_close(self):
|
||||
close_calls.append(True)
|
||||
return await original_close(self)
|
||||
|
||||
monkeypatch.setattr(NestQuestDatabase, "close", _spy_close)
|
||||
|
||||
entry = make_entry()
|
||||
with pytest_module.raises(ConfigEntryNotReady) as excinfo:
|
||||
await _setup_entry(hass, entry, hass.registry)
|
||||
assert isinstance(excinfo.value.__cause__, RuntimeError)
|
||||
assert "boom" in str(excinfo.value.__cause__)
|
||||
|
||||
assert close_calls == [True], (
|
||||
"failed setup must close the connection it opened"
|
||||
)
|
||||
record = hass.data["nestquest"].get(entry.entry_id)
|
||||
assert record is None, "failed setup must not store runtime data"
|
||||
+212
-452
@@ -14,27 +14,16 @@ from conftest import make_config_entry, make_hass, options_flow_base as _options
|
||||
from custom_components.nestquest import config_flow
|
||||
from custom_components.nestquest import options_flow
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
CONF_DAY_ROLLOVER_TIME,
|
||||
CONF_HORIZON_DAYS,
|
||||
CONF_API_BASE_URL,
|
||||
CONF_PANEL_IDLE_TIMEOUT,
|
||||
CONF_PANEL_TOKEN,
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
CONF_AFTERNOON_REMINDER_ENABLED,
|
||||
CONF_AFTERNOON_REMINDER_TIME,
|
||||
CONF_CELEBRATION_ENABLED,
|
||||
CONF_END_OF_DAY_REPORT_ENABLED,
|
||||
CONF_END_OF_DAY_REPORT_TIME,
|
||||
CONF_MORNING_SUMMARY_ENABLED,
|
||||
CONF_MORNING_SUMMARY_TIME,
|
||||
CONF_NOTIFY_TARGET,
|
||||
DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
DEFAULT_AUTOMATION_ENABLED,
|
||||
DEFAULT_END_OF_DAY_REPORT_TIME,
|
||||
DEFAULT_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DEFAULT_DAY_ROLLOVER_TIME,
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_PANEL_IDLE_TIMEOUT,
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
)
|
||||
|
||||
@@ -43,25 +32,19 @@ STRINGS_PATH = PKG_DIR / "strings.json"
|
||||
TRANSLATIONS_EN_PATH = PKG_DIR / "translations" / "en.json"
|
||||
|
||||
VALID_INPUT = {
|
||||
CONF_HORIZON_DAYS: 7,
|
||||
CONF_DAY_ROLLOVER_TIME: "03:30",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 60,
|
||||
}
|
||||
|
||||
#: What a schema-validated submit produces from a bare VALID_INPUT on a
|
||||
#: fresh entry: the Feature 10 refresh interval and the Feature 11
|
||||
#: notification section fill from their defaults.
|
||||
#: fresh entry: the Feature 10 refresh interval, the Feature 18
|
||||
#: staleness threshold, and the Feature 18 API connection fill from
|
||||
#: their defaults.
|
||||
FULL_INPUT = {
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: DEFAULT_UPDATE_INTERVAL,
|
||||
CONF_NOTIFY_TARGET: "",
|
||||
CONF_MORNING_SUMMARY_TIME: DEFAULT_MORNING_SUMMARY_TIME,
|
||||
CONF_AFTERNOON_REMINDER_TIME: DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
CONF_END_OF_DAY_REPORT_TIME: DEFAULT_END_OF_DAY_REPORT_TIME,
|
||||
CONF_MORNING_SUMMARY_ENABLED: DEFAULT_AUTOMATION_ENABLED,
|
||||
CONF_AFTERNOON_REMINDER_ENABLED: DEFAULT_AUTOMATION_ENABLED,
|
||||
CONF_END_OF_DAY_REPORT_ENABLED: DEFAULT_AUTOMATION_ENABLED,
|
||||
CONF_CELEBRATION_ENABLED: DEFAULT_AUTOMATION_ENABLED,
|
||||
CONF_SNAPSHOT_STALENESS: DEFAULT_SNAPSHOT_STALENESS,
|
||||
CONF_API_BASE_URL: DEFAULT_API_BASE_URL,
|
||||
CONF_PANEL_TOKEN: DEFAULT_PANEL_TOKEN,
|
||||
}
|
||||
|
||||
|
||||
@@ -77,48 +60,13 @@ def _make_entry(entry_id: str = "test_entry", options: dict | None = None, data:
|
||||
return make_config_entry(entry_id=entry_id, options=options, data=data)
|
||||
|
||||
|
||||
def _make_flow(entry, *, users=None, database=None) -> options_flow.NestQuestOptionsFlow:
|
||||
"""Create an options flow instance bound to a stubbed config entry.
|
||||
|
||||
``users`` populates a stubbed hass.auth for the admin picker;
|
||||
``database`` wires the runtime record so the flow can read and
|
||||
write the allowlist like real HA's options flow does.
|
||||
"""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
def _make_flow(entry) -> options_flow.NestQuestOptionsFlow:
|
||||
"""Create an options flow instance bound to a stubbed config entry."""
|
||||
flow = options_flow.NestQuestOptionsFlow(config_entry=entry)
|
||||
flow.hass = SimpleNamespace()
|
||||
flow.hass.auth = SimpleNamespace(
|
||||
async_get_users=AsyncMock(return_value=users or [])
|
||||
)
|
||||
if database is not None:
|
||||
from custom_components.nestquest.const import DOMAIN
|
||||
|
||||
flow.hass.data = {
|
||||
DOMAIN: {entry.entry_id: SimpleNamespace(database=database)}
|
||||
}
|
||||
return flow
|
||||
|
||||
|
||||
def _user(user_id: str, name: str):
|
||||
return SimpleNamespace(id=user_id, name=name)
|
||||
|
||||
|
||||
def _open_allowlist_db(tmp_path, name):
|
||||
"""A real migrated temp database for the flow to read and write."""
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
|
||||
hass = MagicMock()
|
||||
hass.async_add_executor_job = AsyncMock(side_effect=(lambda fn, *a: fn(*a)))
|
||||
database = NestQuestDatabase(hass.async_add_executor_job)
|
||||
_run(database.open(tmp_path / name))
|
||||
_run(apply_migrations(database))
|
||||
return database
|
||||
|
||||
|
||||
def _schema_values(schema) -> dict:
|
||||
"""Extract the per-field default values from a real voluptuous schema."""
|
||||
return {
|
||||
@@ -145,11 +93,11 @@ def test_options_flow_get_options_flow_is_ha_callback() -> None:
|
||||
|
||||
def test_options_flow_constructs_through_2024_6_surface() -> None:
|
||||
"""The handler constructs against the mocked 2024.6 base and inherits its contract."""
|
||||
entry = _make_entry(options={CONF_HORIZON_DAYS: 21})
|
||||
entry = _make_entry(options={CONF_UPDATE_INTERVAL: 90})
|
||||
flow = options_flow.NestQuestOptionsFlow(config_entry=entry)
|
||||
assert isinstance(flow, _options_flow_base())
|
||||
assert flow.config_entry is entry
|
||||
assert flow.options == {CONF_HORIZON_DAYS: 21}
|
||||
assert flow.options == {CONF_UPDATE_INTERVAL: 90}
|
||||
|
||||
|
||||
def test_options_flow_submits_through_2024_6_surface() -> None:
|
||||
@@ -184,82 +132,66 @@ def test_options_flow_prefills_from_defaults() -> None:
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(flow.async_step_init(None))
|
||||
values = _schema_values(result["data_schema"])
|
||||
assert values[CONF_HORIZON_DAYS] == DEFAULT_HORIZON_DAYS
|
||||
assert values[CONF_DAY_ROLLOVER_TIME] == DEFAULT_DAY_ROLLOVER_TIME
|
||||
assert values[CONF_PANEL_IDLE_TIMEOUT] == DEFAULT_PANEL_IDLE_TIMEOUT
|
||||
assert values[CONF_UPDATE_INTERVAL] == DEFAULT_UPDATE_INTERVAL
|
||||
assert values[CONF_SNAPSHOT_STALENESS] == DEFAULT_SNAPSHOT_STALENESS
|
||||
|
||||
|
||||
def test_options_flow_prefills_from_entry_options() -> None:
|
||||
"""Stored entry options win over entry data and defaults."""
|
||||
entry = _make_entry(
|
||||
options={
|
||||
CONF_HORIZON_DAYS: 21,
|
||||
CONF_DAY_ROLLOVER_TIME: "05:45",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 120,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_SNAPSHOT_STALENESS: 450,
|
||||
},
|
||||
data={
|
||||
CONF_HORIZON_DAYS: 99,
|
||||
CONF_DAY_ROLLOVER_TIME: "23:59",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 999,
|
||||
CONF_UPDATE_INTERVAL: 999,
|
||||
CONF_SNAPSHOT_STALENESS: 999,
|
||||
},
|
||||
)
|
||||
result = _run(_make_flow(entry).async_step_init(None))
|
||||
values = _schema_values(result["data_schema"])
|
||||
assert values[CONF_HORIZON_DAYS] == 21
|
||||
assert values[CONF_DAY_ROLLOVER_TIME] == "05:45"
|
||||
assert values[CONF_PANEL_IDLE_TIMEOUT] == 120
|
||||
assert values[CONF_UPDATE_INTERVAL] == 90
|
||||
assert values[CONF_SNAPSHOT_STALENESS] == 450
|
||||
|
||||
|
||||
def test_options_flow_falls_back_to_entry_data() -> None:
|
||||
"""Pre-upgrade entries without options fall back to entry.data."""
|
||||
entry = _make_entry(
|
||||
data={
|
||||
CONF_HORIZON_DAYS: 10,
|
||||
CONF_DAY_ROLLOVER_TIME: "01:15",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 90,
|
||||
CONF_UPDATE_INTERVAL: 60,
|
||||
CONF_SNAPSHOT_STALENESS: 240,
|
||||
}
|
||||
)
|
||||
result = _run(_make_flow(entry).async_step_init(None))
|
||||
values = _schema_values(result["data_schema"])
|
||||
assert values[CONF_HORIZON_DAYS] == 10
|
||||
assert values[CONF_DAY_ROLLOVER_TIME] == "01:15"
|
||||
assert values[CONF_PANEL_IDLE_TIMEOUT] == 90
|
||||
assert values[CONF_UPDATE_INTERVAL] == 60
|
||||
assert values[CONF_SNAPSHOT_STALENESS] == 240
|
||||
|
||||
|
||||
def test_options_flow_schema_applies_stored_defaults() -> None:
|
||||
"""A real voluptuous validate({}) fills every field from the stored defaults.
|
||||
|
||||
Without a runtime database (and no auth in the bare harness), the
|
||||
admin picker's default is the empty selection and its choice set is
|
||||
empty — the three legacy settings are unaffected.
|
||||
"""
|
||||
"""A real voluptuous validate({}) fills every field from the stored defaults."""
|
||||
entry = _make_entry(
|
||||
options={
|
||||
CONF_HORIZON_DAYS: 21,
|
||||
CONF_DAY_ROLLOVER_TIME: "05:45",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 120,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_NOTIFY_TARGET: "notify.mobile_app_test",
|
||||
CONF_MORNING_SUMMARY_TIME: "07:00",
|
||||
CONF_AFTERNOON_REMINDER_TIME: "14:00",
|
||||
CONF_END_OF_DAY_REPORT_TIME: "21:30",
|
||||
CONF_SNAPSHOT_STALENESS: 450,
|
||||
CONF_API_BASE_URL: "http://panel.lan:8443",
|
||||
CONF_PANEL_TOKEN: "stored-token",
|
||||
}
|
||||
)
|
||||
result = _run(_make_flow(entry).async_step_init(None))
|
||||
assert result["data_schema"]({}) == {
|
||||
CONF_HORIZON_DAYS: 21,
|
||||
CONF_DAY_ROLLOVER_TIME: "05:45",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 120,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_NOTIFY_TARGET: "notify.mobile_app_test",
|
||||
CONF_MORNING_SUMMARY_TIME: "07:00",
|
||||
CONF_AFTERNOON_REMINDER_TIME: "14:00",
|
||||
CONF_END_OF_DAY_REPORT_TIME: "21:30",
|
||||
CONF_MORNING_SUMMARY_ENABLED: True,
|
||||
CONF_AFTERNOON_REMINDER_ENABLED: True,
|
||||
CONF_END_OF_DAY_REPORT_ENABLED: True,
|
||||
CONF_CELEBRATION_ENABLED: True,
|
||||
CONF_ADMIN_USER_IDS: [],
|
||||
CONF_SNAPSHOT_STALENESS: 450,
|
||||
CONF_API_BASE_URL: "http://panel.lan:8443",
|
||||
CONF_PANEL_TOKEN: "stored-token",
|
||||
}
|
||||
|
||||
|
||||
@@ -269,50 +201,12 @@ def test_options_flow_schema_coerces_field_types() -> None:
|
||||
result = _run(flow.async_step_init(None))
|
||||
schema = result["data_schema"]
|
||||
validators = {marker.schema: validator for marker, validator in schema.schema.items()}
|
||||
assert validators[CONF_HORIZON_DAYS] is int
|
||||
assert validators[CONF_DAY_ROLLOVER_TIME] is str
|
||||
assert validators[CONF_PANEL_IDLE_TIMEOUT] is int
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_horizon", [0, -5])
|
||||
def test_options_flow_rejects_non_positive_horizon(bad_horizon: int) -> None:
|
||||
"""Zero or negative horizon values yield a field-level error, no exception."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_HORIZON_DAYS: bad_horizon})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_HORIZON_DAYS: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_rejects_malformed_time_not_a_time() -> None:
|
||||
"""Non-HH:MM strings are rejected with invalid_time."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_DAY_ROLLOVER_TIME: "noon"})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_DAY_ROLLOVER_TIME: "invalid_time"}
|
||||
|
||||
|
||||
def test_options_flow_rejects_malformed_time_out_of_range() -> None:
|
||||
"""Out-of-range HH:MM values are rejected with invalid_time."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_DAY_ROLLOVER_TIME: "25:99"})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_DAY_ROLLOVER_TIME: "invalid_time"}
|
||||
|
||||
|
||||
def test_options_flow_rejects_pasted_unicode_superscript_time() -> None:
|
||||
"""Pasted Unicode digits like '²²:²²' yield a field-level error, no exception."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_DAY_ROLLOVER_TIME: "²²:²²"})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_DAY_ROLLOVER_TIME: "invalid_time"}
|
||||
assert validators[CONF_UPDATE_INTERVAL] is int
|
||||
assert validators[CONF_SNAPSHOT_STALENESS] is int
|
||||
# The Feature 18 API connection fields are free-text strings.
|
||||
assert validators[CONF_API_BASE_URL] is str
|
||||
assert validators[CONF_PANEL_TOKEN] is str
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad_timeout", ["abc", 0, -10, 10])
|
||||
@@ -326,8 +220,21 @@ def test_options_flow_rejects_invalid_idle_timeout(bad_timeout) -> None:
|
||||
assert result["errors"] == {CONF_PANEL_IDLE_TIMEOUT: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_creates_entry_with_four_keys() -> None:
|
||||
"""A valid submit creates an entry with exactly the four validated keys."""
|
||||
@pytest.mark.parametrize("bad_interval", ["abc", True, 0, -10, 29])
|
||||
def test_options_flow_rejects_invalid_update_interval(bad_interval) -> None:
|
||||
"""Non-numeric, boolean, and below-floor update intervals reject."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_UPDATE_INTERVAL: bad_interval})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_UPDATE_INTERVAL: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_creates_entry_with_validated_keys() -> None:
|
||||
"""A valid submit creates an entry with exactly the validated keys
|
||||
(the client-facing settings, filled from defaults where the raw
|
||||
submit omitted them)."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
@@ -342,7 +249,7 @@ def test_options_flow_create_entry_data_lands_in_entry_options_and_reloads_once(
|
||||
entry = _make_entry()
|
||||
entry.add_update_listener = lambda listener: registry.add(entry.entry_id, listener)
|
||||
|
||||
# Simulate setup registering the merged lifecycle update listener.
|
||||
# Simulate setup registering the lifecycle update listener.
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
|
||||
_run(async_setup_entry(hass, entry))
|
||||
@@ -361,14 +268,13 @@ def test_options_flow_create_entry_data_lands_in_entry_options_and_reloads_once(
|
||||
|
||||
def test_options_flow_validation_never_raises() -> None:
|
||||
"""Validation returns errors instead of raising for arbitrary junk input."""
|
||||
junk = {CONF_HORIZON_DAYS: None, CONF_DAY_ROLLOVER_TIME: None, CONF_PANEL_IDLE_TIMEOUT: None}
|
||||
junk = {CONF_PANEL_IDLE_TIMEOUT: None, CONF_UPDATE_INTERVAL: "abc"}
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(flow.async_step_init(junk))
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {
|
||||
CONF_HORIZON_DAYS: "invalid",
|
||||
CONF_DAY_ROLLOVER_TIME: "invalid_time",
|
||||
CONF_PANEL_IDLE_TIMEOUT: "invalid",
|
||||
CONF_UPDATE_INTERVAL: "invalid",
|
||||
}
|
||||
|
||||
|
||||
@@ -398,10 +304,10 @@ def test_options_strings_present_and_matching(strings: dict, translations_en: di
|
||||
assert init["title"]
|
||||
assert init["description"]
|
||||
data = init["data"]
|
||||
for key in (CONF_HORIZON_DAYS, CONF_DAY_ROLLOVER_TIME, CONF_PANEL_IDLE_TIMEOUT):
|
||||
for key in (CONF_PANEL_IDLE_TIMEOUT,):
|
||||
assert data.get(key), f"Missing field name for '{key}'"
|
||||
errors = options["errors"]
|
||||
for key in ("invalid", "invalid_time"):
|
||||
for key in ("invalid",):
|
||||
assert errors.get(key), f"Missing error string for '{key}'"
|
||||
|
||||
|
||||
@@ -457,345 +363,199 @@ def test_options_flow_no_hardcoded_domain_or_db_filename() -> None:
|
||||
f"Hard-coded database filename in {py_file.name}:{node.lineno}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Admin allowlist picker (Feature 03)
|
||||
# Panel-plane API connection section (Feature 18)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_options_flow_picker_lists_existing_users(tmp_path) -> None:
|
||||
"""The picker offers EXISTING HA users (id -> name), never free text."""
|
||||
import voluptuous as vol
|
||||
|
||||
database = _open_allowlist_db(tmp_path, "picker-users.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import set_admin_ids
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua"), _user("u2", "Sam")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(flow.async_step_init(None))
|
||||
schema = result["data_schema"]
|
||||
marker = next(
|
||||
m for m in schema.schema
|
||||
if getattr(m, "schema", None) == CONF_ADMIN_USER_IDS
|
||||
)
|
||||
# Default is the CURRENT database allowlist.
|
||||
values = _schema_values(schema)
|
||||
assert values[CONF_ADMIN_USER_IDS] == ["u1"]
|
||||
# Both users are selectable; an unknown id is rejected by the
|
||||
# schema itself (this is what real HA submits go through).
|
||||
validated = schema(
|
||||
{
|
||||
CONF_HORIZON_DAYS: 7,
|
||||
CONF_DAY_ROLLOVER_TIME: "03:30",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 60,
|
||||
CONF_ADMIN_USER_IDS: ["u1", "u2"],
|
||||
}
|
||||
)
|
||||
assert validated[CONF_ADMIN_USER_IDS] == ["u1", "u2"]
|
||||
with pytest.raises(vol.Invalid):
|
||||
schema(
|
||||
{
|
||||
CONF_HORIZON_DAYS: 7,
|
||||
CONF_DAY_ROLLOVER_TIME: "03:30",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 60,
|
||||
CONF_ADMIN_USER_IDS: ["impostor"],
|
||||
}
|
||||
)
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_submit_applies_selection_to_database(tmp_path) -> None:
|
||||
database = _open_allowlist_db(tmp_path, "picker-apply.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua"), _user("u2", "Sam")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_ADMIN_USER_IDS: ["u2"]})
|
||||
)
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_ADMIN_USER_IDS] == ["u2"]
|
||||
# The allowlist (and the entry's recovery copy) carry the pick.
|
||||
assert await_gather(list_admin_ids(database)) == ["u2"]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def await_gather(coro):
|
||||
return _run(coro)
|
||||
|
||||
|
||||
def test_options_flow_empty_selection_refused(tmp_path) -> None:
|
||||
"""Saving zero admins is refused: an empty allowlist fails closed."""
|
||||
database = _open_allowlist_db(tmp_path, "picker-empty.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_ADMIN_USER_IDS: []})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_ADMIN_USER_IDS: "no_admins"}
|
||||
assert await_gather(list_admin_ids(database)) == ["u1"]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_unknown_selection_refused(tmp_path) -> None:
|
||||
database = _open_allowlist_db(tmp_path, "picker-unknown.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{**VALID_INPUT, CONF_ADMIN_USER_IDS: ["impostor"]}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_ADMIN_USER_IDS: "invalid_admin"}
|
||||
assert await_gather(list_admin_ids(database)) == ["u1"]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_submit_without_admin_key_keeps_allowlist(tmp_path) -> None:
|
||||
"""Raw callers omitting the key (pre-picker payloads) do not
|
||||
touch the allowlist; the CURRENT allowlist is carried forward on
|
||||
the options copy so no removed admin can be resurrected later."""
|
||||
database = _open_allowlist_db(tmp_path, "picker-legacy.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_ADMIN_USER_IDS] == ["u1"]
|
||||
assert await_gather(list_admin_ids(database)) == ["u1"]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_duplicate_selection_refused(tmp_path) -> None:
|
||||
"""Duplicate ids surface as a field error, not an unhandled
|
||||
ValueError from the business layer."""
|
||||
database = _open_allowlist_db(tmp_path, "picker-dupe.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
list_admin_ids,
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u1"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua"), _user("u2", "Sam")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{**VALID_INPUT, CONF_ADMIN_USER_IDS: ["u2", "u2"]}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_ADMIN_USER_IDS: "invalid_admin"}
|
||||
assert await_gather(list_admin_ids(database)) == ["u1"]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_omitted_picker_carries_allowlist_forward(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""An omitted picker field must not drop the allowlist copy from
|
||||
the returned options: HA replaces entry.options wholesale, and a
|
||||
later database loss must not resurrect removed admins from the
|
||||
stale config-flow copy in entry.data."""
|
||||
database = _open_allowlist_db(tmp_path, "picker-carry.db")
|
||||
try:
|
||||
from custom_components.nestquest.admin_allowlist import (
|
||||
set_admin_ids,
|
||||
)
|
||||
|
||||
_run(set_admin_ids(database, ["u2"]))
|
||||
entry = _make_entry()
|
||||
flow = _make_flow(
|
||||
entry,
|
||||
users=[_user("u1", "Joshua"), _user("u2", "Sam")],
|
||||
database=database,
|
||||
)
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
# The current allowlist rides along on the legacy three-key path.
|
||||
assert result["data"][CONF_ADMIN_USER_IDS] == ["u2"]
|
||||
assert result["data"][CONF_HORIZON_DAYS] == VALID_INPUT[CONF_HORIZON_DAYS]
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_options_flow_notification_section_defaults() -> None:
|
||||
"""A bare submit fills the notification section from const defaults:
|
||||
08:00 / 15:00 / 20:00 — the report deliberately BEFORE the midnight
|
||||
rollover sweep — an empty notify target, and all toggles enabled."""
|
||||
def test_options_flow_api_section_defaults_saved() -> None:
|
||||
"""A bare submit saves the API connection defaults: the const base
|
||||
URL and an EMPTY panel token (no token is ever invented)."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_MORNING_SUMMARY_TIME] == "08:00"
|
||||
assert result["data"][CONF_AFTERNOON_REMINDER_TIME] == "15:00"
|
||||
assert result["data"][CONF_END_OF_DAY_REPORT_TIME] == "20:00"
|
||||
assert result["data"][CONF_NOTIFY_TARGET] == ""
|
||||
for toggle in (
|
||||
CONF_MORNING_SUMMARY_ENABLED,
|
||||
CONF_AFTERNOON_REMINDER_ENABLED,
|
||||
CONF_END_OF_DAY_REPORT_ENABLED,
|
||||
CONF_CELEBRATION_ENABLED,
|
||||
):
|
||||
assert result["data"][toggle] is True
|
||||
assert result["data"][CONF_API_BASE_URL] == DEFAULT_API_BASE_URL
|
||||
assert result["data"][CONF_PANEL_TOKEN] == ""
|
||||
|
||||
|
||||
def test_options_flow_notification_times_must_be_strict_hh_mm() -> None:
|
||||
def test_options_flow_api_base_url_must_be_full_http_url() -> None:
|
||||
"""Scheme-less, host-less, empty, and non-string base URLs reject
|
||||
with a field error — the same rule the client's constructor
|
||||
enforces, so a malformed URL fails at the form, not at the first
|
||||
request."""
|
||||
flow = _make_flow(_make_entry())
|
||||
for bad_time in ("9:00", "25:00", "08:0", "08-00", 800):
|
||||
for bad_url in ("api.lan:8000", "http://", "", " ", 42):
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{
|
||||
**VALID_INPUT,
|
||||
CONF_MORNING_SUMMARY_TIME: bad_time,
|
||||
}
|
||||
{**VALID_INPUT, CONF_API_BASE_URL: bad_url}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_MORNING_SUMMARY_TIME: "invalid_time"}
|
||||
assert result["errors"] == {CONF_API_BASE_URL: "invalid_url"}
|
||||
|
||||
|
||||
def test_options_flow_notify_target_validation() -> None:
|
||||
"""The empty target is VALID (it is the shipped default and must be
|
||||
savable); only malformed non-empty values reject."""
|
||||
def test_options_flow_panel_token_validation() -> None:
|
||||
"""The EMPTY token is valid (the API connection is simply not
|
||||
configured yet); padded and non-string values reject — a padded
|
||||
paste would fail the token check at request time instead."""
|
||||
flow = _make_flow(_make_entry())
|
||||
# The empty default saves cleanly.
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{**VALID_INPUT, CONF_NOTIFY_TARGET: ""}
|
||||
)
|
||||
flow.async_step_init({**VALID_INPUT, CONF_PANEL_TOKEN: ""})
|
||||
)
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_NOTIFY_TARGET] == ""
|
||||
assert result["data"][CONF_PANEL_TOKEN] == ""
|
||||
|
||||
# Malformed non-empty values reject.
|
||||
for bad_target in (" notify.x ", " ", 42):
|
||||
for bad_token in (" secret ", " ", 42):
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{
|
||||
**VALID_INPUT,
|
||||
CONF_NOTIFY_TARGET: bad_target,
|
||||
}
|
||||
{**VALID_INPUT, CONF_PANEL_TOKEN: bad_token}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_NOTIFY_TARGET: "invalid"}
|
||||
assert result["errors"] == {CONF_PANEL_TOKEN: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_toggles_must_be_real_booleans() -> None:
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{
|
||||
**VALID_INPUT,
|
||||
CONF_CELEBRATION_ENABLED: "on",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_CELEBRATION_ENABLED: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_notification_stored_values_round_trip() -> None:
|
||||
"""Stored notification settings are the form's defaults and a raw
|
||||
def test_options_flow_api_section_stored_values_round_trip() -> None:
|
||||
"""Stored API settings are the form's defaults and a raw legacy
|
||||
submit without them keeps the stored values."""
|
||||
entry = _make_entry(
|
||||
options={
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_NOTIFY_TARGET: "notify.mobile_app_dad",
|
||||
CONF_MORNING_SUMMARY_TIME: "07:15",
|
||||
CONF_AFTERNOON_REMINDER_TIME: "16:45",
|
||||
CONF_END_OF_DAY_REPORT_TIME: "21:00",
|
||||
CONF_MORNING_SUMMARY_ENABLED: False,
|
||||
CONF_AFTERNOON_REMINDER_ENABLED: True,
|
||||
CONF_END_OF_DAY_REPORT_ENABLED: False,
|
||||
CONF_CELEBRATION_ENABLED: True,
|
||||
CONF_API_BASE_URL: "http://panel.lan:8443",
|
||||
CONF_PANEL_TOKEN: "stored-token",
|
||||
}
|
||||
)
|
||||
flow = _make_flow(entry)
|
||||
form = _run(flow.async_step_init(None))
|
||||
schema_defaults = form["data_schema"]({})
|
||||
assert schema_defaults[CONF_NOTIFY_TARGET] == "notify.mobile_app_dad"
|
||||
assert schema_defaults[CONF_MORNING_SUMMARY_TIME] == "07:15"
|
||||
assert schema_defaults[CONF_END_OF_DAY_REPORT_ENABLED] is False
|
||||
assert schema_defaults[CONF_API_BASE_URL] == "http://panel.lan:8443"
|
||||
assert schema_defaults[CONF_PANEL_TOKEN] == "stored-token"
|
||||
|
||||
# A raw submit carrying only the legacy keys keeps the stored
|
||||
# notification settings.
|
||||
# A raw submit carrying only the panel-idle key keeps the stored
|
||||
# API connection settings.
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_NOTIFY_TARGET] == "notify.mobile_app_dad"
|
||||
assert result["data"][CONF_MORNING_SUMMARY_TIME] == "07:15"
|
||||
assert result["data"][CONF_MORNING_SUMMARY_ENABLED] is False
|
||||
assert result["data"][CONF_CELEBRATION_ENABLED] is True
|
||||
assert result["data"][CONF_API_BASE_URL] == "http://panel.lan:8443"
|
||||
assert result["data"][CONF_PANEL_TOKEN] == "stored-token"
|
||||
|
||||
|
||||
def test_options_flow_no_hard_coded_personal_target_in_source() -> None:
|
||||
"""The notify target's DEFAULT is the empty string: the household
|
||||
fills their own service name, and no personal target ships as a
|
||||
value anywhere in the const/flow defaults."""
|
||||
from custom_components.nestquest import const
|
||||
def test_options_flow_strings_cover_api_section(
|
||||
strings: dict, translations_en: dict
|
||||
) -> None:
|
||||
"""Both string files name the API fields and the URL error."""
|
||||
data = strings["options"]["step"]["init"]["data"]
|
||||
for key in (CONF_API_BASE_URL, CONF_PANEL_TOKEN):
|
||||
assert data.get(key), f"Missing field name for '{key}'"
|
||||
assert strings["options"]["errors"]["invalid_url"]
|
||||
assert translations_en["options"] == strings["options"]
|
||||
|
||||
assert getattr(const, "CONF_NOTIFY_TARGET", None) == "notify_target"
|
||||
# No const default carries a concrete notify service.
|
||||
assert const.__dict__.get("DEFAULT_NOTIFY_TARGET", "") == ""
|
||||
form = _run(_make_flow(_make_entry()).async_step_init(None))
|
||||
assert form["data_schema"]({})[CONF_NOTIFY_TARGET] == ""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Last-good snapshot staleness section (Feature 18)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_options_flow_staleness_below_update_interval_refused() -> None:
|
||||
"""A staleness threshold shorter than the submit's update interval
|
||||
is refused with the dedicated error: such a threshold could never
|
||||
serve even one cached snapshot."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: 300,
|
||||
CONF_SNAPSHOT_STALENESS: 60,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_SNAPSHOT_STALENESS: "invalid_staleness"}
|
||||
|
||||
|
||||
def test_options_flow_staleness_below_stored_interval_refused() -> None:
|
||||
"""A raw submit setting the staleness but omitting the update
|
||||
interval is checked against the STORED interval, not the default."""
|
||||
entry = _make_entry(options={CONF_UPDATE_INTERVAL: 300})
|
||||
flow = _make_flow(entry)
|
||||
result = _run(
|
||||
flow.async_step_init({**VALID_INPUT, CONF_SNAPSHOT_STALENESS: 60})
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_SNAPSHOT_STALENESS: "invalid_staleness"}
|
||||
|
||||
|
||||
def test_options_flow_staleness_must_be_positive_int() -> None:
|
||||
"""Non-int, boolean, and non-positive staleness values reject with
|
||||
the plain invalid error."""
|
||||
flow = _make_flow(_make_entry())
|
||||
for bad_staleness in ("900", True, 0, -10):
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{**VALID_INPUT, CONF_SNAPSHOT_STALENESS: bad_staleness}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {CONF_SNAPSHOT_STALENESS: "invalid"}
|
||||
|
||||
|
||||
def test_options_flow_staleness_equal_to_interval_saves() -> None:
|
||||
"""A threshold exactly as long as the update interval is valid (the
|
||||
boundary is inclusive)."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(
|
||||
flow.async_step_init(
|
||||
{
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: 300,
|
||||
CONF_SNAPSHOT_STALENESS: 300,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_SNAPSHOT_STALENESS] == 300
|
||||
|
||||
|
||||
def test_options_flow_staleness_defaults_saved() -> None:
|
||||
"""A bare submit saves the staleness default (three update
|
||||
intervals) alongside the other defaults."""
|
||||
flow = _make_flow(_make_entry())
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_SNAPSHOT_STALENESS] == DEFAULT_SNAPSHOT_STALENESS
|
||||
|
||||
|
||||
def test_options_flow_staleness_stored_values_round_trip() -> None:
|
||||
"""A stored staleness is the form's default and a raw legacy submit
|
||||
without it keeps the stored value."""
|
||||
entry = _make_entry(
|
||||
options={
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: 300,
|
||||
CONF_SNAPSHOT_STALENESS: 1200,
|
||||
}
|
||||
)
|
||||
flow = _make_flow(entry)
|
||||
form = _run(flow.async_step_init(None))
|
||||
schema_defaults = form["data_schema"]({})
|
||||
assert schema_defaults[CONF_SNAPSHOT_STALENESS] == 1200
|
||||
|
||||
# A raw submit carrying only the panel-idle key keeps the stored
|
||||
# staleness (and never trips the interval cross-check).
|
||||
result = _run(flow.async_step_init(dict(VALID_INPUT)))
|
||||
assert result["type"] == "create_entry"
|
||||
assert result["data"][CONF_SNAPSHOT_STALENESS] == 1200
|
||||
|
||||
|
||||
def test_options_flow_strings_cover_staleness_section(
|
||||
strings: dict, translations_en: dict
|
||||
) -> None:
|
||||
"""Both string files name the staleness field and its error."""
|
||||
data = strings["options"]["step"]["init"]["data"]
|
||||
assert data.get(CONF_SNAPSHOT_STALENESS), (
|
||||
f"Missing field name for '{CONF_SNAPSHOT_STALENESS}'"
|
||||
)
|
||||
assert strings["options"]["errors"]["invalid_staleness"]
|
||||
assert translations_en["options"] == strings["options"]
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
"""Feature 09 permission test matrix across every registered service."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
import pytest
|
||||
from homeassistant.exceptions import Unauthorized
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
DOMAIN,
|
||||
DOMAIN_SERVICES,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
SERVICE_CREATE_PRESENCE_OVERRIDE,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
SERVICE_DELETE_PRESENCE_OVERRIDE,
|
||||
SERVICE_EXPORT_HISTORY_CSV,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
SERVICE_REGENERATE,
|
||||
SERVICE_SET_PRESENCE_PATTERN,
|
||||
SERVICE_SET_QUEST_DEFINITION_ACTIVE,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
SERVICE_UPDATE_QUEST_DEFINITION,
|
||||
)
|
||||
from custom_components.nestquest.service_policy import (
|
||||
ADMIN_ONLY,
|
||||
OPEN,
|
||||
SERVICE_POLICY,
|
||||
)
|
||||
|
||||
ADMIN_ID = "admin-1"
|
||||
ADMIN_CTX = {"user_id": ADMIN_ID}
|
||||
NON_ADMIN_ID = "non-admin"
|
||||
NON_ADMIN_CTX = {"user_id": NON_ADMIN_ID}
|
||||
KIOSK_ID = "kiosk-panel"
|
||||
KIOSK_CTX = {"user_id": KIOSK_ID}
|
||||
|
||||
|
||||
def test_every_registered_service_is_in_the_operation_registry() -> None:
|
||||
"""The registry is total: a service outside it could never be gated."""
|
||||
missing = [
|
||||
service for service in DOMAIN_SERVICES if service not in SERVICE_POLICY
|
||||
]
|
||||
extra = [
|
||||
service for service in SERVICE_POLICY if service not in DOMAIN_SERVICES
|
||||
]
|
||||
assert not missing, f"registered but ungated: {missing}"
|
||||
assert not extra, f"gated but never registered: {extra}"
|
||||
assert set(SERVICE_POLICY.values()) == {OPEN, ADMIN_ONLY}
|
||||
|
||||
|
||||
async def _setup(hass, make_entry, *, admin=True):
|
||||
data = {CONF_ADMIN_USER_IDS: [ADMIN_ID]} if admin else {}
|
||||
entry = wire_entry_to_registry(make_entry(data=data), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry
|
||||
|
||||
|
||||
async def _seed(hass, entry) -> dict:
|
||||
"""Seed one child, one definition, and materialized instances."""
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
database = entry.runtime_data.database
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [(await list_children(database))[0].id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
child = (await list_children(database))[0]
|
||||
today = datetime.date.today().isoformat()
|
||||
end = (
|
||||
datetime.date.today() + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
instances = await QuestInstancesDao(database).list_by_date_range(
|
||||
child.id, today, end
|
||||
)
|
||||
assert instances
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
PresenceOverridesDao,
|
||||
)
|
||||
|
||||
return {
|
||||
"child_id": child.id,
|
||||
"instance_id": instances[0].id,
|
||||
"definition_id": instances[0].definition_id,
|
||||
"override": await PresenceOverridesDao(database).create(
|
||||
child.id, "2027-01-01", "2027-01-02", False
|
||||
),
|
||||
"today": today,
|
||||
"database": database,
|
||||
}
|
||||
|
||||
|
||||
def _admin_success_payload(service: str, ctx: dict) -> dict | None:
|
||||
"""A schema-valid, end-to-end-successful payload per admin service."""
|
||||
if service == SERVICE_UNCOMPLETE_QUEST:
|
||||
return {"instance_id": ctx["instance_id"], "actor": "user"}
|
||||
if service == SERVICE_CREATE_QUEST_DEFINITION:
|
||||
return {
|
||||
"title": "Second quest",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [ctx["child_id"]],
|
||||
"windows": ["afternoon"],
|
||||
}
|
||||
if service == SERVICE_UPDATE_QUEST_DEFINITION:
|
||||
return {"definition_id": ctx["definition_id"], "title": "Brush teeth 2"}
|
||||
if service == SERVICE_SET_QUEST_DEFINITION_ACTIVE:
|
||||
return {"definition_id": ctx["definition_id"], "is_active": False}
|
||||
if service == SERVICE_SET_PRESENCE_PATTERN:
|
||||
return {
|
||||
"child_id": ctx["child_id"],
|
||||
"cycle_length_weeks": 1,
|
||||
"anchor_date": ctx["today"],
|
||||
"pattern": {0: [0, 1, 2, 3, 4, 5, 6]},
|
||||
}
|
||||
if service == SERVICE_CREATE_PRESENCE_OVERRIDE:
|
||||
return {
|
||||
"child_id": ctx["child_id"],
|
||||
"start_date": "2027-03-01",
|
||||
"end_date": "2027-03-02",
|
||||
"is_present": False,
|
||||
}
|
||||
if service == SERVICE_DELETE_PRESENCE_OVERRIDE:
|
||||
return {"override_id": ctx["override"].id}
|
||||
if service == SERVICE_EXPORT_HISTORY_CSV:
|
||||
return None # raises HomeAssistantError (Feature 13) — not Unauthorized
|
||||
if service == SERVICE_MANAGE_CHILD:
|
||||
return {"action": "create", "display_name": "Bo"}
|
||||
if service == SERVICE_REGENERATE:
|
||||
return {}
|
||||
raise AssertionError(f"unexpected service {service}")
|
||||
|
||||
|
||||
_ADMIN_ONLY = [
|
||||
service for service, policy in SERVICE_POLICY.items() if policy == ADMIN_ONLY
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("service", _ADMIN_ONLY)
|
||||
async def test_admin_succeeds_on_every_admin_only_service(
|
||||
hass, make_entry, service
|
||||
) -> None:
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
entry = await _setup(hass, make_entry)
|
||||
ctx = await _seed(hass, entry)
|
||||
if service == SERVICE_EXPORT_HISTORY_CSV:
|
||||
# The gate passes; the Feature 13 stub raises its "not
|
||||
# implemented" HomeAssistantError — NOT Unauthorized.
|
||||
with pytest.raises(HomeAssistantError, match="Feature 13"):
|
||||
await hass.services.call(
|
||||
DOMAIN, service, None, context=ADMIN_CTX
|
||||
)
|
||||
return
|
||||
await hass.services.call(
|
||||
DOMAIN, service, _admin_success_payload(service, ctx), context=ADMIN_CTX
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("service", _ADMIN_ONLY)
|
||||
async def test_non_admin_refused_on_every_admin_only_service(
|
||||
hass, make_entry, service
|
||||
) -> None:
|
||||
entry = await _setup(hass, make_entry)
|
||||
ctx = await _seed(hass, entry)
|
||||
if service != SERVICE_EXPORT_HISTORY_CSV:
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
service,
|
||||
_admin_success_payload(service, ctx),
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
service,
|
||||
_admin_success_payload(service, ctx),
|
||||
context=NON_ADMIN_CTX,
|
||||
)
|
||||
|
||||
|
||||
async def test_non_admin_allowed_on_complete_quest(hass, make_entry) -> None:
|
||||
from custom_components.nestquest.completion import instance_state
|
||||
|
||||
entry = await _setup(hass, make_entry)
|
||||
ctx = await _seed(hass, entry)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": ctx["instance_id"],
|
||||
"actor": "panel",
|
||||
"actor_child_id": ctx["child_id"],
|
||||
},
|
||||
context=NON_ADMIN_CTX,
|
||||
)
|
||||
assert (
|
||||
await instance_state(ctx["database"], ctx["instance_id"]) == "done"
|
||||
)
|
||||
|
||||
|
||||
async def test_kiosk_refused_on_uncomplete_and_regenerate(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = await _setup(hass, make_entry)
|
||||
ctx = await _seed(hass, entry)
|
||||
from custom_components.nestquest.admin_allowlist import list_admin_ids
|
||||
|
||||
assert KIOSK_ID not in await list_admin_ids(ctx["database"])
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
{"instance_id": ctx["instance_id"], "actor": "user"},
|
||||
context=KIOSK_CTX,
|
||||
)
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN, SERVICE_REGENERATE, context=KIOSK_CTX
|
||||
)
|
||||
@@ -1,122 +0,0 @@
|
||||
"""Tests for the Feature 09 permission gate's audit logging."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from homeassistant.exceptions import Unauthorized
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
)
|
||||
|
||||
ADMIN_ID = "admin-1"
|
||||
ADMIN_CTX = {"user_id": ADMIN_ID}
|
||||
_TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
|
||||
|
||||
|
||||
async def _set_up(hass, make_entry):
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(data={CONF_ADMIN_USER_IDS: [ADMIN_ID]}), hass.registry
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
return entry
|
||||
|
||||
|
||||
async def test_denied_call_logs_warning_with_fields(
|
||||
hass, make_entry, caplog
|
||||
) -> None:
|
||||
entry = await _set_up(hass, make_entry)
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context={"user_id": "kiosk-panel"},
|
||||
)
|
||||
denials = [
|
||||
record
|
||||
for record in caplog.records
|
||||
if record.levelno == logging.WARNING
|
||||
and "denied" in record.getMessage()
|
||||
]
|
||||
assert len(denials) == 1
|
||||
message = denials[0].getMessage()
|
||||
assert SERVICE_MANAGE_CHILD in message
|
||||
assert "kiosk-panel" in message
|
||||
assert _TIMESTAMP.search(message), message
|
||||
|
||||
|
||||
async def test_denied_no_context_logs_user_none(
|
||||
hass, make_entry, caplog
|
||||
) -> None:
|
||||
entry = await _set_up(hass, make_entry)
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
)
|
||||
denials = [
|
||||
record
|
||||
for record in caplog.records
|
||||
if record.levelno == logging.WARNING
|
||||
and "denied" in record.getMessage()
|
||||
]
|
||||
assert len(denials) == 1
|
||||
message = denials[0].getMessage()
|
||||
assert "none" in message
|
||||
assert _TIMESTAMP.search(message), message
|
||||
|
||||
|
||||
async def test_successful_admin_call_logs_debug_with_fields(
|
||||
hass, make_entry, caplog
|
||||
) -> None:
|
||||
caplog.set_level(logging.DEBUG, logger="custom_components.nestquest")
|
||||
entry = await _set_up(hass, make_entry)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
allowed = [
|
||||
record
|
||||
for record in caplog.records
|
||||
if record.levelno == logging.DEBUG
|
||||
and "allowed" in record.getMessage()
|
||||
]
|
||||
assert len(allowed) == 1
|
||||
message = allowed[0].getMessage()
|
||||
assert SERVICE_MANAGE_CHILD in message
|
||||
assert ADMIN_ID in message
|
||||
assert _TIMESTAMP.search(message), message
|
||||
|
||||
|
||||
async def test_denied_log_carries_no_personal_data_beyond_user_id(
|
||||
hass, make_entry, caplog
|
||||
) -> None:
|
||||
"""The log line names the caller's user id only: the payload's
|
||||
display name must not leak into the audit trail."""
|
||||
entry = await _set_up(hass, make_entry)
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context={"user_id": "kiosk-panel"},
|
||||
)
|
||||
denials = [
|
||||
record.getMessage()
|
||||
for record in caplog.records
|
||||
if record.levelno == logging.WARNING and "denied" in record.getMessage()
|
||||
]
|
||||
assert denials, "expected a denial log line"
|
||||
assert "Ada" not in denials[0]
|
||||
assert "display_name" not in denials[0]
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.presence import (
|
||||
from custom_components.nestquest.core.presence import (
|
||||
MAX_CYCLE_LENGTH_WEEKS,
|
||||
PresenceEngine,
|
||||
PresenceOverride,
|
||||
|
||||
@@ -7,20 +7,20 @@ import re
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.core.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
from custom_components.nestquest.core.dao_instances import (
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import (
|
||||
from custom_components.nestquest.core.dao_rules import (
|
||||
QuestDefinitionsDao,
|
||||
ScheduleRulesDao,
|
||||
schedule_rule_to_storage,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
CreatedQuestDefinition,
|
||||
assign_child,
|
||||
create_quest_definition,
|
||||
@@ -31,7 +31,7 @@ from custom_components.nestquest.quest_definitions import (
|
||||
set_quest_definition_active,
|
||||
unassign_child,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import RuleType, ScheduleRule
|
||||
from custom_components.nestquest.core.recurrence import RuleType, ScheduleRule
|
||||
|
||||
|
||||
def _run(coro):
|
||||
@@ -1150,7 +1150,7 @@ def test_concurrent_assign_unassign_returns_consistent_roster(
|
||||
)
|
||||
bo = await children.create("Bo", NOW)
|
||||
|
||||
import custom_components.nestquest.dao_rules as dao_rules
|
||||
import custom_components.nestquest.core.dao_rules as dao_rules
|
||||
|
||||
original_list = dao_rules.QuestDefinitionsDao.list_assignees
|
||||
started = asyncio.Event()
|
||||
@@ -1666,7 +1666,7 @@ def test_list_query_snapshot_coherent_under_racing_edit(tmp_path) -> None:
|
||||
start_date="2026-09-14",
|
||||
)
|
||||
|
||||
import custom_components.nestquest.dao_rules as dao_rules
|
||||
import custom_components.nestquest.core.dao_rules as dao_rules
|
||||
|
||||
original_list = dao_rules.QuestDefinitionsDao.list_windows
|
||||
started = asyncio.Event()
|
||||
@@ -1732,7 +1732,7 @@ def test_list_definitions_for_child_snapshot_coherent_under_racing_unassign(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
|
||||
import custom_components.nestquest.dao_rules as dao_rules
|
||||
import custom_components.nestquest.core.dao_rules as dao_rules
|
||||
|
||||
original_list = dao_rules.QuestDefinitionsDao.list_assignees
|
||||
started = asyncio.Event()
|
||||
@@ -1795,7 +1795,7 @@ def test_list_active_definitions_snapshot_coherent_under_racing_edit(
|
||||
start_date="2026-09-14",
|
||||
)
|
||||
|
||||
import custom_components.nestquest.dao_rules as dao_rules
|
||||
import custom_components.nestquest.core.dao_rules as dao_rules
|
||||
|
||||
original_list = dao_rules.QuestDefinitionsDao.list_windows
|
||||
started = asyncio.Event()
|
||||
|
||||
@@ -12,7 +12,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -15,7 +15,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
ScheduleRule,
|
||||
RuleType,
|
||||
occurs_on,
|
||||
@@ -395,7 +395,7 @@ def test_recurrence_engine_imports_nothing_forbidden() -> None:
|
||||
|
||||
module_file = Path(
|
||||
importlib.util.find_spec(
|
||||
"custom_components.nestquest.recurrence"
|
||||
"custom_components.nestquest.core.recurrence"
|
||||
).origin
|
||||
)
|
||||
tree = ast.parse(module_file.read_text())
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
@@ -219,7 +219,7 @@ def test_occurs_on_rejects_unknown_shapes_loudly() -> None:
|
||||
than a silent wrong answer. Forged via a private enum extension
|
||||
because ScheduleRule validation rejects unknown names."""
|
||||
import enum as enum_module
|
||||
from custom_components.nestquest import recurrence as mod
|
||||
from custom_components.nestquest.core import recurrence as mod
|
||||
|
||||
ForgedType = enum_module.Enum(
|
||||
"ForgedType", {"UNKNOWN_SHAPE": "unknown_shape"}
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
@@ -344,12 +344,12 @@ def test_purity_guard_logic_catches_probe_statements(tmp_path) -> None:
|
||||
"from homeassistant.core import HomeAssistant",
|
||||
"import sqlite3",
|
||||
"from .db import NestQuestDatabase",
|
||||
"from custom_components.nestquest.db import NestQuestDatabase",
|
||||
"from custom_components.nestquest.core.db import NestQuestDatabase",
|
||||
"from custom_components.nestquest import db",
|
||||
"import custom_components.nestquest.dao_rules",
|
||||
"import custom_components.nestquest.core.dao_rules",
|
||||
"from . import db",
|
||||
"from . import schema",
|
||||
"from custom_components.nestquest.migrations import apply_migrations",
|
||||
"from custom_components.nestquest.core.migrations import apply_migrations",
|
||||
]
|
||||
for probe in probes:
|
||||
offenders = _scan_forbidden_imports(probe)
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -18,7 +18,7 @@ import random
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -5,7 +5,7 @@ import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.recurrence import (
|
||||
from custom_components.nestquest.core.recurrence import (
|
||||
RuleType,
|
||||
RuleValidationError,
|
||||
ScheduleRule,
|
||||
|
||||
@@ -6,8 +6,8 @@ import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.schema import (
|
||||
from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.schema import (
|
||||
SCHEMA_V1_ADMIN_USERS_DDL,
|
||||
SCHEMA_V1_CHILDREN_DDL,
|
||||
SCHEMA_V1_COMPLETION_EVENTS_DDL,
|
||||
|
||||
+236
-210
@@ -1,75 +1,132 @@
|
||||
"""Tests for the per-child daily count and percentage sensors (Feature 10, task 2)."""
|
||||
"""Tests for the per-child daily count and percentage sensors (Feature 10, task 2).
|
||||
|
||||
Since the DB removal the snapshot comes from the API service's panel
|
||||
route, so these tests script the route's payload (the documented
|
||||
Feature 16 shape ``test_coordinator.py`` also uses) through
|
||||
:class:`conftest.StubSnapshotClient` instead of seeding a local
|
||||
database: the coordinator rebuilds the same core dataclasses the
|
||||
sensors read, and every assertion below is on entity state.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
from conftest import StubSnapshotClient, set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
from custom_components.nestquest.children import create_child
|
||||
from custom_components.nestquest.completion import complete_instance
|
||||
from custom_components.nestquest.const import DOMAIN
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import create_quest_definition
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
from custom_components.nestquest.sensor import (
|
||||
MAX_STATE_LENGTH,
|
||||
_state_within_limit,
|
||||
)
|
||||
|
||||
#: The seeding horizon: instances exist for today and a few days out,
|
||||
#: enough for the day snapshot without slowing the walk down.
|
||||
SEED_HORIZON_DAYS = 3
|
||||
|
||||
#: The documented per-child day sensor kinds (unique_id suffixes).
|
||||
SENSOR_KINDS = (
|
||||
"quests_due_today",
|
||||
"quests_completed_today",
|
||||
"quests_remaining_today",
|
||||
"completion_pct_today",
|
||||
)
|
||||
def _today_iso() -> str:
|
||||
return datetime.date.today().isoformat()
|
||||
|
||||
|
||||
def _today() -> datetime.date:
|
||||
return datetime.date.today()
|
||||
def _instance(instance_id: int, child_id: int, **overrides) -> dict:
|
||||
"""One panel instance in the API route's payload shape."""
|
||||
payload = {
|
||||
"id": instance_id,
|
||||
"definition_id": 3,
|
||||
"child_id": child_id,
|
||||
"title": "Brush teeth",
|
||||
"icon": "🦷",
|
||||
"window": "morning",
|
||||
"due_time": "08:00",
|
||||
"state": "open",
|
||||
"overdue": False,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
async def _seed_children(database):
|
||||
"""Three active children: Ada and Bo share one daily quest; Cory has none."""
|
||||
ada = await create_child(database, "Ada")
|
||||
bo = await create_child(database, "Bo")
|
||||
cory = await create_child(database, "Cory")
|
||||
today = _today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
),
|
||||
[ada.id, bo.id],
|
||||
["morning"],
|
||||
)
|
||||
end = (today + datetime.timedelta(days=SEED_HORIZON_DAYS)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
return ada, bo, cory
|
||||
def _child(child_id: int, name: str, instances=(), **overrides) -> dict:
|
||||
"""One child in the API route's payload shape, counts precomputed.
|
||||
|
||||
|
||||
async def _setup_seeded_entry(hass, make_entry):
|
||||
"""Set up the integration, seed three children, refresh: sensors exist.
|
||||
|
||||
Children are seeded AFTER setup (the entry's database only exists
|
||||
once setup opens it), so the sensors appear through the refresh
|
||||
listener — the same path production takes when a child is added.
|
||||
The API precomputes the per-child rollups from the full day; the
|
||||
builder here derives them from the instance list so a payload can
|
||||
never drift from its own counts.
|
||||
"""
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
completed = sum(1 for i in instances if i["state"] == "completed")
|
||||
due = max(len(instances), 0)
|
||||
payload = {
|
||||
"child_id": child_id,
|
||||
"child_name": name,
|
||||
"present": True,
|
||||
"next_present": None,
|
||||
"due_today": due,
|
||||
"completed_today": completed,
|
||||
"remaining_today": due - completed,
|
||||
"completion_pct": 100 if due == 0 else round(completed / due * 100),
|
||||
"instances": list(instances),
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": _today_iso(),
|
||||
"cycle_day": 0,
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
#: The seeded household: Ada and Bo share one daily quest, Cory has none.
|
||||
ADA = 1
|
||||
BO = 2
|
||||
CORY = 3
|
||||
|
||||
|
||||
def _seeded_payload() -> dict:
|
||||
return _payload(
|
||||
[
|
||||
_child(ADA, "Ada", [_instance(7, ADA)]),
|
||||
_child(BO, "Bo", [_instance(8, BO)]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _completed_payload() -> dict:
|
||||
"""The same household after the API recorded Ada's completion."""
|
||||
return _payload(
|
||||
[
|
||||
_child(
|
||||
ADA,
|
||||
"Ada",
|
||||
[_instance(7, ADA, state="completed", completed_at=f"{_today_iso()}T07:55:00+00:00", on_time=True)],
|
||||
),
|
||||
_child(BO, "Bo", [_instance(8, BO)]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def _setup_entry(hass, make_entry, *payloads):
|
||||
"""Set up the integration with a scripted snapshot client.
|
||||
|
||||
The client serves the payloads in order (repeating the last), so
|
||||
setup's first refresh and any later explicit refresh each get the
|
||||
scripted state — the same path production takes through the API.
|
||||
"""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
data={"api_base_url": "http://api.test:8000", "panel_token": "tok"}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
client = set_coordinator_client(entry, StubSnapshotClient(*payloads))
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
database = entry.runtime_data.database
|
||||
ada, bo, cory = await _seed_children(database)
|
||||
await coordinator.async_refresh()
|
||||
return entry, coordinator, (ada, bo, cory)
|
||||
assert coordinator.api_client is client
|
||||
return entry, coordinator, client
|
||||
|
||||
|
||||
def _snapshot_child(coordinator, child_id):
|
||||
@@ -85,47 +142,31 @@ def _sensor(hass, child_id, kind):
|
||||
return hass.entities[f"{DOMAIN}_child_{child_id}_{kind}"]
|
||||
|
||||
|
||||
async def _complete_first_instance(database, coordinator, child) -> None:
|
||||
"""Complete the child's first open instance through the business layer."""
|
||||
snapshot_child = _snapshot_child(coordinator, child.id)
|
||||
instance_id = snapshot_child.instances[0].instance_id
|
||||
await complete_instance(
|
||||
database,
|
||||
instance_id,
|
||||
actor_source="panel",
|
||||
actor_child_id=child.id,
|
||||
)
|
||||
|
||||
|
||||
async def test_every_active_child_gets_five_sensors_with_documented_identity(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload(), _completed_payload()
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
assert hass.config_entries.forwarded_platforms == [
|
||||
"sensor",
|
||||
"binary_sensor",
|
||||
]
|
||||
await _complete_first_instance(database, coordinator, ada)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
# Two quest children plus the zero-quest child: three children x
|
||||
# (five sensors + two binary sensors) + three household sensors,
|
||||
# no duplicates.
|
||||
# Three children x (five sensors + two binary sensors) + three
|
||||
# household sensors, no duplicates.
|
||||
assert len(hass.entities) == 24
|
||||
expected = {
|
||||
ada.id: ("Ada", 1, 1, 0, 100),
|
||||
bo.id: ("Bo", 1, 0, 1, 0),
|
||||
cory.id: ("Cory", 0, 0, 0, 100),
|
||||
ADA: ("Ada", 1, 1, 0, 100),
|
||||
BO: ("Bo", 1, 0, 1, 0),
|
||||
CORY: ("Cory", 0, 0, 0, 100),
|
||||
}
|
||||
for child_id, (name, due, completed, remaining, pct) in expected.items():
|
||||
due_entity = _sensor(hass, child_id, "quests_due_today")
|
||||
completed_entity = _sensor(hass, child_id, "quests_completed_today")
|
||||
remaining_entity = _sensor(hass, child_id, "quests_remaining_today")
|
||||
pct_entity = _sensor(hass, child_id, "completion_pct_today")
|
||||
next_entity = _sensor(hass, child_id, "next_quest")
|
||||
assert due_entity.name == f"NestQuest {name} quests due today"
|
||||
assert completed_entity.name == (
|
||||
f"NestQuest {name} quests completed today"
|
||||
@@ -151,11 +192,11 @@ async def test_every_active_child_gets_five_sensors_with_documented_identity(
|
||||
|
||||
|
||||
async def test_zero_quest_child_is_a_perfect_day(hass, make_entry) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, _coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload()
|
||||
)
|
||||
due_entity = _sensor(hass, cory.id, "quests_due_today")
|
||||
pct_entity = _sensor(hass, cory.id, "completion_pct_today")
|
||||
due_entity = _sensor(hass, CORY, "quests_due_today")
|
||||
pct_entity = _sensor(hass, CORY, "completion_pct_today")
|
||||
assert due_entity.native_value == 0
|
||||
assert pct_entity.native_value == 100, (
|
||||
"zero quests is a perfect day, not a division error"
|
||||
@@ -168,14 +209,11 @@ async def test_zero_quest_child_is_a_perfect_day(hass, make_entry) -> None:
|
||||
async def test_due_today_attributes_carry_the_panel_payload(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _completed_payload()
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
await _complete_first_instance(database, coordinator, ada)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
ada_due = _sensor(hass, ada.id, "quests_due_today")
|
||||
ada_due = _sensor(hass, ADA, "quests_due_today")
|
||||
attributes = ada_due.extra_state_attributes
|
||||
assert set(attributes) == {
|
||||
"instances",
|
||||
@@ -184,7 +222,7 @@ async def test_due_today_attributes_carry_the_panel_payload(
|
||||
"child_name",
|
||||
"present",
|
||||
}
|
||||
assert attributes["child_id"] == ada.id
|
||||
assert attributes["child_id"] == ADA
|
||||
assert attributes["child_name"] == "Ada"
|
||||
assert attributes["present"] is True
|
||||
[instance] = attributes["instances"]
|
||||
@@ -201,7 +239,7 @@ async def test_due_today_attributes_carry_the_panel_payload(
|
||||
"completed_at",
|
||||
"on_time",
|
||||
}
|
||||
assert instance["child_id"] == ada.id
|
||||
assert instance["child_id"] == ADA
|
||||
assert instance["title"] == "Brush teeth"
|
||||
assert instance["window"] == "morning"
|
||||
assert instance["state"] == "completed", (
|
||||
@@ -214,65 +252,72 @@ async def test_due_today_attributes_carry_the_panel_payload(
|
||||
"with nothing missed, admin and panel payloads are identical"
|
||||
)
|
||||
|
||||
bo_due = _sensor(hass, bo.id, "quests_due_today")
|
||||
bo_due = _sensor(hass, BO, "quests_due_today")
|
||||
[bo_instance] = bo_due.extra_state_attributes["instances"]
|
||||
assert bo_instance["state"] == "open"
|
||||
assert bo_instance["completed_at"] is None
|
||||
assert bo_instance["on_time"] is None
|
||||
|
||||
|
||||
async def test_due_today_payload_omits_missed_for_panel_includes_for_admin(
|
||||
hass, make_entry, monkeypatch
|
||||
async def test_due_today_payload_omits_missed_admin_equals_panel(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""D-009: the panel payload omits missed instances, the admin one keeps them.
|
||||
"""D-009: the panel payload omits missed instances.
|
||||
|
||||
A missed instance is derived (``due_date`` before the snapshot's
|
||||
"today"), never stored. The coordinator's day listing is keyed on
|
||||
``_local_now``'s date, so pinning the clock forward would move the
|
||||
listing window off today's rows entirely; the pinned FUTURE clock
|
||||
is therefore applied at the ``derive_state`` boundary instead —
|
||||
today's open instances then read as missed through the same
|
||||
derivation rule, without back-dating instance rows past the DAO's
|
||||
no-past guard or touching append-only completion events.
|
||||
Since Feature 18 the snapshot comes from the API panel route,
|
||||
which omits missed rows entirely (the admin surface for missed
|
||||
quests is the PWA, reading the API directly). The integration
|
||||
renders exactly what the route sent: a snapshot can never carry a
|
||||
``missed`` view, ``admin_instances`` equals ``instances``, and the
|
||||
precomputed counts arrive untouched — pinned here with an open
|
||||
instance whose derived state reads missed (a past ``due_time``
|
||||
with the counts already rolled up the way the route builds them).
|
||||
"""
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
payload = _payload(
|
||||
[
|
||||
_child(
|
||||
BO,
|
||||
"Bo",
|
||||
[
|
||||
_instance(
|
||||
8,
|
||||
BO,
|
||||
due_time="00:01",
|
||||
overdue=True,
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
import custom_components.nestquest.core.snapshot as snapshot_module
|
||||
entry, _coordinator, _client = await _setup_entry(hass, make_entry, payload)
|
||||
|
||||
tomorrow = _today() + datetime.timedelta(days=1)
|
||||
real_derive_state = snapshot_module.derive_state
|
||||
|
||||
def _derive_against_pinned_future(instance, latest, today):
|
||||
return real_derive_state(instance, latest, tomorrow)
|
||||
|
||||
monkeypatch.setattr(
|
||||
snapshot_module, "derive_state", _derive_against_pinned_future
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
bo_due = _sensor(hass, bo.id, "quests_due_today")
|
||||
bo_due = _sensor(hass, BO, "quests_due_today")
|
||||
attributes = bo_due.extra_state_attributes
|
||||
assert attributes["instances"] == [], (
|
||||
"missed instances are omitted from the panel payload"
|
||||
assert attributes["instances"], "an open row renders in the panel payload"
|
||||
assert attributes["admin_instances"] == attributes["instances"], (
|
||||
"the API payload omits missed rows, so the admin payload "
|
||||
"carries none either (the PWA is the admin surface now)"
|
||||
)
|
||||
[missed] = attributes["admin_instances"]
|
||||
assert missed["state"] == "missed"
|
||||
assert missed["completed_at"] is None
|
||||
# Counts still roll the missed instance up as not-completed.
|
||||
assert _sensor(hass, bo.id, "quests_completed_today").native_value == 0
|
||||
assert _sensor(hass, bo.id, "quests_remaining_today").native_value == 1
|
||||
# The counts arrive precomputed from the route's own build, which
|
||||
# rolls the FULL day (any missed row included) into the numbers.
|
||||
assert _sensor(hass, BO, "quests_completed_today").native_value == 0
|
||||
assert _sensor(hass, BO, "quests_remaining_today").native_value == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", SENSOR_KINDS)
|
||||
@pytest.mark.parametrize("kind", (
|
||||
"quests_due_today",
|
||||
"quests_completed_today",
|
||||
"quests_remaining_today",
|
||||
"completion_pct_today",
|
||||
))
|
||||
async def test_no_sensor_state_exceeds_the_255_character_limit(
|
||||
hass, make_entry, kind
|
||||
) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, _coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload()
|
||||
)
|
||||
for child in (ada, bo, cory):
|
||||
entity = _sensor(hass, child.id, kind)
|
||||
for child_id in (ADA, BO, CORY):
|
||||
entity = _sensor(hass, child_id, kind)
|
||||
state = entity.native_value
|
||||
assert len(str(state)) <= MAX_STATE_LENGTH
|
||||
|
||||
@@ -288,14 +333,13 @@ def test_state_within_limit_refuses_overlong_strings() -> None:
|
||||
async def test_sensors_update_on_refresh_after_a_completion(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload(), _completed_payload()
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
completed_entity = _sensor(hass, ada.id, "quests_completed_today")
|
||||
remaining_entity = _sensor(hass, ada.id, "quests_remaining_today")
|
||||
pct_entity = _sensor(hass, ada.id, "completion_pct_today")
|
||||
due_entity = _sensor(hass, ada.id, "quests_due_today")
|
||||
completed_entity = _sensor(hass, ADA, "quests_completed_today")
|
||||
remaining_entity = _sensor(hass, ADA, "quests_remaining_today")
|
||||
pct_entity = _sensor(hass, ADA, "completion_pct_today")
|
||||
due_entity = _sensor(hass, ADA, "quests_due_today")
|
||||
assert completed_entity.native_value == 0
|
||||
assert remaining_entity.native_value == 1
|
||||
assert pct_entity.native_value == 0
|
||||
@@ -311,7 +355,6 @@ async def test_sensors_update_on_refresh_after_a_completion(
|
||||
|
||||
due_entity.async_write_ha_state = _record_write
|
||||
|
||||
await _complete_first_instance(database, coordinator, ada)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
assert completed_entity.native_value == 1
|
||||
@@ -323,8 +366,8 @@ async def test_sensors_update_on_refresh_after_a_completion(
|
||||
async def test_repeated_refreshes_do_not_duplicate_entities(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload()
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
await coordinator.async_refresh()
|
||||
@@ -334,8 +377,9 @@ async def test_repeated_refreshes_do_not_duplicate_entities(
|
||||
async def test_setup_with_no_children_registers_only_household(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
entry, _coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _payload([])
|
||||
)
|
||||
# No children means no per-child entities; the three household
|
||||
# rollups still exist (an empty household is a valid 0).
|
||||
assert set(hass.entities) == {
|
||||
@@ -347,8 +391,7 @@ async def test_setup_with_no_children_registers_only_household(
|
||||
|
||||
|
||||
async def test_unload_unloads_platforms(hass, make_entry) -> None:
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
entry, _coordinator, _client = await _setup_entry(hass, make_entry)
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
assert hass.config_entries.unloaded_platforms == [
|
||||
"sensor",
|
||||
@@ -359,20 +402,23 @@ async def test_unload_unloads_platforms(hass, make_entry) -> None:
|
||||
async def test_rename_propagates_to_name_and_device_label(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A manage_child rename shows on the next refresh: the name and
|
||||
device label re-derive from the snapshot while the unique_id (and
|
||||
therefore history) is untouched."""
|
||||
from custom_components.nestquest.children import edit_child
|
||||
|
||||
entry, coordinator, (ada, _bo, _cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
"""A rename in the API's snapshot shows on the next refresh: the
|
||||
name and device label re-derive from the snapshot while the
|
||||
unique_id (and therefore history) is untouched."""
|
||||
renamed = _payload(
|
||||
[
|
||||
_child(ADA, "Mirren", [_instance(7, ADA)]),
|
||||
_child(BO, "Bo", [_instance(8, BO)]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
due_sensor = _sensor(hass, ada.id, "quests_due_today")
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload(), renamed
|
||||
)
|
||||
due_sensor = _sensor(hass, ADA, "quests_due_today")
|
||||
original_unique_id = due_sensor.unique_id
|
||||
assert due_sensor.name.startswith("NestQuest Ada ")
|
||||
|
||||
await edit_child(database, ada.id, display_name="Mirren")
|
||||
await coordinator.async_refresh()
|
||||
|
||||
assert due_sensor.name.startswith("NestQuest Mirren ")
|
||||
@@ -384,12 +430,11 @@ async def test_failed_platform_unload_returns_false_and_retains_runtime(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""When HA reports platforms still loaded, the unload must NOT
|
||||
close the database the live entities read: it returns False and
|
||||
keeps the runtime record for a retry."""
|
||||
entry, _coordinator, _children = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
tear down the coordinator the live entities read: it returns False
|
||||
and keeps the runtime record for a retry."""
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload()
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
|
||||
async def _refuse_unload(entry_arg, platforms):
|
||||
return False
|
||||
@@ -397,26 +442,27 @@ async def test_failed_platform_unload_returns_false_and_retains_runtime(
|
||||
hass.config_entries.async_unload_platforms = _refuse_unload
|
||||
assert await async_unload_entry(hass, entry) is False
|
||||
assert hass.data[DOMAIN][entry.entry_id] is entry.runtime_data
|
||||
assert database.connected is True
|
||||
assert entry.runtime_data.coordinator is coordinator
|
||||
|
||||
|
||||
async def test_next_quest_sensor_reports_earliest_open_quest(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The next-quest sensor carries the earliest open quest's title in
|
||||
state with the full shape in attributes."""
|
||||
entry, coordinator, (ada, _bo, _cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _seeded_payload()
|
||||
)
|
||||
next_entity = _sensor(hass, ada.id, "next_quest")
|
||||
next_entity = _sensor(hass, ADA, "next_quest")
|
||||
assert next_entity.name == f"NestQuest Ada next quest"
|
||||
assert next_entity.native_value == "Brush teeth"
|
||||
attributes = next_entity.extra_state_attributes
|
||||
assert attributes["title"] == "Brush teeth"
|
||||
assert attributes["window"] == "morning"
|
||||
assert attributes["instance_id"] == _snapshot_child(
|
||||
coordinator, ada.id
|
||||
coordinator, ADA
|
||||
).instances[0].instance_id
|
||||
assert attributes["child_id"] == ada.id
|
||||
assert attributes["child_id"] == ADA
|
||||
|
||||
|
||||
async def test_next_quest_sensor_reports_none_sentinel_when_day_clear(
|
||||
@@ -424,14 +470,11 @@ async def test_next_quest_sensor_reports_none_sentinel_when_day_clear(
|
||||
) -> None:
|
||||
"""A child with every quest done (and a zero-quest child) reports
|
||||
the documented sentinel, never an empty string."""
|
||||
entry, coordinator, (ada, _bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
entry, _coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, _completed_payload()
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
await _complete_first_instance(database, coordinator, ada)
|
||||
await coordinator.async_refresh()
|
||||
assert _sensor(hass, ada.id, "next_quest").native_value == "none"
|
||||
assert _sensor(hass, cory.id, "next_quest").native_value == "none"
|
||||
assert _sensor(hass, ADA, "next_quest").native_value == "none"
|
||||
assert _sensor(hass, CORY, "next_quest").native_value == "none"
|
||||
|
||||
|
||||
async def test_next_quest_state_truncates_over_the_limit(
|
||||
@@ -439,23 +482,15 @@ async def test_next_quest_state_truncates_over_the_limit(
|
||||
) -> None:
|
||||
"""A quest title longer than the state limit is truncated; the
|
||||
attribute keeps the full title."""
|
||||
entry, coordinator, (ada, _bo, _cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
long_title = "A very long quest title. " * 30
|
||||
payload = _payload(
|
||||
[_child(ADA, "Ada", [_instance(7, ADA, title=long_title)])]
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
edit_quest_definition,
|
||||
)
|
||||
|
||||
snapshot_child = _snapshot_child(coordinator, ada.id)
|
||||
await edit_quest_definition(
|
||||
database,
|
||||
snapshot_child.instances[0].definition_id,
|
||||
title="A very long quest title. " * 30,
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
next_entity = _sensor(hass, ada.id, "next_quest")
|
||||
full_title = _snapshot_child(coordinator, ada.id).instances[0].title
|
||||
entry, _coordinator, _client = await _setup_entry(hass, make_entry, payload)
|
||||
next_entity = _sensor(hass, ADA, "next_quest")
|
||||
full_title = _snapshot_child(
|
||||
entry.runtime_data.coordinator, ADA
|
||||
).instances[0].title
|
||||
assert len(full_title) > 255
|
||||
state = next_entity.native_value
|
||||
assert len(state) <= 255
|
||||
@@ -466,19 +501,21 @@ async def test_household_rollups_sum_the_active_children(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Household due/completed equal the sum of the per-child sensors;
|
||||
the cycle-day sensor carries the coordinator's answer."""
|
||||
import datetime as _dt
|
||||
|
||||
from custom_components.nestquest.dao_presence import (
|
||||
PresenceSchedulesDao,
|
||||
the cycle-day sensor carries the coordinator's answer (precomputed
|
||||
by the API, which resolves the schedule engine server-side)."""
|
||||
payload = _payload(
|
||||
[
|
||||
_child(
|
||||
ADA,
|
||||
"Ada",
|
||||
[_instance(7, ADA, state="completed", completed_at=f"{_today_iso()}T07:55:00+00:00", on_time=True)],
|
||||
),
|
||||
_child(BO, "Bo", [_instance(8, BO)]),
|
||||
_child(CORY, "Cory"),
|
||||
]
|
||||
)
|
||||
|
||||
entry, coordinator, (ada, bo, cory) = await _setup_seeded_entry(
|
||||
hass, make_entry
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
await _complete_first_instance(database, coordinator, ada)
|
||||
await coordinator.async_refresh()
|
||||
payload["cycle_day"] = 4
|
||||
entry, coordinator, _client = await _setup_entry(hass, make_entry, payload)
|
||||
|
||||
household_due = hass.entities["nestquest_household_quests_due_today"]
|
||||
household_completed = hass.entities[
|
||||
@@ -486,12 +523,12 @@ async def test_household_rollups_sum_the_active_children(
|
||||
]
|
||||
cycle_day_entity = hass.entities["nestquest_cycle_day"]
|
||||
per_child_due = [
|
||||
_sensor(hass, child.id, "quests_due_today").native_value
|
||||
for child in (ada, bo, cory)
|
||||
_sensor(hass, child_id, "quests_due_today").native_value
|
||||
for child_id in (ADA, BO, CORY)
|
||||
]
|
||||
per_child_completed = [
|
||||
_sensor(hass, child.id, "quests_completed_today").native_value
|
||||
for child in (ada, bo, cory)
|
||||
_sensor(hass, child_id, "quests_completed_today").native_value
|
||||
for child_id in (ADA, BO, CORY)
|
||||
]
|
||||
assert household_due.native_value == sum(per_child_due)
|
||||
assert household_completed.native_value == sum(per_child_completed)
|
||||
@@ -500,16 +537,5 @@ async def test_household_rollups_sum_the_active_children(
|
||||
"NestQuest household quests completed today"
|
||||
)
|
||||
assert cycle_day_entity.name == "NestQuest cycle day"
|
||||
assert cycle_day_entity.native_value == 0, "no schedule anywhere"
|
||||
|
||||
# A schedule on the FIRST active child drives cycle day.
|
||||
today = _dt.date.today()
|
||||
await PresenceSchedulesDao(database).upsert_by_child(
|
||||
ada.id, 2, (today - _dt.timedelta(days=3)).isoformat(),
|
||||
"0,1,2,3,4,5,6|",
|
||||
)
|
||||
await coordinator.async_refresh()
|
||||
assert cycle_day_entity.native_value == 4
|
||||
assert cycle_day_entity.extra_state_attributes["today"] == (
|
||||
today.isoformat()
|
||||
)
|
||||
assert cycle_day_entity.extra_state_attributes["today"] == _today_iso()
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
"""Tests for the Feature 09 admin-only versus open service registry."""
|
||||
from __future__ import annotations
|
||||
|
||||
from custom_components.nestquest.const import (
|
||||
DOMAIN_SERVICES,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
)
|
||||
from custom_components.nestquest.service_policy import (
|
||||
ADMIN_ONLY,
|
||||
OPEN,
|
||||
SERVICE_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_policy_covers_exactly_the_registered_services() -> None:
|
||||
assert frozenset(SERVICE_POLICY) == frozenset(DOMAIN_SERVICES)
|
||||
|
||||
|
||||
def test_only_complete_quest_is_open() -> None:
|
||||
open_services = {
|
||||
name for name, access in SERVICE_POLICY.items() if access == OPEN
|
||||
}
|
||||
assert open_services == {SERVICE_COMPLETE_QUEST}
|
||||
assert all(
|
||||
access == ADMIN_ONLY
|
||||
for name, access in SERVICE_POLICY.items()
|
||||
if name != SERVICE_COMPLETE_QUEST
|
||||
)
|
||||
|
||||
|
||||
def test_policy_values_are_only_open_or_admin_only() -> None:
|
||||
assert set(SERVICE_POLICY.values()) <= {OPEN, ADMIN_ONLY}
|
||||
+40
-472
@@ -1,4 +1,13 @@
|
||||
"""Tests for NestQuest service declarations and domain-global handlers."""
|
||||
"""Tests for NestQuest service declarations and domain-global handlers.
|
||||
|
||||
Since Feature 18 the integration is a client of the NestQuest API
|
||||
service: the only HA service left is the panel completion path
|
||||
(``nestquest.complete_quest``, a proxy to the API's panel complete
|
||||
route). Every admin service was removed — the admin surface is the
|
||||
PWA and the API service's admin routes — so these tests pin the
|
||||
shrunk surface: services.yaml declares nothing else, setup registers
|
||||
nothing else, and no removed admin service name may come back.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
@@ -6,27 +15,16 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import voluptuous as vol
|
||||
from homeassistant.exceptions import HomeAssistantError, Unauthorized
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry, async_unload_entry
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
DOMAIN,
|
||||
DOMAIN_SERVICES,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
SERVICE_CREATE_PRESENCE_OVERRIDE,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
SERVICE_DELETE_PRESENCE_OVERRIDE,
|
||||
SERVICE_EXPORT_HISTORY_CSV,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
SERVICE_REGENERATE,
|
||||
SERVICE_SET_PRESENCE_PATTERN,
|
||||
SERVICE_SET_QUEST_DEFINITION_ACTIVE,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
)
|
||||
from custom_components.nestquest.service_policy import ADMIN_ONLY, SERVICE_POLICY
|
||||
|
||||
SERVICES_PATH = (
|
||||
Path(__file__).parent.parent
|
||||
@@ -35,21 +33,27 @@ SERVICES_PATH = (
|
||||
/ "services.yaml"
|
||||
)
|
||||
|
||||
#: The admin services removed in Feature 18. None of these names may
|
||||
#: be registered as an HA service again — the admin surface is the PWA
|
||||
#: and the API service's admin routes.
|
||||
REMOVED_ADMIN_SERVICES = (
|
||||
"uncomplete_quest",
|
||||
"create_quest_definition",
|
||||
"update_quest_definition",
|
||||
"set_quest_definition_active",
|
||||
"set_presence_pattern",
|
||||
"create_presence_override",
|
||||
"delete_presence_override",
|
||||
"export_history_csv",
|
||||
"manage_child",
|
||||
"regenerate",
|
||||
)
|
||||
|
||||
|
||||
def _wire(entry, registry):
|
||||
return wire_entry_to_registry(entry, registry)
|
||||
|
||||
|
||||
ADMIN_ID = "admin-1"
|
||||
ADMIN_CTX = {"user_id": ADMIN_ID}
|
||||
|
||||
|
||||
def _make_admin_entry(make_entry):
|
||||
from custom_components.nestquest.const import CONF_ADMIN_USER_IDS
|
||||
|
||||
return make_entry(data={CONF_ADMIN_USER_IDS: [ADMIN_ID]})
|
||||
|
||||
|
||||
def _service_section(text: str, name: str) -> str:
|
||||
match = re.search(rf"^{name}:\s*$", text, re.MULTILINE)
|
||||
assert match is not None, f"services.yaml must declare {name!r}"
|
||||
@@ -77,42 +81,33 @@ def test_services_yaml_declares_every_canonical_service() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_services_yaml_declares_regenerate() -> None:
|
||||
def test_services_yaml_no_longer_declares_removed_admin_services() -> None:
|
||||
"""The admin services are gone from the HA service surface."""
|
||||
text = SERVICES_PATH.read_text(encoding="utf-8")
|
||||
assert re.search(r"^regenerate:\s*$", text, re.MULTILINE), (
|
||||
"services.yaml must declare the 'regenerate' service"
|
||||
)
|
||||
for name in REMOVED_ADMIN_SERVICES:
|
||||
assert not re.search(rf"^{name}:\s*$", text, re.MULTILINE), (
|
||||
f"removed admin service {name!r} must not be declared"
|
||||
)
|
||||
|
||||
|
||||
def test_services_yaml_regenerate_has_description_and_no_fields() -> None:
|
||||
"""The regenerate service is documented with a clear description and no
|
||||
required fields (there is no ``fields`` block under it)."""
|
||||
text = SERVICES_PATH.read_text(encoding="utf-8")
|
||||
section = _service_section(text, "regenerate")
|
||||
assert re.search(r"description:", section), (
|
||||
"regenerate must carry a description"
|
||||
)
|
||||
assert "fields:" not in section, (
|
||||
"regenerate declares no required fields"
|
||||
)
|
||||
|
||||
|
||||
def test_services_yaml_other_services_declare_fields() -> None:
|
||||
def test_services_yaml_canonical_services_declare_fields() -> None:
|
||||
text = SERVICES_PATH.read_text(encoding="utf-8")
|
||||
for name in DOMAIN_SERVICES:
|
||||
if name in (SERVICE_REGENERATE, SERVICE_EXPORT_HISTORY_CSV):
|
||||
continue
|
||||
section = _service_section(text, name)
|
||||
assert "fields:" in section, f"{name} must declare fields"
|
||||
|
||||
|
||||
async def test_all_canonical_services_registered_after_setup(
|
||||
async def test_only_complete_quest_registered_after_setup(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Setup registers exactly the panel completion service — and no
|
||||
removed admin service under any name."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
for service in DOMAIN_SERVICES:
|
||||
assert hass.services.has_service(DOMAIN, service), service
|
||||
for service in REMOVED_ADMIN_SERVICES:
|
||||
assert not hass.services.has_service(DOMAIN, service), service
|
||||
|
||||
|
||||
async def test_unload_last_entry_removes_all_services(hass, make_entry) -> None:
|
||||
@@ -138,271 +133,6 @@ async def test_unload_one_of_two_entries_keeps_services(
|
||||
assert not hass.services.has_service(DOMAIN, service), service
|
||||
|
||||
|
||||
async def test_manage_child_create_persists_child(hass, make_entry) -> None:
|
||||
from custom_components.nestquest.children import list_children
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
children = await list_children(entry.runtime_data.database)
|
||||
assert [child.display_name for child in children] == ["Ada"]
|
||||
|
||||
|
||||
async def test_create_and_set_quest_definition_active(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
list_active_definitions,
|
||||
)
|
||||
from custom_components.nestquest.dao_rules import QuestDefinitionsDao
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
child = (await list_children(entry.runtime_data.database))[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [child.id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
active = await list_active_definitions(entry.runtime_data.database)
|
||||
assert len(active) == 1
|
||||
definition_id = active[0].definition.id
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_SET_QUEST_DEFINITION_ACTIVE,
|
||||
{"definition_id": definition_id, "is_active": False},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
assert await list_active_definitions(entry.runtime_data.database) == []
|
||||
stored = await QuestDefinitionsDao(entry.runtime_data.database).get(
|
||||
definition_id
|
||||
)
|
||||
assert stored is not None
|
||||
assert stored.is_active is False
|
||||
|
||||
|
||||
async def test_complete_and_uncomplete_quest_call_business_layer(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.completion import instance_state
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
child = (await list_children(entry.runtime_data.database))[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [child.id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
today = datetime.date.today().isoformat()
|
||||
end = (
|
||||
datetime.date.today() + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
records = await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(child.id, today, end)
|
||||
assert records
|
||||
instance_id = records[0].id
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance_id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
assert (
|
||||
await instance_state(entry.runtime_data.database, instance_id)
|
||||
== "done"
|
||||
)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance_id,
|
||||
"actor": "user",
|
||||
"actor_user_id": ADMIN_ID,
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
assert (
|
||||
await instance_state(entry.runtime_data.database, instance_id)
|
||||
== "open"
|
||||
)
|
||||
|
||||
|
||||
async def test_set_presence_pattern_regenerates_child_instances(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
child = (await list_children(entry.runtime_data.database))[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [child.id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
today = datetime.date.today().isoformat()
|
||||
end = (
|
||||
datetime.date.today() + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
dao = QuestInstancesDao(entry.runtime_data.database)
|
||||
assert await dao.list_by_date_range(child.id, today, end)
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_SET_PRESENCE_PATTERN,
|
||||
{
|
||||
"child_id": child.id,
|
||||
"cycle_length_weeks": 1,
|
||||
"anchor_date": today,
|
||||
"pattern": {0: []},
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
assert await dao.list_by_date_range(child.id, today, end) == []
|
||||
|
||||
|
||||
async def test_presence_override_create_and_delete_regenerate(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.dao_presence import PresenceOverridesDao
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
child = (await list_children(entry.runtime_data.database))[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [child.id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
today = datetime.date.today()
|
||||
end = today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
dao = QuestInstancesDao(entry.runtime_data.database)
|
||||
before = await dao.list_by_date_range(
|
||||
child.id, today.isoformat(), end.isoformat()
|
||||
)
|
||||
assert before
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_PRESENCE_OVERRIDE,
|
||||
{
|
||||
"child_id": child.id,
|
||||
"start_date": today.isoformat(),
|
||||
"end_date": end.isoformat(),
|
||||
"is_present": False,
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
assert (
|
||||
await dao.list_by_date_range(
|
||||
child.id, today.isoformat(), end.isoformat()
|
||||
)
|
||||
== []
|
||||
)
|
||||
override = (
|
||||
await PresenceOverridesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_child_and_range(
|
||||
child.id, today.isoformat(), end.isoformat()
|
||||
)
|
||||
)[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_DELETE_PRESENCE_OVERRIDE,
|
||||
{"override_id": override.id},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
after = await dao.list_by_date_range(
|
||||
child.id, today.isoformat(), end.isoformat()
|
||||
)
|
||||
assert len(after) == len(before)
|
||||
|
||||
|
||||
async def test_export_history_csv_raises_home_assistant_error(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(HomeAssistantError, match="Feature 13"):
|
||||
await hass.services.call(
|
||||
DOMAIN, SERVICE_EXPORT_HISTORY_CSV, context=ADMIN_CTX
|
||||
)
|
||||
|
||||
|
||||
async def test_invalid_schema_data_surfaces_as_error(hass, make_entry) -> None:
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
@@ -414,168 +144,6 @@ async def test_invalid_schema_data_surfaces_as_error(hass, make_entry) -> None:
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": True, "actor": "panel", "actor_child_id": 1},
|
||||
)
|
||||
with pytest.raises((vol.Invalid, ValueError, HomeAssistantError)):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create"},
|
||||
)
|
||||
|
||||
|
||||
async def test_admin_only_service_denies_non_admin(hass, make_entry) -> None:
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context={"user_id": "kiosk-panel"},
|
||||
)
|
||||
|
||||
|
||||
async def test_admin_only_service_denies_missing_user_context(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
)
|
||||
|
||||
|
||||
async def test_admin_only_service_denies_admin_on_empty_allowlist(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""Even the allowlisted id is denied when the allowlist is empty."""
|
||||
entry = _wire(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
|
||||
|
||||
async def test_unauthorized_is_raised_before_handler_runs(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
from custom_components.nestquest.children import list_children
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context={"user_id": "kiosk-panel"},
|
||||
)
|
||||
assert await list_children(entry.runtime_data.database) == []
|
||||
|
||||
|
||||
_MINIMAL_PAYLOADS = {
|
||||
"uncomplete_quest": {"instance_id": 1, "actor": "user"},
|
||||
"create_quest_definition": {
|
||||
"title": "T",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [1],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
"update_quest_definition": {"definition_id": 1},
|
||||
"set_quest_definition_active": {"definition_id": 1, "is_active": True},
|
||||
"set_presence_pattern": {
|
||||
"child_id": 1,
|
||||
"cycle_length_weeks": 1,
|
||||
"anchor_date": "2026-09-19",
|
||||
"pattern": {0: [0]},
|
||||
},
|
||||
"create_presence_override": {
|
||||
"child_id": 1,
|
||||
"start_date": "2026-09-19",
|
||||
"end_date": "2026-09-19",
|
||||
"is_present": False,
|
||||
},
|
||||
"delete_presence_override": {"override_id": 1},
|
||||
"export_history_csv": {},
|
||||
"manage_child": {"action": "create", "display_name": "Ada"},
|
||||
"regenerate": {},
|
||||
}
|
||||
|
||||
_ADMIN_ONLY_SERVICES = [
|
||||
name for name, policy in SERVICE_POLICY.items() if policy == ADMIN_ONLY
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("service", _ADMIN_ONLY_SERVICES)
|
||||
async def test_admin_only_service_fails_closed_without_user_context(
|
||||
hass, make_entry, service
|
||||
) -> None:
|
||||
"""A call with no user_id is denied on every admin-only service."""
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
with pytest.raises(Unauthorized):
|
||||
await hass.services.call(
|
||||
DOMAIN, service, dict(_MINIMAL_PAYLOADS[service])
|
||||
)
|
||||
|
||||
|
||||
async def test_complete_quest_proceeds_without_user_context(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The open service needs no user context: the kiosk panel taps a
|
||||
child profile and the call goes through with no HA user at all."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.children import list_children
|
||||
from custom_components.nestquest.completion import instance_state
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
|
||||
entry = _wire(_make_admin_entry(make_entry), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_MANAGE_CHILD,
|
||||
{"action": "create", "display_name": "Ada"},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
child = (await list_children(entry.runtime_data.database))[0]
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_CREATE_QUEST_DEFINITION,
|
||||
{
|
||||
"title": "Brush teeth",
|
||||
"rule": {"rule_type": "daily"},
|
||||
"assignee_child_ids": [child.id],
|
||||
"windows": ["morning"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
await hass.services.call(DOMAIN, SERVICE_REGENERATE, context=ADMIN_CTX)
|
||||
today = datetime.date.today().isoformat()
|
||||
end = (
|
||||
datetime.date.today() + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
).isoformat()
|
||||
instance_id = (
|
||||
await QuestInstancesDao(
|
||||
entry.runtime_data.database
|
||||
).list_by_date_range(child.id, today, end)
|
||||
)[0].id
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": instance_id, "actor": "panel", "actor_child_id": child.id},
|
||||
)
|
||||
assert (
|
||||
await instance_state(entry.runtime_data.database, instance_id)
|
||||
== "done"
|
||||
)
|
||||
|
||||
|
||||
async def test_scheduled_internals_never_call_the_service_layer(
|
||||
@@ -590,4 +158,4 @@ async def test_scheduled_internals_never_call_the_service_layer(
|
||||
assert "hass.services.call" not in source, (
|
||||
"scheduled internals must call the materialization directly, "
|
||||
"never through hass.services.call"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,619 @@
|
||||
"""Tests for the panel SSE subscription (HA-bus re-firing task).
|
||||
|
||||
Three layers are exercised, all STUB-driven — no network, no aiohttp,
|
||||
no real Home Assistant:
|
||||
|
||||
- The API client's ``stream_events`` (transport stub): what goes on
|
||||
the wire (GET, the events URL, the Bearer header), SSE frame
|
||||
parsing (``event:``/``data:`` lines, blank-line frame ends, chunk
|
||||
boundaries, multi-line data), and every failure mode (non-2xx,
|
||||
connection failure, mid-stream drop, malformed frame) surfacing as
|
||||
the typed :class:`NestQuestApiError`; cancellation closes the
|
||||
stream cleanly.
|
||||
- The :class:`~custom_components.nestquest.sse.NestQuestEventStream`
|
||||
subscription manager (duck-typed stream client): the four documented
|
||||
transition events (design/ENTITIES-AND-SERVICES.md §3, exactly as
|
||||
``tests/test_api_sse.py`` observes them on the API side) fire on
|
||||
``hass.bus`` with the documented payload fields; ``stop()`` cancels
|
||||
the task so no frame fires afterwards; a stream failure reconnects
|
||||
with a bounded, reset-on-success backoff and never crashes the
|
||||
task.
|
||||
- The integration wiring: setup starts the stream alongside the
|
||||
runtime record, unload tears it down (no firing afterwards, task
|
||||
cancelled), and an entry whose client has no stream surface (the
|
||||
unconfigured-token stub, the test snapshot client) starts none.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from conftest import set_coordinator_client, wire_entry_to_registry
|
||||
|
||||
import custom_components.nestquest as nq_integration
|
||||
from custom_components.nestquest import (
|
||||
async_setup_entry,
|
||||
async_unload_entry,
|
||||
)
|
||||
from custom_components.nestquest import sse as sse_module
|
||||
from custom_components.nestquest.api_client import (
|
||||
NestQuestApiClient,
|
||||
NestQuestApiError,
|
||||
)
|
||||
from custom_components.nestquest.sse import NestQuestEventStream
|
||||
|
||||
BASE_URL = "http://api.test:8000"
|
||||
TOKEN = "test-panel-token"
|
||||
|
||||
# Captured BEFORE any test patches asyncio.sleep (the reconnect test
|
||||
# swaps in a recording fake; this reference keeps helpers sleeping for
|
||||
# real regardless).
|
||||
_REAL_SLEEP = asyncio.sleep
|
||||
|
||||
#: The four documented transition events with their documented payload
|
||||
#: fields — the exact shapes the API side streams (test_api_sse.py).
|
||||
DOCUMENTED_FRAMES = (
|
||||
(
|
||||
"nestquest_quest_completed",
|
||||
{
|
||||
"child_id": 1,
|
||||
"child_name": "Ada",
|
||||
"instance_id": 7,
|
||||
"quest_title": "Pack bag",
|
||||
"window": "morning",
|
||||
"due_date": "2026-09-23",
|
||||
"due_time": "10:00",
|
||||
"occurred_at": "2026-09-23T12:00:00+00:00",
|
||||
"was_on_time": False,
|
||||
},
|
||||
),
|
||||
(
|
||||
"nestquest_quest_uncompleted",
|
||||
{
|
||||
"child_id": 1,
|
||||
"child_name": "Ada",
|
||||
"instance_id": 7,
|
||||
"quest_title": "Pack bag",
|
||||
"window": "morning",
|
||||
"due_date": "2026-09-23",
|
||||
"due_time": "10:00",
|
||||
"occurred_at": "2026-09-23T12:00:00+00:00",
|
||||
},
|
||||
),
|
||||
(
|
||||
"nestquest_quest_missed",
|
||||
{
|
||||
"child_id": 1,
|
||||
"child_name": "Ada",
|
||||
"instance_id": 9,
|
||||
"quest_title": "Stale chore",
|
||||
"window": "morning",
|
||||
"due_date": "2026-09-23",
|
||||
"due_time": "09:00",
|
||||
"occurred_at": "2026-09-23T23:30:00+00:00",
|
||||
},
|
||||
),
|
||||
(
|
||||
"nestquest_child_day_complete",
|
||||
{
|
||||
"child_id": 1,
|
||||
"child_name": "Ada",
|
||||
"quests_due": 1,
|
||||
"quests_completed": 1,
|
||||
"occurred_at": "2026-09-23T12:00:00+00:00",
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
#: The documented payload field sets per event type.
|
||||
DOCUMENTED_FIELDS = {
|
||||
"nestquest_quest_completed": {
|
||||
"child_id",
|
||||
"child_name",
|
||||
"instance_id",
|
||||
"quest_title",
|
||||
"window",
|
||||
"due_date",
|
||||
"due_time",
|
||||
"occurred_at",
|
||||
"was_on_time",
|
||||
},
|
||||
"nestquest_quest_uncompleted": {
|
||||
"child_id",
|
||||
"child_name",
|
||||
"instance_id",
|
||||
"quest_title",
|
||||
"window",
|
||||
"due_date",
|
||||
"due_time",
|
||||
"occurred_at",
|
||||
},
|
||||
"nestquest_quest_missed": {
|
||||
"child_id",
|
||||
"child_name",
|
||||
"instance_id",
|
||||
"quest_title",
|
||||
"window",
|
||||
"due_date",
|
||||
"due_time",
|
||||
"occurred_at",
|
||||
},
|
||||
"nestquest_child_day_complete": {
|
||||
"child_id",
|
||||
"child_name",
|
||||
"quests_due",
|
||||
"quests_completed",
|
||||
"occurred_at",
|
||||
},
|
||||
}
|
||||
|
||||
#: A minimal panel snapshot payload for the full-setup wiring tests
|
||||
#: (the shape ``snapshot_from_api_payload`` consumes; no children).
|
||||
MINIMAL_SNAPSHOT = {"today_iso": "2026-09-23", "cycle_day": 1, "children": []}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stub transports and stream clients (no network anywhere)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _StreamingResponse:
|
||||
"""A fake aiohttp streaming response: ``status`` + chunk iteration.
|
||||
|
||||
``chunks`` are the body pieces the stream yields in order; a chunk
|
||||
may be an exception, raised when the iteration reaches it (a
|
||||
mid-stream transport drop). ``hold_open`` keeps the stream open
|
||||
forever after the chunks run out, for cancellation tests.
|
||||
"""
|
||||
|
||||
def __init__(self, status: int, chunks, *, hold_open: bool = False) -> None:
|
||||
self.status = status
|
||||
self._chunks = list(chunks)
|
||||
self._hold_open = hold_open
|
||||
self.closed = False
|
||||
|
||||
def __aiter__(self):
|
||||
return self._iterate()
|
||||
|
||||
async def _iterate(self):
|
||||
for chunk in self._chunks:
|
||||
if isinstance(chunk, BaseException):
|
||||
raise chunk
|
||||
yield chunk
|
||||
if self._hold_open:
|
||||
await asyncio.Event().wait() # cancelled, never ends
|
||||
|
||||
|
||||
class _RequestContext:
|
||||
"""Async context manager mirroring ``session.request(...)``'s return.
|
||||
|
||||
Entering performs the request (a scripted transport error raises
|
||||
THERE, where aiohttp's connector raises on a refused connection);
|
||||
exiting marks the response closed, so tests can assert the stream
|
||||
was released.
|
||||
"""
|
||||
|
||||
def __init__(self, response, error) -> None:
|
||||
self._response = response
|
||||
self._error = error
|
||||
|
||||
async def __aenter__(self):
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._response
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> bool:
|
||||
if self._response is not None:
|
||||
self._response.closed = True
|
||||
return False
|
||||
|
||||
|
||||
class _StreamTransport:
|
||||
"""A no-network stand-in for aiohttp's ``ClientSession``.
|
||||
|
||||
Records every ``request(...)`` call and answers from a scripted
|
||||
queue of outcomes (a :class:`_StreamingResponse` or an exception
|
||||
per attempt, consumed in order).
|
||||
"""
|
||||
|
||||
def __init__(self, *outcomes) -> None:
|
||||
self.calls: list[dict] = []
|
||||
self._outcomes = list(outcomes)
|
||||
|
||||
def request(self, method: str, url: str, **kwargs):
|
||||
self.calls.append(
|
||||
{
|
||||
"method": method,
|
||||
"url": url,
|
||||
"headers": kwargs.get("headers"),
|
||||
"json": kwargs.get("json"),
|
||||
}
|
||||
)
|
||||
outcome = self._outcomes.pop(0)
|
||||
if isinstance(outcome, BaseException):
|
||||
return _RequestContext(None, outcome)
|
||||
return _RequestContext(outcome, None)
|
||||
|
||||
|
||||
def make_stream_client(transport) -> NestQuestApiClient:
|
||||
"""Build a client over the streaming stub with the test credentials."""
|
||||
return NestQuestApiClient(BASE_URL, TOKEN, transport)
|
||||
|
||||
|
||||
def _frame_text(event_type: str, payload: dict) -> str:
|
||||
"""One documented SSE frame: event line, data line, blank line."""
|
||||
return f"event: {event_type}\ndata: {json.dumps(payload)}\n\n"
|
||||
|
||||
|
||||
class _ScriptedStreamClient:
|
||||
"""Duck-typed API client: one scripted stream per connection.
|
||||
|
||||
``script`` holds generator FACTORIES — ``stream_events()`` pops the
|
||||
next one and returns its async generator, so a test scripts exactly
|
||||
what each connection attempt yields (or how it fails).
|
||||
"""
|
||||
|
||||
def __init__(self, script) -> None:
|
||||
self._script = list(script)
|
||||
self.calls = 0
|
||||
|
||||
def stream_events(self):
|
||||
self.calls += 1
|
||||
return self._script.pop(0)()
|
||||
|
||||
|
||||
def _frames(*frames):
|
||||
"""A live stream factory: yields ``frames``, then stays open."""
|
||||
|
||||
def _factory():
|
||||
async def _gen():
|
||||
for frame in frames:
|
||||
yield frame
|
||||
await asyncio.Event().wait() # cancelled, never ends
|
||||
|
||||
return _gen()
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
def _fail(error: BaseException):
|
||||
"""A stream factory that fails before yielding anything."""
|
||||
|
||||
def _factory():
|
||||
async def _gen():
|
||||
raise error
|
||||
yield # noqa: unreachable — makes _gen an async generator
|
||||
|
||||
return _gen()
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
def _drop_after(error: BaseException, *frames):
|
||||
"""A stream factory that yields ``frames`` then drops mid-stream."""
|
||||
|
||||
def _factory():
|
||||
async def _gen():
|
||||
for frame in frames:
|
||||
yield frame
|
||||
raise error
|
||||
|
||||
return _gen()
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
async def _wait_until(predicate, *, timeout: float = 2.0) -> None:
|
||||
"""Poll ``predicate`` until true or the deadline passes."""
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout
|
||||
while not predicate():
|
||||
if loop.time() > deadline:
|
||||
raise AssertionError("condition not met within the deadline")
|
||||
await _REAL_SLEEP(0.01)
|
||||
|
||||
|
||||
def make_manager(
|
||||
hass, client, *, min_backoff: float = 0.01, max_backoff: float = 0.05
|
||||
) -> NestQuestEventStream:
|
||||
"""A manager with fast (test-sized) backoff bounds."""
|
||||
return NestQuestEventStream(
|
||||
hass,
|
||||
client,
|
||||
reconnect_min_seconds=min_backoff,
|
||||
reconnect_max_seconds=max_backoff,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The client's stream_events: parsing and typed failures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_stream_events_yields_documented_frames_and_sends_bearer() -> None:
|
||||
"""All four documented frames parse, with the Bearer GET on the wire."""
|
||||
body = "".join(
|
||||
_frame_text(event_type, payload)
|
||||
for event_type, payload in DOCUMENTED_FRAMES
|
||||
)
|
||||
transport = _StreamTransport(_StreamingResponse(200, [body]))
|
||||
client = make_stream_client(transport)
|
||||
|
||||
frames = [frame async for frame in client.stream_events()]
|
||||
|
||||
assert frames == list(DOCUMENTED_FRAMES)
|
||||
call = transport.calls[0]
|
||||
assert call["method"] == "GET"
|
||||
assert call["url"] == f"{BASE_URL}/api/v1/panel/events"
|
||||
assert call["headers"] == {"Authorization": f"Bearer {TOKEN}"}
|
||||
assert call["json"] is None
|
||||
|
||||
|
||||
async def test_stream_events_buffers_lines_across_chunks_and_joins_data() -> None:
|
||||
"""Chunk-split lines parse, and multi-line data joins per SSE rules."""
|
||||
first_type, first_payload = DOCUMENTED_FRAMES[0]
|
||||
# The first frame is cut MID-LINE across two chunks; the second
|
||||
# frame spreads its JSON over two ``data:`` lines.
|
||||
chunks = [
|
||||
f"event: {first_type}\nda",
|
||||
f"ta: {json.dumps(first_payload)}\n\nevent: "
|
||||
f"{DOCUMENTED_FRAMES[1][0]}\n",
|
||||
f'data: {{"extra":\ndata: true}}\n\n',
|
||||
]
|
||||
transport = _StreamTransport(_StreamingResponse(200, chunks))
|
||||
client = make_stream_client(transport)
|
||||
|
||||
frames = [frame async for frame in client.stream_events()]
|
||||
|
||||
assert len(frames) == 2
|
||||
assert frames[0] == DOCUMENTED_FRAMES[0]
|
||||
# The split-out frame's data spread over two ``data:`` lines joins
|
||||
# with a newline (the SSE standard) and parses as one JSON body.
|
||||
assert frames[1] == (DOCUMENTED_FRAMES[1][0], {"extra": True})
|
||||
|
||||
|
||||
async def test_stream_events_non_2xx_raises_typed_and_closes() -> None:
|
||||
"""A wrong token (401) is typed with its status; no stream is read."""
|
||||
response = _StreamingResponse(401, ["event: x\ndata: {}\n\n"])
|
||||
transport = _StreamTransport(response)
|
||||
client = make_stream_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
async for _ in client.stream_events():
|
||||
pass
|
||||
|
||||
assert excinfo.value.status == 401
|
||||
assert not excinfo.value.is_transport_error
|
||||
assert TOKEN not in str(excinfo.value)
|
||||
assert response.closed
|
||||
|
||||
|
||||
async def test_stream_events_connection_failure_raises_typed_transport_error() -> None:
|
||||
"""A failure before any response is a typed transport error."""
|
||||
transport = _StreamTransport(OSError("connection refused"))
|
||||
client = make_stream_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
async for _ in client.stream_events():
|
||||
pass
|
||||
|
||||
assert excinfo.value.status is None
|
||||
assert excinfo.value.is_transport_error
|
||||
assert isinstance(excinfo.value.__cause__, OSError)
|
||||
|
||||
|
||||
async def test_stream_events_midstream_drop_raises_typed() -> None:
|
||||
"""A transport error mid-stream is typed, so the consumer reconnects."""
|
||||
response = _StreamingResponse(
|
||||
200,
|
||||
[_frame_text(DOCUMENTED_FRAMES[0][0], DOCUMENTED_FRAMES[0][1]), OSError("reset")],
|
||||
)
|
||||
transport = _StreamTransport(response)
|
||||
client = make_stream_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
async for _ in client.stream_events():
|
||||
pass
|
||||
|
||||
assert excinfo.value.status is None
|
||||
assert excinfo.value.is_transport_error
|
||||
assert isinstance(excinfo.value.__cause__, OSError)
|
||||
assert response.closed
|
||||
|
||||
|
||||
async def test_stream_events_stops_cleanly_on_cancellation() -> None:
|
||||
"""Closing the generator (the consumer task's cancellation) stops
|
||||
cleanly: no error, the underlying response is closed, and nothing
|
||||
further is yielded."""
|
||||
response = _StreamingResponse(
|
||||
200,
|
||||
[_frame_text(DOCUMENTED_FRAMES[0][0], DOCUMENTED_FRAMES[0][1])],
|
||||
hold_open=True,
|
||||
)
|
||||
transport = _StreamTransport(response)
|
||||
client = make_stream_client(transport)
|
||||
|
||||
generator = client.stream_events()
|
||||
first = await asyncio.wait_for(generator.__anext__(), timeout=2.0)
|
||||
assert first == DOCUMENTED_FRAMES[0]
|
||||
|
||||
await asyncio.wait_for(generator.aclose(), timeout=2.0)
|
||||
assert response.closed
|
||||
|
||||
|
||||
async def test_stream_events_malformed_frame_raises_typed() -> None:
|
||||
"""A frame whose data is not JSON is a typed protocol failure."""
|
||||
response = _StreamingResponse(
|
||||
200, ["event: nestquest_quest_completed\ndata: not-json\n\n"]
|
||||
)
|
||||
transport = _StreamTransport(response)
|
||||
client = make_stream_client(transport)
|
||||
|
||||
with pytest.raises(NestQuestApiError) as excinfo:
|
||||
async for _ in client.stream_events():
|
||||
pass
|
||||
|
||||
assert excinfo.value.status == 200
|
||||
assert response.closed
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The subscription manager: firing, teardown, reconnect
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_manager_fires_documented_frames_on_ha_bus(hass) -> None:
|
||||
"""Every documented transition fires on hass.bus with its payload."""
|
||||
client = _ScriptedStreamClient([_frames(*DOCUMENTED_FRAMES)])
|
||||
manager = make_manager(hass, client)
|
||||
manager.start()
|
||||
try:
|
||||
await _wait_until(lambda: len(hass.bus.events) >= 4)
|
||||
assert hass.bus.events == [tuple(f) for f in DOCUMENTED_FRAMES]
|
||||
for event_type, payload in DOCUMENTED_FRAMES:
|
||||
fired = hass.bus.fired(event_type)
|
||||
assert fired, f"{event_type} never fired"
|
||||
assert set(fired[-1]) == DOCUMENTED_FIELDS[event_type]
|
||||
finally:
|
||||
await manager.stop()
|
||||
|
||||
|
||||
async def test_manager_stop_cancels_task_and_blocks_later_frames(hass) -> None:
|
||||
"""stop() cancels and awaits the task: no frame fires afterwards,
|
||||
even when the (dead) stream is later offered more data."""
|
||||
stream_release = asyncio.Event()
|
||||
first_type, first_payload = DOCUMENTED_FRAMES[0]
|
||||
later_type, later_payload = DOCUMENTED_FRAMES[1]
|
||||
|
||||
def _factory():
|
||||
async def _gen():
|
||||
yield (first_type, dict(first_payload))
|
||||
await stream_release.wait()
|
||||
yield (later_type, dict(later_payload))
|
||||
|
||||
return _gen()
|
||||
|
||||
client = _ScriptedStreamClient([_factory])
|
||||
manager = make_manager(hass, client)
|
||||
manager.start()
|
||||
await _wait_until(lambda: len(hass.bus.events) == 1)
|
||||
|
||||
task = manager.task
|
||||
await manager.stop()
|
||||
assert task.cancelled()
|
||||
assert manager.task is None
|
||||
|
||||
# Offer the stream more data after teardown: nothing fires.
|
||||
stream_release.set()
|
||||
await _REAL_SLEEP(0.05)
|
||||
assert hass.bus.events == [(first_type, dict(first_payload))]
|
||||
|
||||
|
||||
async def test_manager_reconnects_with_bounded_backoff(hass, monkeypatch) -> None:
|
||||
"""A failed stream reconnects with a bounded, reset-on-success
|
||||
backoff and never crashes the task."""
|
||||
delays: list[float] = []
|
||||
|
||||
async def fake_sleep(delay, *args, **kwargs):
|
||||
delays.append(delay)
|
||||
await _REAL_SLEEP(0)
|
||||
|
||||
monkeypatch.setattr(sse_module.asyncio, "sleep", fake_sleep)
|
||||
|
||||
stream_error = ConnectionError("stream reset")
|
||||
client = _ScriptedStreamClient(
|
||||
[
|
||||
_fail(RuntimeError("api down")),
|
||||
_fail(RuntimeError("api down")),
|
||||
_fail(RuntimeError("api down")),
|
||||
_fail(RuntimeError("api down")),
|
||||
_drop_after(stream_error, DOCUMENTED_FRAMES[0]),
|
||||
_frames(*DOCUMENTED_FRAMES),
|
||||
]
|
||||
)
|
||||
manager = make_manager(hass, client, min_backoff=0.05, max_backoff=0.2)
|
||||
manager.start()
|
||||
try:
|
||||
await _wait_until(lambda: len(hass.bus.events) >= 5)
|
||||
# 5s → 10s → 20s (cap) → 20s (cap), then a frame on a healthy
|
||||
# stream reset it to the 5s minimum for the next failure.
|
||||
assert delays == [0.05, 0.1, 0.2, 0.2, 0.05]
|
||||
assert hass.bus.events == [
|
||||
tuple(DOCUMENTED_FRAMES[0]),
|
||||
*[tuple(f) for f in DOCUMENTED_FRAMES],
|
||||
]
|
||||
# The task is still alive (subscribed and idle), not crashed.
|
||||
assert manager.task is not None and not manager.task.done()
|
||||
finally:
|
||||
await manager.stop()
|
||||
|
||||
|
||||
def test_manager_rejects_invalid_backoff_bounds(hass) -> None:
|
||||
"""Non-positive or inverted backoff bounds fail at construction."""
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestEventStream(hass, object(), reconnect_min_seconds=0)
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestEventStream(hass, object(), reconnect_min_seconds=-1)
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestEventStream(hass, object(), reconnect_max_seconds=0)
|
||||
with pytest.raises(ValueError):
|
||||
NestQuestEventStream(hass, object(), reconnect_min_seconds=10.0, reconnect_max_seconds=5.0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration wiring: setup starts the stream, unload stops it
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _SetupClient:
|
||||
"""Client for full-setup wiring tests: scripted snapshot + stream."""
|
||||
|
||||
def __init__(self, script) -> None:
|
||||
self._script = list(script)
|
||||
self.stream_calls = 0
|
||||
|
||||
async def get_snapshot(self) -> dict:
|
||||
return dict(MINIMAL_SNAPSHOT)
|
||||
|
||||
def stream_events(self):
|
||||
self.stream_calls += 1
|
||||
return self._script.pop(0)()
|
||||
|
||||
|
||||
async def test_setup_starts_stream_and_unload_stops_it(hass, make_entry) -> None:
|
||||
"""Setup starts the subscription alongside the runtime record; unload
|
||||
tears the task down so no frame fires afterwards."""
|
||||
client = _SetupClient([_frames(*DOCUMENTED_FRAMES)])
|
||||
set_coordinator_client(make_entry(), client)
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await nq_integration.async_setup_entry(hass, entry) is True
|
||||
|
||||
runtime = entry.runtime_data
|
||||
assert runtime.event_stream is not None
|
||||
await _wait_until(lambda: len(hass.bus.events) >= 4)
|
||||
assert [event for event, _ in hass.bus.events] == [
|
||||
frame[0] for frame in DOCUMENTED_FRAMES
|
||||
]
|
||||
|
||||
task = runtime.event_stream.task
|
||||
assert await nq_integration.async_unload_entry(hass, entry) is True
|
||||
assert task.cancelled()
|
||||
assert runtime.event_stream.task is None
|
||||
|
||||
events_after_unload = len(hass.bus.events)
|
||||
await _REAL_SLEEP(0.05)
|
||||
assert len(hass.bus.events) == events_after_unload
|
||||
|
||||
|
||||
async def test_setup_without_stream_surface_starts_no_subscription(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""An entry whose API client has no stream surface (the local-snapshot
|
||||
stub the harness installs, like the unconfigured-token stub in
|
||||
production) starts NO subscription — and setup still succeeds."""
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await nq_integration.async_setup_entry(hass, entry) is True
|
||||
assert entry.runtime_data.event_stream is None
|
||||
assert await nq_integration.async_unload_entry(hass, entry) is True
|
||||
@@ -1,472 +0,0 @@
|
||||
"""Tests for startup handling of missing, valid, and corrupt databases."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import sqlite3
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from conftest import make_config_entry
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
|
||||
from custom_components.nestquest import (
|
||||
_async_open_database,
|
||||
_is_corruption_error,
|
||||
async_setup_entry,
|
||||
async_unload_entry,
|
||||
)
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import (
|
||||
MIGRATIONS,
|
||||
VERSION_TABLE,
|
||||
apply_migrations,
|
||||
)
|
||||
from tests.test_lifecycle import _wire
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.new_event_loop().run_until_complete(coro)
|
||||
|
||||
|
||||
def _make_hass_mock():
|
||||
hass = MagicMock()
|
||||
hass.async_add_executor_job = AsyncMock(side_effect=(lambda fn, *a: fn(*a)))
|
||||
return hass
|
||||
|
||||
|
||||
def _open_db(path) -> NestQuestDatabase:
|
||||
database = NestQuestDatabase(_make_hass_mock().async_add_executor_job)
|
||||
_run(database.open(path))
|
||||
return database
|
||||
|
||||
|
||||
async def _avalid_database(path) -> None:
|
||||
"""Create a valid, migrated NestQuest database file (async, on the
|
||||
running loop, for use inside pytest-asyncio tests)."""
|
||||
database = NestQuestDatabase(_make_hass_mock().async_add_executor_job)
|
||||
await database.open(path)
|
||||
try:
|
||||
await apply_migrations(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
def _valid_database(path) -> None:
|
||||
"""Create a valid, migrated NestQuest database file at ``path``."""
|
||||
database = _open_db(path)
|
||||
try:
|
||||
_run(apply_migrations(database))
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def _truncated_database(path) -> None:
|
||||
"""Create a deliberately truncated (corrupt) database file.
|
||||
|
||||
A valid database is written, closed, then cut short mid-header:
|
||||
opening it reports 'file is not a database' — exactly what an
|
||||
interrupted write or failing disk leaves behind.
|
||||
"""
|
||||
_valid_database(path)
|
||||
data = path.read_bytes()
|
||||
assert len(data) > 64, "valid database must exist before truncation"
|
||||
path.write_bytes(data[: len(data) // 2])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Corruption classification
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_is_corruption_error_matches_sqlite_spellings() -> None:
|
||||
assert _is_corruption_error(
|
||||
sqlite3.DatabaseError("file is not a database")
|
||||
)
|
||||
assert _is_corruption_error(
|
||||
sqlite3.DatabaseError("file is not a database".upper())
|
||||
)
|
||||
assert _is_corruption_error(
|
||||
sqlite3.DatabaseError("file is encrypted or malformed")
|
||||
)
|
||||
assert _is_corruption_error(
|
||||
sqlite3.OperationalError("file is not a database")
|
||||
)
|
||||
|
||||
|
||||
def test_is_corruption_error_rejects_other_failures() -> None:
|
||||
assert not _is_corruption_error(
|
||||
sqlite3.OperationalError("database is locked")
|
||||
)
|
||||
assert not _is_corruption_error(
|
||||
sqlite3.IntegrityError("NOT NULL constraint failed")
|
||||
)
|
||||
assert not _is_corruption_error(RuntimeError("boom"))
|
||||
assert not _is_corruption_error(ValueError("nope"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Startup: three cases through _async_open_database
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_missing_file_opens_fresh(tmp_path) -> None:
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
assert not db_path.exists()
|
||||
database = _run(_async_open_database(_make_hass_mock(), db_path))
|
||||
try:
|
||||
# The file was created fresh and migrations stamped the
|
||||
# latest schema version.
|
||||
assert db_path.exists()
|
||||
row = _run(
|
||||
database.fetch_one(f"SELECT version FROM {VERSION_TABLE}")
|
||||
)
|
||||
assert row == (len(MIGRATIONS),)
|
||||
finally:
|
||||
_run(database.close())
|
||||
|
||||
|
||||
def test_zero_byte_existing_file_is_corrupt_and_untouched(tmp_path) -> None:
|
||||
"""A zero-byte file is neither missing nor valid: it is corrupt.
|
||||
|
||||
The leave-untouched contract applies — startup refuses (retryable)
|
||||
rather than silently initializing over whatever interrupted write
|
||||
left the empty file, and the file stays exactly zero bytes.
|
||||
"""
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
db_path.write_bytes(b"")
|
||||
with pytest.raises(ConfigEntryNotReady) as excinfo:
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
assert db_path.stat().st_size == 0
|
||||
assert isinstance(excinfo.value.__cause__, sqlite3.DatabaseError)
|
||||
# No sidecars appeared from the refusal path.
|
||||
assert not (tmp_path / "nestquest.db-wal").exists()
|
||||
assert not (tmp_path / "nestquest.db-shm").exists()
|
||||
|
||||
|
||||
def test_valid_file_opens_and_migrations_noop(tmp_path) -> None:
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
_valid_database(db_path)
|
||||
digest_before = hashlib.sha256(db_path.read_bytes()).hexdigest()
|
||||
database = _run(_async_open_database(_make_hass_mock(), db_path))
|
||||
try:
|
||||
row = _run(
|
||||
database.fetch_one(f"SELECT version FROM {VERSION_TABLE}")
|
||||
)
|
||||
assert row == (len(MIGRATIONS),)
|
||||
finally:
|
||||
_run(database.close())
|
||||
# Opening a valid file must not rewrite it (the no-op path).
|
||||
assert (
|
||||
hashlib.sha256(db_path.read_bytes()).hexdigest() == digest_before
|
||||
)
|
||||
|
||||
|
||||
def test_corrupt_file_raises_not_ready_and_leaves_file_untouched(
|
||||
tmp_path, caplog
|
||||
) -> None:
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
_truncated_database(db_path)
|
||||
corrupt_bytes = db_path.read_bytes()
|
||||
digest = hashlib.sha256(corrupt_bytes).hexdigest()
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady) as excinfo:
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
|
||||
# The file is byte-identical: the owner can restore/inspect it.
|
||||
assert hashlib.sha256(db_path.read_bytes()).hexdigest() == digest
|
||||
assert len(db_path.read_bytes()) == len(corrupt_bytes)
|
||||
# The original error is preserved and the log names the path.
|
||||
assert isinstance(excinfo.value.__cause__, sqlite3.DatabaseError)
|
||||
assert any(
|
||||
"corrupt" in record.getMessage().lower()
|
||||
and str(db_path) in record.getMessage()
|
||||
for record in caplog.records
|
||||
if record.levelname == "ERROR"
|
||||
), "the error log must name the corrupt path"
|
||||
|
||||
|
||||
def test_corrupt_file_raises_not_ready_never_raw_error(tmp_path) -> None:
|
||||
"""The corrupt case must surface as ConfigEntryNotReady, not crash
|
||||
setup with a raw sqlite3.DatabaseError — and it must ALWAYS raise
|
||||
(returning normally would mean corruption was silently accepted)."""
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
_truncated_database(db_path)
|
||||
with pytest.raises(ConfigEntryNotReady) as excinfo:
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
assert isinstance(excinfo.value.__cause__, sqlite3.DatabaseError)
|
||||
|
||||
|
||||
def test_migration_stage_corruption_leaves_db_and_sidecars_untouched(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""A valid header with a corrupt LATER page must be rejected by the
|
||||
whole-file read-only preflight BEFORE the read-write open can
|
||||
switch the journal mode to WAL.
|
||||
|
||||
The fixture is deliberately a ROLLBACK-JOURNAL file (created with
|
||||
plain sqlite3, default journal_mode=delete, NOT via the wrapper):
|
||||
that is the case where the WAL transition actually rewrites the
|
||||
header — a WAL-mode fixture would mask the write under test. The
|
||||
open() spy proves the read-write open was never reached.
|
||||
"""
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
conn = sqlite3.connect(db_path)
|
||||
try:
|
||||
conn.execute("PRAGMA journal_mode=DELETE")
|
||||
conn.execute(
|
||||
"CREATE TABLE filler (id INTEGER PRIMARY KEY, "
|
||||
"payload TEXT NOT NULL)"
|
||||
)
|
||||
conn.executemany(
|
||||
"INSERT INTO filler (payload) VALUES (?)",
|
||||
[(f"row-{index}" * 8,) for index in range(200)],
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
data = bytearray(db_path.read_bytes())
|
||||
assert conn.execute is not None
|
||||
assert len(data) > 4200, "fixture must span more than one page"
|
||||
# Corrupt a page well past the 100-byte header (offset 4096, the
|
||||
# second page region): the header itself stays valid, so the
|
||||
# read-write open succeeds and only the integrity probe/migrations
|
||||
# discover damage.
|
||||
for offset in range(4096, 4128):
|
||||
data[offset] = 0xFF
|
||||
db_path.write_bytes(bytes(data))
|
||||
corrupt_bytes = db_path.read_bytes()
|
||||
digest = hashlib.sha256(corrupt_bytes).hexdigest()
|
||||
|
||||
# Track whether the read-write open is reached at all: the whole
|
||||
# preflight must reject this corruption BEFORE NestQuestDatabase
|
||||
# .open() is ever called, which is the only way the file can stay
|
||||
# byte-identical (the open persists WAL, rewriting the header).
|
||||
open_calls: list[str] = []
|
||||
original_open = NestQuestDatabase.open
|
||||
|
||||
async def _spy_open(self, path):
|
||||
open_calls.append(str(path))
|
||||
return await original_open(self, path)
|
||||
|
||||
monkeypatch.setattr(NestQuestDatabase, "open", _spy_open)
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady) as excinfo:
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
assert isinstance(excinfo.value.__cause__, sqlite3.DatabaseError)
|
||||
|
||||
# The corruption was caught at the preflight: the read-write open
|
||||
# (and with it the WAL header rewrite) was never attempted.
|
||||
assert open_calls == [], (
|
||||
"whole-file preflight must reject corruption before the "
|
||||
"read-write open can transition the journal mode"
|
||||
)
|
||||
|
||||
# The main file is byte-identical to the corrupt state we handed in.
|
||||
assert hashlib.sha256(db_path.read_bytes()).hexdigest() == digest
|
||||
# No WAL/SHM sidecars left behind (WAL mode was never persisted,
|
||||
# or they were cleaned up on close).
|
||||
assert not (tmp_path / "nestquest.db-wal").exists()
|
||||
assert not (tmp_path / "nestquest.db-shm").exists()
|
||||
|
||||
|
||||
def test_wal_mode_corruption_leaves_file_and_sidecars_untouched(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""A corrupt WAL-HEADER file must be rejected without creating
|
||||
-shm sidecars from the read-only preflight itself.
|
||||
|
||||
The immutable=1 probe URI is what guarantees a read-only
|
||||
connection creates no sidecars even for a WAL-header database; the
|
||||
sidecar assertions after the call prove it.
|
||||
"""
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
# WAL fixture: created via the wrapper (journal_mode=WAL persists).
|
||||
_valid_database(db_path)
|
||||
data = bytearray(db_path.read_bytes())
|
||||
# Corrupt the WAL header flag region: bytes 18/19 hold the
|
||||
# read/write version numbers (2 = WAL). Flip them to garbage so
|
||||
# the file claims a broken journal mode.
|
||||
assert len(data) > 64
|
||||
data[18] = 0x99
|
||||
data[19] = 0x99
|
||||
db_path.write_bytes(bytes(data))
|
||||
corrupt_bytes = db_path.read_bytes()
|
||||
digest = hashlib.sha256(corrupt_bytes).hexdigest()
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
|
||||
# Main file byte-identical; no -shm appeared from the probe.
|
||||
assert hashlib.sha256(db_path.read_bytes()).hexdigest() == digest
|
||||
assert not (tmp_path / "nestquest.db-shm").exists()
|
||||
|
||||
|
||||
def test_open_failure_closes_connection_when_opened(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""A failure DURING MIGRATIONS closes the opened connection; a
|
||||
failure inside open() itself has nothing to close (the wrapper
|
||||
never adopted a connection), so close must not be called there.
|
||||
"""
|
||||
db_path = tmp_path / "nestquest.db"
|
||||
_truncated_database(db_path)
|
||||
|
||||
close_calls: list[bool] = []
|
||||
original_close = NestQuestDatabase.close
|
||||
|
||||
async def _spy_close(self):
|
||||
close_calls.append(True)
|
||||
return await original_close(self)
|
||||
|
||||
monkeypatch.setattr(NestQuestDatabase, "close", _spy_close)
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
_run(_async_open_database(_make_hass_mock(), db_path))
|
||||
# Corruption hit at PRAGMA time inside open(): no connection was
|
||||
# adopted, so there is nothing to close and close() must NOT have
|
||||
# been called (calling close on a never-opened wrapper would be
|
||||
# harmless but the helper deliberately skips it).
|
||||
assert close_calls == []
|
||||
|
||||
# Contrast: a failure DURING migrations (file opens fine) closes.
|
||||
close_calls.clear()
|
||||
valid_path = tmp_path / "migrations-fail.db"
|
||||
_valid_database(valid_path)
|
||||
# _valid_database's own close went through the spy; only the
|
||||
# failure path's close counts from here.
|
||||
close_calls.clear()
|
||||
from custom_components.nestquest import migrations as migrations_mod
|
||||
from custom_components.nestquest.db import NestQuestDatabase as _DB
|
||||
|
||||
async def _failing(database, migrations=None):
|
||||
raise sqlite3.DatabaseError("database disk image is malformed")
|
||||
|
||||
monkeypatch.setattr(migrations_mod, "apply_migrations", _failing)
|
||||
monkeypatch.setattr(
|
||||
"custom_components.nestquest.apply_migrations", _failing
|
||||
)
|
||||
with pytest.raises(ConfigEntryNotReady) as excinfo:
|
||||
_run(_async_open_database(_make_hass_mock(), valid_path))
|
||||
# Exactly one close: the migrations-failure cleanup path. (The
|
||||
# spy also sees the wrapper's own idempotent close if it were
|
||||
# double-called — it must not be.)
|
||||
assert close_calls == [True], (
|
||||
"an open connection must be closed before the error propagates"
|
||||
)
|
||||
assert isinstance(excinfo.value.__cause__, sqlite3.DatabaseError)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Startup through async_setup_entry (the real wiring)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_setup(hass, registry):
|
||||
def _setup(entry):
|
||||
return async_setup_entry(hass, entry)
|
||||
|
||||
return _setup
|
||||
|
||||
|
||||
async def _setup_entry(hass, entry, registry) -> object:
|
||||
entry = _wire(entry, registry)
|
||||
await async_setup_entry(hass, entry)
|
||||
return entry
|
||||
|
||||
|
||||
async def test_setup_with_corrupt_file_raises_not_ready(
|
||||
hass, make_entry, monkeypatch, tmp_path, caplog
|
||||
) -> None:
|
||||
from custom_components.nestquest.store import async_get_db_path
|
||||
|
||||
db_path = await async_get_db_path(hass)
|
||||
await _avalid_database(db_path)
|
||||
data = db_path.read_bytes()
|
||||
assert len(data) > 64
|
||||
db_path.write_bytes(data[: len(data) // 2])
|
||||
corrupt_bytes = db_path.read_bytes()
|
||||
|
||||
entry = make_entry()
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
await _setup_entry(hass, entry, hass.registry)
|
||||
# File untouched, no runtime data stored.
|
||||
assert db_path.read_bytes() == corrupt_bytes
|
||||
assert hass.data["nestquest"].get(entry.entry_id) is None
|
||||
|
||||
|
||||
async def test_setup_with_missing_file_creates_and_loads(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database = entry.runtime_data.database
|
||||
try:
|
||||
row = await database.fetch_one(
|
||||
f"SELECT version FROM {VERSION_TABLE}"
|
||||
)
|
||||
assert row == (len(MIGRATIONS),)
|
||||
finally:
|
||||
await database.close()
|
||||
assert await async_unload_entry(hass, entry) is True
|
||||
|
||||
|
||||
async def test_setup_with_valid_file_preserves_rows(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry_a = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database_a = entry_a.runtime_data.database
|
||||
await database_a.execute(
|
||||
"INSERT INTO children (display_name, created_at) VALUES (?, ?)",
|
||||
("Ada", "2026-09-14T12:00:00+00:00"),
|
||||
)
|
||||
# Unload pops the runtime record AND closes the connection; a
|
||||
# fresh setup for the same entry_id then reopens the file.
|
||||
assert await async_unload_entry(hass, entry_a) is True
|
||||
|
||||
entry_b = await _setup_entry(hass, make_entry(), hass.registry)
|
||||
database_b = entry_b.runtime_data.database
|
||||
assert database_b is not database_a
|
||||
try:
|
||||
row = await database_b.fetch_one("SELECT COUNT(*) FROM children")
|
||||
assert row == (1,)
|
||||
finally:
|
||||
await database_b.close()
|
||||
assert await async_unload_entry(hass, entry_b) is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# No code path deletes or overwrites an existing database file
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_package_never_unlinks_or_truncates_db_files() -> None:
|
||||
"""Guardrail: no code path may delete or overwrite an existing
|
||||
database file. Scans the package for unlink/rmtree/write on the
|
||||
DB filename constant or *.db patterns.
|
||||
|
||||
Recursive (``rglob``) so the bundled ``core/`` package (extracted
|
||||
in task d0b691d8 / 510c1f78) is scanned alongside the integration's
|
||||
own modules — a non-recursive ``glob`` skips ``core/`` and leaves
|
||||
the guardrail vacuous against it.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
package = Path(
|
||||
__import__(
|
||||
"custom_components.nestquest", fromlist=["__file__"]
|
||||
).__file__
|
||||
).parent
|
||||
pattern = re.compile(
|
||||
r"(unlink|rmtree|write_bytes|write_text|open\s*\(\s*[^)]*['\"]w)"
|
||||
r"[^\n]*(nestquest\.db|\.db['\"])|"
|
||||
r"(nestquest\.db|\.db['\"])[^\n]*"
|
||||
r"(unlink|rmtree|write_bytes|write_text)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
offenders: list[str] = []
|
||||
for py in sorted(package.rglob("*.py")):
|
||||
if pattern.search(py.read_text()):
|
||||
offenders.append(py.name)
|
||||
assert offenders == [], (
|
||||
f"code paths that could delete/overwrite the database: {offenders}"
|
||||
)
|
||||
@@ -1,215 +0,0 @@
|
||||
"""Tests for store.py of NestQuest."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from custom_components.nestquest import store
|
||||
from custom_components.nestquest.const import SQLITE_DB_FILENAME
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.new_event_loop().run_until_complete(coro)
|
||||
|
||||
|
||||
def _make_hass(config_dir: Path, execute: bool = True):
|
||||
hass = MagicMock()
|
||||
hass.config.path = MagicMock(return_value=str(config_dir / SQLITE_DB_FILENAME))
|
||||
hass.async_add_executor_job = AsyncMock(
|
||||
side_effect=(lambda fn, *a: fn(*a)) if execute else None
|
||||
)
|
||||
return hass
|
||||
|
||||
|
||||
def test_returns_absolute_path_from_config_path(monkeypatch) -> None:
|
||||
# Path resolution only: the parent-dir mkdir is a side effect of
|
||||
# core.store and is exercised elsewhere; suppress it here so the
|
||||
# absolute-path assertion can run against /config (non-writable).
|
||||
monkeypatch.setattr("custom_components.nestquest.core.store._ensure_dir", lambda path: None)
|
||||
hass = _make_hass(Path("/config"), execute=False)
|
||||
db_path = _run(store.async_get_db_path(hass))
|
||||
hass.config.path.assert_called_once_with(SQLITE_DB_FILENAME)
|
||||
assert db_path == Path("/config") / SQLITE_DB_FILENAME
|
||||
assert db_path.is_absolute()
|
||||
|
||||
|
||||
def test_relative_config_path_is_normalized_to_absolute(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.chdir(tmp_path)
|
||||
hass = MagicMock()
|
||||
hass.config.path = MagicMock(return_value="relative-config/" + SQLITE_DB_FILENAME)
|
||||
hass.async_add_executor_job = AsyncMock(side_effect=(lambda fn, *a: fn(*a)))
|
||||
db_path = _run(store.async_get_db_path(hass))
|
||||
assert db_path.is_absolute()
|
||||
assert db_path.name == SQLITE_DB_FILENAME
|
||||
assert str(db_path).endswith("relative-config/" + SQLITE_DB_FILENAME)
|
||||
assert db_path.parent.is_dir()
|
||||
assert (tmp_path / "relative-config").is_dir()
|
||||
assert not db_path.exists()
|
||||
|
||||
|
||||
def test_creates_missing_parent_directory(tmp_path) -> None:
|
||||
nested = tmp_path / "homeassistant" / "config"
|
||||
hass = _make_hass(nested)
|
||||
db_path = _run(store.async_get_db_path(hass))
|
||||
assert db_path.parent == nested
|
||||
assert nested.is_dir()
|
||||
assert db_path.parent.is_dir()
|
||||
assert not db_path.exists()
|
||||
|
||||
|
||||
def test_two_calls_return_same_path(tmp_path) -> None:
|
||||
hass = _make_hass(tmp_path)
|
||||
first = _run(store.async_get_db_path(hass))
|
||||
second = _run(store.async_get_db_path(hass))
|
||||
assert first == second
|
||||
assert first.parent.is_dir()
|
||||
assert not first.exists()
|
||||
assert not second.exists()
|
||||
|
||||
|
||||
def test_existing_directory_does_not_fail(tmp_path) -> None:
|
||||
nested = tmp_path / "config"
|
||||
nested.mkdir()
|
||||
hass = _make_hass(nested)
|
||||
db_path = _run(store.async_get_db_path(hass))
|
||||
assert db_path == nested / SQLITE_DB_FILENAME
|
||||
assert db_path.parent.is_dir()
|
||||
assert not db_path.exists()
|
||||
|
||||
|
||||
def test_mkdir_runs_off_event_loop(tmp_path, monkeypatch) -> None:
|
||||
"""The parent-directory mkdir runs off the event loop via asyncio.to_thread.
|
||||
|
||||
core.store is Home-Assistant-free, so it schedules the blocking
|
||||
``mkdir`` through :func:`asyncio.to_thread` rather than
|
||||
``hass.async_add_executor_job``; the integration shim delegates to it
|
||||
unchanged. The intent is preserved: the mkdir still runs off the
|
||||
event loop, with ``_ensure_dir`` on the parent directory, and the
|
||||
directory exists afterwards.
|
||||
"""
|
||||
nested = tmp_path / "deep" / "nested"
|
||||
hass = _make_hass(nested)
|
||||
to_thread_calls: list = []
|
||||
real_to_thread = asyncio.to_thread
|
||||
|
||||
def _trace_to_thread(fn, *args, **kwargs):
|
||||
to_thread_calls.append((fn, args, kwargs))
|
||||
return real_to_thread(fn, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(asyncio, "to_thread", _trace_to_thread)
|
||||
db_path = _run(store.async_get_db_path(hass))
|
||||
assert nested.is_dir()
|
||||
assert len(to_thread_calls) == 1, (
|
||||
f"expected one asyncio.to_thread call, got {len(to_thread_calls)}"
|
||||
)
|
||||
fn, fn_args, fn_kwargs = to_thread_calls[0]
|
||||
assert callable(fn)
|
||||
assert fn is store._ensure_dir
|
||||
assert fn_args == (nested,)
|
||||
assert fn_kwargs == {}
|
||||
assert db_path.parent == nested
|
||||
assert db_path.parent.is_dir()
|
||||
assert not db_path.exists()
|
||||
|
||||
|
||||
def test_executor_helper_creates_directory(tmp_path) -> None:
|
||||
nested = tmp_path / "executor" / "made"
|
||||
store._ensure_dir(nested)
|
||||
assert nested.is_dir()
|
||||
store._ensure_dir(nested)
|
||||
assert nested.is_dir()
|
||||
|
||||
|
||||
def test_no_sqlite3_import_outside_db_module() -> None:
|
||||
"""sqlite3 is banned package-wide except two justified modules.
|
||||
|
||||
db.py is the connection wrapper (all statement execution lives
|
||||
there). __init__.py imports sqlite3 ONLY for its exception types
|
||||
to classify corruption on startup (done-condition: corrupt file ->
|
||||
ConfigEntryNotReady); it never opens a connection or executes
|
||||
SQL — that is asserted separately below.
|
||||
"""
|
||||
pkg_dir = Path(store.__file__).parent
|
||||
py_files = list(pkg_dir.glob("*.py"))
|
||||
assert py_files
|
||||
allowed = {"db.py", "__init__.py"}
|
||||
for py_file in py_files:
|
||||
if py_file.name in allowed:
|
||||
continue
|
||||
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
assert alias.name != "sqlite3", (
|
||||
f"Found sqlite3 import in {py_file.name}:{node.lineno}"
|
||||
)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module == "sqlite3":
|
||||
raise AssertionError(
|
||||
f"Found sqlite3 import in {py_file.name}:{node.lineno}"
|
||||
)
|
||||
|
||||
|
||||
def test_init_module_never_opens_or_executes_sqlite() -> None:
|
||||
"""The __init__.py sqlite3 usage is limited to (a) exception typing
|
||||
for corruption classification and (b) the ONE read-only preflight
|
||||
connection (mode=ro URI, SELECT-only) that detects corruption in an
|
||||
existing file before the real read-write open. No read-write
|
||||
connect, no cursor writes, no non-SELECT statements may appear.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
init_path = (
|
||||
Path(store.__file__).parent / "__init__.py"
|
||||
).read_text(encoding="utf-8")
|
||||
# The preflight connect must be the URI read-only form, and only
|
||||
# SELECT statements and the integrity_check PRAGMA may run there.
|
||||
assert "sqlite3.connect(uri, uri=True)" in init_path
|
||||
assert "?mode=ro" in init_path
|
||||
assert 'PRAGMA integrity_check' in init_path
|
||||
forbidden = re.compile(
|
||||
r"sqlite3\s*\.\s*connect(?!\(\s*uri\s*,)"
|
||||
r"|\bconn(ection)?\s*\.\s*execute\s*\(\s*[\"'](?!SELECT\s|PRAGMA\s+integrity_check)"
|
||||
r"|\bexecutemany\b|\bexecutescript\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
assert forbidden.search(init_path) is None, (
|
||||
"__init__.py may use sqlite3 only for exception typing and the "
|
||||
"read-only corruption preflight (SELECT + integrity_check)"
|
||||
)
|
||||
|
||||
|
||||
def test_no_file_creation_calls_in_store() -> None:
|
||||
source = Path(store.__file__).read_text(encoding="utf-8")
|
||||
tree = ast.parse(source, filename=str(store.__file__))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Call):
|
||||
func = node.func
|
||||
if isinstance(func, ast.Name) and func.id == "open":
|
||||
raise AssertionError(
|
||||
f"Found open() call in store.py:{node.lineno}"
|
||||
)
|
||||
if (
|
||||
isinstance(func, ast.Attribute)
|
||||
and func.attr == "touch"
|
||||
):
|
||||
raise AssertionError(
|
||||
f"Found touch() call in store.py:{node.lineno}"
|
||||
)
|
||||
assert "touch(" not in source
|
||||
assert "open(" not in source
|
||||
|
||||
|
||||
def test_container_style_path_resolves(monkeypatch) -> None:
|
||||
monkeypatch.setattr("custom_components.nestquest.core.store._ensure_dir", lambda path: None)
|
||||
hass = _make_hass(Path("/config"), execute=False)
|
||||
assert _run(store.async_get_db_path(hass)) == Path("/config") / SQLITE_DB_FILENAME
|
||||
|
||||
|
||||
def test_core_style_path_resolves(tmp_path) -> None:
|
||||
config_dir = tmp_path / ".homeassistant"
|
||||
hass = _make_hass(config_dir)
|
||||
assert _run(store.async_get_db_path(hass)) == config_dir / SQLITE_DB_FILENAME
|
||||
assert (config_dir / SQLITE_DB_FILENAME).parent.is_dir()
|
||||
@@ -1,259 +0,0 @@
|
||||
"""Tests for the nightly missed-quest sweep (Feature 11, task 1)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import re
|
||||
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import create_child, list_children
|
||||
from custom_components.nestquest.completion import (
|
||||
complete_instance,
|
||||
uncomplete_instance,
|
||||
)
|
||||
from custom_components.nestquest.const import EVENT_QUEST_MISSED
|
||||
from custom_components.nestquest.dao_instances import (
|
||||
CompletionEventsDao,
|
||||
QuestInstancesDao,
|
||||
)
|
||||
from custom_components.nestquest.dao_meta import MetaStateDao
|
||||
from custom_components.nestquest.materialize import materialize
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
create_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import ScheduleRule
|
||||
from custom_components.nestquest.sweep import (
|
||||
SWEEP_WATERMARK_KEY,
|
||||
run_missed_sweep,
|
||||
)
|
||||
|
||||
_TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$")
|
||||
|
||||
|
||||
async def _seed(hass, make_entry) -> tuple:
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
ada = await create_child(database, "Ada")
|
||||
bo = await create_child(database, "Bo")
|
||||
today = datetime.date.today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
),
|
||||
[ada.id, bo.id],
|
||||
["morning"],
|
||||
)
|
||||
end = (today + datetime.timedelta(days=3)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
return entry, ada, bo
|
||||
|
||||
|
||||
async def test_sweep_fires_one_event_per_past_due_open_instance(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
today = datetime.date.today()
|
||||
tomorrow = today + datetime.timedelta(days=1)
|
||||
|
||||
fired = await run_missed_sweep(hass, database, today=tomorrow)
|
||||
assert fired == 2, "one per child for today's now-past-due instance"
|
||||
|
||||
events = hass.bus.fired(EVENT_QUEST_MISSED)
|
||||
assert len(events) == 2
|
||||
payload = events[0]
|
||||
assert payload["child_name"] in ("Ada", "Bo")
|
||||
assert payload["quest_title"] == "Brush teeth"
|
||||
assert payload["window"] == "morning"
|
||||
assert payload["due_date"] == today.isoformat()
|
||||
assert payload["due_time"] is None
|
||||
assert _TIMESTAMP.match(payload["occurred_at"])
|
||||
assert {payload["child_id"] for payload in events} == {ada.id, bo.id}
|
||||
# The sweep is read-only over the domain tables.
|
||||
assert await _count_events(database) == 0
|
||||
|
||||
|
||||
async def test_sweep_is_idempotent_same_night(hass, make_entry) -> None:
|
||||
entry, _ada, _bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
|
||||
|
||||
first = await run_missed_sweep(hass, database, today=tomorrow)
|
||||
second = await run_missed_sweep(hass, database, today=tomorrow)
|
||||
assert first == 2
|
||||
assert second == 0, "the watermark makes a rerun fire nothing"
|
||||
assert len(hass.bus.fired(EVENT_QUEST_MISSED)) == 2
|
||||
assert await MetaStateDao(database).get(SWEEP_WATERMARK_KEY) == (
|
||||
tomorrow.isoformat()
|
||||
)
|
||||
|
||||
|
||||
async def test_sweep_only_fires_new_instances_after_watermark(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, _bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
today = datetime.date.today()
|
||||
tomorrow = today + datetime.timedelta(days=1)
|
||||
day_after = today + datetime.timedelta(days=2)
|
||||
|
||||
# First sweep one day ahead: today's instances fire.
|
||||
fired = await run_missed_sweep(hass, database, today=tomorrow)
|
||||
assert fired == 2
|
||||
first_events = hass.bus.fired(EVENT_QUEST_MISSED)
|
||||
assert all(
|
||||
payload["due_date"] == today.isoformat()
|
||||
for payload in first_events
|
||||
)
|
||||
|
||||
# One more day passes: only tomorrow's instances fire now.
|
||||
fired = await run_missed_sweep(hass, database, today=day_after)
|
||||
assert fired == 2
|
||||
all_events = hass.bus.fired(EVENT_QUEST_MISSED)
|
||||
assert len(all_events) == 4
|
||||
assert all(
|
||||
payload["due_date"] == tomorrow.isoformat()
|
||||
for payload in all_events[2:]
|
||||
)
|
||||
|
||||
|
||||
async def test_sweep_never_reports_completed_or_reversed_instances(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
entry, ada, bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
today = datetime.date.today()
|
||||
tomorrow = today + datetime.timedelta(days=1)
|
||||
|
||||
instances_ada = await QuestInstancesDao(database).list_by_date_range(
|
||||
ada.id, today.isoformat(), today.isoformat()
|
||||
)
|
||||
instances_bo = await QuestInstancesDao(database).list_by_date_range(
|
||||
bo.id, today.isoformat(), today.isoformat()
|
||||
)
|
||||
# Ada completed hers; Bo completed his then reversed it.
|
||||
await complete_instance(
|
||||
database,
|
||||
instances_ada[0].id,
|
||||
actor_source="panel",
|
||||
actor_child_id=ada.id,
|
||||
)
|
||||
await complete_instance(
|
||||
database,
|
||||
instances_bo[0].id,
|
||||
actor_source="panel",
|
||||
actor_child_id=bo.id,
|
||||
)
|
||||
await uncomplete_instance(
|
||||
database,
|
||||
instances_bo[0].id,
|
||||
actor_source="user",
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
fired = await run_missed_sweep(hass, database, today=tomorrow)
|
||||
assert fired == 0, (
|
||||
"no-completion-event rule excludes both the completed and the "
|
||||
"reversed instance (append-only history keeps both)"
|
||||
)
|
||||
assert hass.bus.fired(EVENT_QUEST_MISSED) == []
|
||||
|
||||
|
||||
async def test_sweep_skips_instance_completed_after_sweep(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A missed instance completed later is never re-announced; the
|
||||
late completion still lands in the append-only log."""
|
||||
entry, ada, _bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
today = datetime.date.today()
|
||||
tomorrow = today + datetime.timedelta(days=1)
|
||||
day3 = today + datetime.timedelta(days=2)
|
||||
|
||||
await run_missed_sweep(hass, database, today=tomorrow)
|
||||
instance = (
|
||||
await QuestInstancesDao(database).list_by_date_range(
|
||||
ada.id, today.isoformat(), today.isoformat()
|
||||
)
|
||||
)[0]
|
||||
await complete_instance(
|
||||
database,
|
||||
instance.id,
|
||||
actor_source="panel",
|
||||
actor_child_id=ada.id,
|
||||
)
|
||||
fired = await run_missed_sweep(hass, database, today=day3)
|
||||
assert fired == 0 or all(
|
||||
payload["instance_id"] != instance.id
|
||||
for payload in hass.bus.fired(EVENT_QUEST_MISSED)[2:]
|
||||
)
|
||||
|
||||
|
||||
async def test_rollover_listener_runs_sweep_after_materialization(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
calls = []
|
||||
|
||||
async def _record_sweep(hass_arg, database, **kwargs):
|
||||
calls.append("sweep")
|
||||
|
||||
monkeypatch.setattr(nestquest, "run_missed_sweep", _record_sweep)
|
||||
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(options={"day_rollover_time": "00:00"}), hass.registry
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
assert calls == ["sweep"], "startup runs the sweep once"
|
||||
|
||||
await hass.time_change.fire()
|
||||
assert calls == ["sweep", "sweep"], "the rollover listener sweeps too"
|
||||
|
||||
|
||||
async def test_v6_database_migrates_to_v7_meta_state(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A database stamped at version 6 gains the meta_state table and
|
||||
version 7 on the next startup; existing rows are untouched."""
|
||||
entry = wire_entry_to_registry(make_entry(), hass.registry)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
version = await database.fetch_one(
|
||||
"SELECT version FROM nestquest_schema_version"
|
||||
)
|
||||
assert version == (7,)
|
||||
tables = await database.fetch_all(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' "
|
||||
"AND name='nestquest_meta_state'"
|
||||
)
|
||||
assert tables, "migration 7 created the meta_state table"
|
||||
|
||||
|
||||
async def _count_events(database) -> int:
|
||||
rows = await database.fetch_all("SELECT COUNT(*) FROM completion_events")
|
||||
return rows[0][0]
|
||||
|
||||
|
||||
async def test_overlapping_sweeps_never_double_announce(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A startup sweep and a rollover sweep racing on the same night
|
||||
queue on the sweep lock: the winner announces, the loser re-reads
|
||||
the watermark inside the lock and fires nothing."""
|
||||
import asyncio
|
||||
|
||||
entry, _ada, _bo = await _seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
|
||||
|
||||
first, second = await asyncio.gather(
|
||||
run_missed_sweep(hass, database, today=tomorrow),
|
||||
run_missed_sweep(hass, database, today=tomorrow),
|
||||
)
|
||||
assert first + second == 2, "each instance announced exactly once"
|
||||
assert len(hass.bus.fired(EVENT_QUEST_MISSED)) == 2
|
||||
@@ -1,355 +0,0 @@
|
||||
"""Timezone tests for the single HA-local date source in the generation path.
|
||||
|
||||
These pin the done-condition that every "today" read in the generation path
|
||||
derives from ``hass.config.time_zone`` — not the host clock and not UTC —
|
||||
and that the rolling horizon ``[today, today + DEFAULT_HORIZON_DAYS]`` and the
|
||||
no-past guard resolve the correct local dates around midnight and across the
|
||||
daylight-saving transitions.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
from types import SimpleNamespace
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from conftest import freeze_nestquest_clock
|
||||
from custom_components.nestquest.const import DEFAULT_HORIZON_DAYS
|
||||
from custom_components.nestquest.core.settings import NestQuestSettings
|
||||
from custom_components.nestquest.dao_children import ChildrenDao
|
||||
from custom_components.nestquest.dao_instances import QuestInstancesDao
|
||||
from custom_components.nestquest.db import NestQuestDatabase
|
||||
from custom_components.nestquest.migrations import apply_migrations
|
||||
from custom_components.nestquest.quest_definitions import (
|
||||
assign_child,
|
||||
create_quest_definition,
|
||||
edit_quest_definition,
|
||||
)
|
||||
from custom_components.nestquest.recurrence import RuleType, ScheduleRule
|
||||
|
||||
NOW = "2026-09-14T12:00:00+00:00"
|
||||
NEW_YORK = "America/New_York"
|
||||
|
||||
|
||||
def _make_hass_mock():
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
hass = MagicMock()
|
||||
hass.async_add_executor_job = AsyncMock(side_effect=(lambda fn, *a: fn(*a)))
|
||||
return hass
|
||||
|
||||
|
||||
async def _prepare(path):
|
||||
database = NestQuestDatabase(_make_hass_mock().async_add_executor_job)
|
||||
await database.open(path)
|
||||
await apply_migrations(database)
|
||||
return database
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.new_event_loop().run_until_complete(coro)
|
||||
|
||||
|
||||
def _freeze_clock(
|
||||
monkeypatch, instant: datetime.datetime
|
||||
) -> tuple[datetime.datetime, list]:
|
||||
"""Freeze the integration's ``datetime`` clock to a fixed aware instant.
|
||||
|
||||
Thin wrapper over :func:`conftest.freeze_nestquest_clock` kept for the
|
||||
``(frozen, requested)`` return shape the timezone assertions read.
|
||||
"""
|
||||
return freeze_nestquest_clock(monkeypatch, instant)
|
||||
|
||||
|
||||
def _assert_requested_ha_timezone(requested, time_zone: str) -> None:
|
||||
"""Assert ``now`` was called with (only) the configured HA time zone.
|
||||
|
||||
This is what turns the DST tests into a real proof of the HA-local date
|
||||
source: if the generation path regressed to ``now(timezone.utc)``, its
|
||||
requested tz would be UTC and this fails.
|
||||
"""
|
||||
assert requested, "the generation path never called now(tz)"
|
||||
assert all(tz == ZoneInfo(time_zone) for tz in requested)
|
||||
|
||||
|
||||
def _tz_hass(time_zone: str):
|
||||
"""A minimal hass exposing only the ``config.time_zone`` the walk reads."""
|
||||
return SimpleNamespace(config=SimpleNamespace(time_zone=time_zone))
|
||||
|
||||
|
||||
async def _seed_daily(database, start_iso: str) -> int:
|
||||
"""One always-present child + a daily definition starting ``start_iso``."""
|
||||
child = await ChildrenDao(database).create("Ada", NOW)
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Daily chore",
|
||||
ScheduleRule(rule_type=RuleType.DAILY, start_date=start_iso),
|
||||
[child.id],
|
||||
["morning"],
|
||||
)
|
||||
return child.id
|
||||
|
||||
|
||||
def _local_date(instant_utc: datetime.datetime, time_zone: str) -> datetime.date:
|
||||
return instant_utc.astimezone(ZoneInfo(time_zone)).date()
|
||||
|
||||
|
||||
def _assert_contiguous_horizon(records, local_today: datetime.date) -> None:
|
||||
"""The horizon is exactly today..today+horizon, no off-by-one, no gap."""
|
||||
expected = {
|
||||
(local_today + datetime.timedelta(days=offset)).isoformat()
|
||||
for offset in range(DEFAULT_HORIZON_DAYS + 1)
|
||||
}
|
||||
assert {r.due_date for r in records} == expected
|
||||
assert len(records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
def test_horizon_uses_newyork_local_date_after_local_midnight(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""A run just after New York local midnight uses the local date.
|
||||
|
||||
The frozen instant is 00:05 New York local time on 2026-03-10 (EDT, so
|
||||
04:05 UTC). The horizon must start on 2026-03-10 — the local calendar
|
||||
date — not any host/UTC-derived value.
|
||||
"""
|
||||
instant = datetime.datetime(
|
||||
2026, 3, 10, 0, 5, tzinfo=ZoneInfo(NEW_YORK)
|
||||
)
|
||||
local_today = instant.date()
|
||||
|
||||
async def _body(database):
|
||||
hass = _tz_hass(NEW_YORK)
|
||||
_frozen, requested = _freeze_clock(monkeypatch, instant)
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
child_id = await _seed_daily(database, local_today.isoformat())
|
||||
await nestquest._run_horizon_materialization(
|
||||
hass, database, NestQuestSettings()
|
||||
)
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id,
|
||||
local_today.isoformat(),
|
||||
(local_today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat(),
|
||||
)
|
||||
_assert_contiguous_horizon(records, local_today)
|
||||
_assert_requested_ha_timezone(requested, NEW_YORK)
|
||||
return len(records)
|
||||
|
||||
async def _main():
|
||||
database = await _prepare(tmp_path / "tz-midnight.db")
|
||||
try:
|
||||
return await _body(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
assert _run(_main()) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
def test_horizon_uses_local_date_not_utc_when_host_ahead(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""The walk's "today" is HA-local, never the UTC/system calendar date.
|
||||
|
||||
FROZEN at 2026-01-15 03:00 UTC: the UTC calendar date is 2026-01-15, but
|
||||
New York local is still 2026-01-14 22:00 EST. The horizon must start on
|
||||
2026-01-14 (local), proving the UTC date did not win.
|
||||
"""
|
||||
instant = datetime.datetime(2026, 1, 15, 3, 0, tzinfo=datetime.timezone.utc)
|
||||
local_today = _local_date(instant, NEW_YORK)
|
||||
assert local_today == datetime.date(2026, 1, 14)
|
||||
assert instant.date() == datetime.date(2026, 1, 15)
|
||||
|
||||
async def _body(database):
|
||||
hass = _tz_hass(NEW_YORK)
|
||||
_frozen, requested = _freeze_clock(monkeypatch, instant)
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
child_id = await _seed_daily(database, local_today.isoformat())
|
||||
await nestquest._run_horizon_materialization(
|
||||
hass, database, NestQuestSettings()
|
||||
)
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id,
|
||||
local_today.isoformat(),
|
||||
(local_today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat(),
|
||||
)
|
||||
_assert_contiguous_horizon(records, local_today)
|
||||
_assert_requested_ha_timezone(requested, NEW_YORK)
|
||||
return len(records)
|
||||
|
||||
async def _main():
|
||||
database = await _prepare(tmp_path / "tz-host-ahead.db")
|
||||
try:
|
||||
return await _body(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
assert _run(_main()) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
|
||||
def test_horizon_resolves_spring_forward_day_without_off_by_one(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""Across the 2026-03-08 spring-forward, today and the horizon stay local.
|
||||
|
||||
Before the jump ("01:30 EST") and after it ("03:30 EDT") both resolve to
|
||||
2026-03-08 local — the lost hour must not skip or repeat a calendar day —
|
||||
and the full horizon remains 15 contiguous days.
|
||||
"""
|
||||
zone = ZoneInfo(NEW_YORK)
|
||||
before = datetime.datetime(2026, 3, 8, 1, 30, tzinfo=zone) # EST
|
||||
after = datetime.datetime(2026, 3, 8, 3, 30, tzinfo=zone) # EDT
|
||||
assert before.date() == after.date() == datetime.date(2026, 3, 8)
|
||||
|
||||
async def _body(database):
|
||||
hass = _tz_hass(NEW_YORK)
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
requested_batches: list[list] = []
|
||||
for instant in (before, after):
|
||||
_frozen, requested = _freeze_clock(monkeypatch, instant)
|
||||
requested_batches.append(requested)
|
||||
local_today = instant.date()
|
||||
child_id = await _seed_daily(database, local_today.isoformat())
|
||||
await nestquest._run_horizon_materialization(
|
||||
hass, database, NestQuestSettings()
|
||||
)
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id,
|
||||
local_today.isoformat(),
|
||||
(local_today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat(),
|
||||
)
|
||||
_assert_contiguous_horizon(records, local_today)
|
||||
requested_all = [tz for batch in requested_batches for tz in batch]
|
||||
_assert_requested_ha_timezone(requested_all, NEW_YORK)
|
||||
return local_today
|
||||
|
||||
async def _main():
|
||||
database = await _prepare(tmp_path / "tz-spring-forward.db")
|
||||
try:
|
||||
return await _body(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
assert _run(_main()) == datetime.date(2026, 3, 8)
|
||||
|
||||
|
||||
def test_horizon_resolves_fall_back_day_without_off_by_one(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""Across the 2026-11-01 fall-back, today and the horizon stay local.
|
||||
|
||||
The repeated 01:00-02:00 hour must not resolve to the wrong calendar
|
||||
day: the first 01:30 (``fold=0``, EDT) and the repeated 01:30
|
||||
(``fold=1``, EST) are distinct instants yet both resolve to 2026-11-01
|
||||
— and both, along with 03:30 EST after the jump, materialize the same
|
||||
15 contiguous-day horizon with no off-by-one.
|
||||
"""
|
||||
zone = ZoneInfo(NEW_YORK)
|
||||
first = datetime.datetime(2026, 11, 1, 1, 30, tzinfo=zone, fold=0) # EDT
|
||||
second = datetime.datetime(2026, 11, 1, 1, 30, tzinfo=zone, fold=1) # EST
|
||||
after = datetime.datetime(2026, 11, 1, 3, 30, tzinfo=zone) # EST
|
||||
assert first.date() == second.date() == after.date() == datetime.date(2026, 11, 1)
|
||||
assert first.utcoffset() != second.utcoffset() # the two repeated-hour folds
|
||||
|
||||
async def _body(database):
|
||||
hass = _tz_hass(NEW_YORK)
|
||||
import custom_components.nestquest as nestquest
|
||||
|
||||
requested_batches: list[list] = []
|
||||
for instant in (first, second, after):
|
||||
_frozen, requested = _freeze_clock(monkeypatch, instant)
|
||||
requested_batches.append(requested)
|
||||
local_today = instant.date()
|
||||
child_id = await _seed_daily(database, local_today.isoformat())
|
||||
await nestquest._run_horizon_materialization(
|
||||
hass, database, NestQuestSettings()
|
||||
)
|
||||
records = await QuestInstancesDao(database).list_by_date_range(
|
||||
child_id,
|
||||
local_today.isoformat(),
|
||||
(local_today + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)).isoformat(),
|
||||
)
|
||||
_assert_contiguous_horizon(records, local_today)
|
||||
requested_all = [tz for batch in requested_batches for tz in batch]
|
||||
_assert_requested_ha_timezone(requested_all, NEW_YORK)
|
||||
return local_today
|
||||
|
||||
async def _main():
|
||||
database = await _prepare(tmp_path / "tz-fall-back.db")
|
||||
try:
|
||||
return await _body(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
assert _run(_main()) == datetime.date(2026, 11, 1)
|
||||
|
||||
|
||||
def test_definition_business_regeneration_uses_pinned_today_not_host(
|
||||
tmp_path, monkeypatch
|
||||
) -> None:
|
||||
"""``edit_quest_definition``/``assign_child`` anchor regeneration on
|
||||
the caller-pinned HA-local ``today``, not the host clock.
|
||||
|
||||
The host clock (the ``_today`` fallback) is pinned one day AHEAD of the
|
||||
HA-local ``today``; the guard would reject the local "today" as past
|
||||
(and the horizon would skip it) if it consulted the host clock. Both
|
||||
business operations must regenerate against the pinned date and keep
|
||||
that first local day, proving the threaded ``today`` wins.
|
||||
"""
|
||||
import custom_components.nestquest.core.dao_instances as dao_instances_module
|
||||
|
||||
pinned = datetime.date(2026, 1, 14)
|
||||
host_today = datetime.date(2026, 1, 15)
|
||||
monkeypatch.setattr(dao_instances_module, "_today", lambda: host_today)
|
||||
|
||||
async def _body(database):
|
||||
children = ChildrenDao(database)
|
||||
dao = QuestInstancesDao(database)
|
||||
horizon_end = pinned + datetime.timedelta(days=DEFAULT_HORIZON_DAYS)
|
||||
|
||||
a = await children.create("Ada", NOW)
|
||||
created = await create_quest_definition(
|
||||
database,
|
||||
"Daily chore",
|
||||
ScheduleRule(rule_type=RuleType.DAILY, start_date=pinned.isoformat()),
|
||||
[a.id],
|
||||
[("morning", "09:00")],
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
|
||||
# edit anchors on pinned: the horizon starts at the local day the
|
||||
# host clock calls "past", so its presence proves pinned won.
|
||||
await edit_quest_definition(
|
||||
database,
|
||||
definition_id,
|
||||
windows=[("morning", "10:15")],
|
||||
today=pinned,
|
||||
)
|
||||
a_records = await dao.list_by_date_range(
|
||||
a.id, pinned.isoformat(), horizon_end.isoformat()
|
||||
)
|
||||
assert [r.due_date for r in a_records][0] == pinned.isoformat()
|
||||
assert {r.due_time for r in a_records} == {"10:15"}
|
||||
assert len(a_records) == DEFAULT_HORIZON_DAYS + 1
|
||||
|
||||
# assign anchors on pinned too: the new child's regeneration keeps
|
||||
# the same pinned-local first day rather than skipping to the host day.
|
||||
b = await children.create("Bo", NOW)
|
||||
await assign_child(database, definition_id, b.id, today=pinned)
|
||||
b_records = await dao.list_by_date_range(
|
||||
b.id, pinned.isoformat(), horizon_end.isoformat()
|
||||
)
|
||||
assert [r.due_date for r in b_records][0] == pinned.isoformat()
|
||||
assert len(b_records) == DEFAULT_HORIZON_DAYS + 1
|
||||
return definition_id
|
||||
|
||||
async def _main():
|
||||
database = await _prepare(tmp_path / "tz-definition-regen.db")
|
||||
try:
|
||||
return await _body(database)
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
assert _run(_main()) is not None
|
||||
Reference in New Issue
Block a user