Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5b18326f5 |
@@ -18,9 +18,7 @@ from homeassistant.helpers.event import async_track_time_change
|
||||
|
||||
from .const import (
|
||||
CONF_ADMIN_USER_IDS,
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
@@ -520,9 +518,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
update_interval_seconds=entry.options.get(
|
||||
CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL
|
||||
),
|
||||
staleness_seconds=entry.options.get(
|
||||
CONF_SNAPSHOT_STALENESS, DEFAULT_SNAPSHOT_STALENESS
|
||||
),
|
||||
)
|
||||
# The panel event subscription (the SSE task): a background
|
||||
# task consumes the API service's transition-event stream and
|
||||
|
||||
@@ -43,24 +43,11 @@ conversion matters at setup: HA's real
|
||||
``async_config_entry_first_refresh`` wraps any failed pass in
|
||||
``ConfigEntryNotReady``, so a setup that keys on the original
|
||||
exception type would never match it.)
|
||||
|
||||
Last-good cache and staleness: every successful pass refreshes a cache
|
||||
of the rebuilt snapshot stamped with the :func:`time.monotonic`
|
||||
instant of the success. A typed failure is checked against that stamp
|
||||
BEFORE the pass is declared failed: within the configured staleness
|
||||
threshold (``CONF_SNAPSHOT_STALENESS``, seconds, default three update
|
||||
intervals) the pass SUCCEEDS with the cached snapshot — the panel
|
||||
keeps rendering last-good data and the entities stay available — and
|
||||
the outage is logged as a warning. Entities go unavailable only once
|
||||
the cache is older than the threshold (or before the first success);
|
||||
a later successful fetch refreshes the cache and the entities recover
|
||||
on their own, without a config-entry reload.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -72,7 +59,6 @@ from homeassistant.helpers.update_coordinator import (
|
||||
from .api_client import NestQuestApiClient, NestQuestApiError, resolve_api_config
|
||||
from .const import (
|
||||
CONF_UPDATE_INTERVAL,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
@@ -190,17 +176,6 @@ class _UnconfiguredApiClient:
|
||||
)
|
||||
|
||||
|
||||
def _monotonic() -> float:
|
||||
"""The monotonic clock the staleness math reads.
|
||||
|
||||
A one-line indirection over :func:`time.monotonic` so the staleness
|
||||
tests can drive the clock deterministically (patch THIS function,
|
||||
never the stdlib clock). Monotonic is deliberate: wall-clock jumps
|
||||
(NTP corrections, suspends) must not shorten or extend the window.
|
||||
"""
|
||||
return time.monotonic()
|
||||
|
||||
|
||||
class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
"""Shared refresh cycle for every NestQuest entity.
|
||||
|
||||
@@ -224,15 +199,6 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
newer one and leave entities wrong until the next poll. Real
|
||||
HA's coordinator already serializes internally; the lock keeps
|
||||
the same guarantee on the stand-in and costs nothing upstream.
|
||||
|
||||
Last-good cache: a successful pass stamps the rebuilt snapshot
|
||||
with the :func:`~.coordinator._monotonic` instant of the success;
|
||||
a typed failure within the configured staleness threshold
|
||||
(``staleness_seconds``, from ``CONF_SNAPSHOT_STALENESS``) serves
|
||||
that cached snapshot instead of failing the pass, so a short API
|
||||
outage keeps the board up. Past the threshold — or before the
|
||||
first success — the pass fails as above, and a later successful
|
||||
pass refreshes the cache and recovers the entities on its own.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -242,7 +208,6 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
entry_id: str,
|
||||
api_client: NestQuestApiClient,
|
||||
update_interval_seconds: int | None = None,
|
||||
staleness_seconds: int | None = None,
|
||||
) -> None:
|
||||
interval = update_interval_seconds
|
||||
if (
|
||||
@@ -251,19 +216,6 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
or interval < MIN_UPDATE_INTERVAL
|
||||
):
|
||||
interval = DEFAULT_UPDATE_INTERVAL
|
||||
staleness = staleness_seconds
|
||||
if (
|
||||
not isinstance(staleness, int)
|
||||
or isinstance(staleness, bool)
|
||||
or staleness < interval
|
||||
):
|
||||
# A missing or nonsensical threshold falls back to the
|
||||
# shipped default; a configured-but-too-short one (below
|
||||
# even one poll interval) falls back to whichever of
|
||||
# default/interval spans at least one failed poll, so the
|
||||
# cache is never dead on arrival. (The options flow
|
||||
# validates the same rule at the form.)
|
||||
staleness = max(DEFAULT_SNAPSHOT_STALENESS, interval)
|
||||
super().__init__(
|
||||
hass,
|
||||
LOGGER,
|
||||
@@ -273,14 +225,6 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
self.entry_id = entry_id
|
||||
self.api_client = api_client
|
||||
self._refresh_lock = asyncio.Lock()
|
||||
#: The configured last-good window, in SECONDS (const.py:
|
||||
#: CONF_SNAPSHOT_STALENESS / DEFAULT_SNAPSHOT_STALENESS).
|
||||
self._staleness_seconds = staleness
|
||||
#: The last-good cache: the snapshot from the most recent
|
||||
#: SUCCESSFUL fetch and the :func:`time.monotonic` instant it
|
||||
#: landed. Both stay None until the first success.
|
||||
self._last_good_snapshot: NestQuestSnapshot | None = None
|
||||
self._last_good_monotonic: float | None = None
|
||||
|
||||
async def async_refresh(self) -> None:
|
||||
"""One refresh at a time; a queued refresh runs AFTER the
|
||||
@@ -292,19 +236,8 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
async def _async_update_data(self) -> NestQuestSnapshot:
|
||||
"""One refresh pass: fetch the panel snapshot and rebuild it.
|
||||
|
||||
A successful pass rebuilds the snapshot and refreshes the
|
||||
last-good cache (the snapshot plus the
|
||||
:func:`time.monotonic` instant of the success).
|
||||
|
||||
A typed API failure (unconfigured token stub, transport
|
||||
failure, non-2xx response) is first checked against that
|
||||
stamp: WITHIN the configured staleness threshold (elapsed time
|
||||
since the last successful fetch, inclusive of the threshold
|
||||
itself) the pass SUCCEEDS with the cached snapshot — the panel
|
||||
keeps rendering last-good data, the entities stay available —
|
||||
and the outage is logged as a clear warning (never silent).
|
||||
With no cache yet, or past the threshold, the typed error is
|
||||
converted to
|
||||
failure, non-2xx response) is converted to
|
||||
:class:`~homeassistant.helpers.update_coordinator.UpdateFailed`
|
||||
— the exception HA's coordinator machinery records as a failed
|
||||
pass (``last_update_success = False``, ``data`` unchanged) so
|
||||
@@ -315,31 +248,11 @@ class NestQuestCoordinator(DataUpdateCoordinator):
|
||||
try:
|
||||
payload = await self.api_client.get_snapshot()
|
||||
except NestQuestApiError as err:
|
||||
now = _monotonic()
|
||||
cached = self._last_good_snapshot
|
||||
fetched_at = self._last_good_monotonic
|
||||
if (
|
||||
cached is not None
|
||||
and fetched_at is not None
|
||||
and now - fetched_at <= self._staleness_seconds
|
||||
):
|
||||
LOGGER.warning(
|
||||
"NestQuest API refresh failed (%s); serving the "
|
||||
"last-good snapshot fetched %.0f s ago, within the "
|
||||
"%d s staleness threshold",
|
||||
err,
|
||||
now - fetched_at,
|
||||
self._staleness_seconds,
|
||||
)
|
||||
return cached
|
||||
LOGGER.error(
|
||||
"NestQuest coordinator refresh failed: %s", err
|
||||
)
|
||||
raise UpdateFailed(str(err)) from err
|
||||
snapshot = snapshot_from_api_payload(payload)
|
||||
self._last_good_snapshot = snapshot
|
||||
self._last_good_monotonic = _monotonic()
|
||||
return snapshot
|
||||
return snapshot_from_api_payload(payload)
|
||||
|
||||
|
||||
def coordinator_client_from_entry(
|
||||
|
||||
@@ -81,21 +81,6 @@ CONF_UPDATE_INTERVAL = "update_interval"
|
||||
DEFAULT_UPDATE_INTERVAL = 300
|
||||
MIN_UPDATE_INTERVAL = 30
|
||||
|
||||
# Last-good snapshot staleness (Feature 18), in SECONDS: how long the
|
||||
# coordinator keeps SERVING the last good snapshot after the API stops
|
||||
# answering. A failed poll whose elapsed time since the last successful
|
||||
# fetch is within the threshold returns the cached snapshot (the panel
|
||||
# keeps rendering last-good data, entities stay available); past it the
|
||||
# poll fails the HA way and the entities go unavailable. The default is
|
||||
# 3x the default update interval (900 s = 15 minutes): three consecutive
|
||||
# failed five-minute polls before the board is declared stale — enough
|
||||
# to ride out an API service restart, short enough not to render a
|
||||
# days-old board all day. Validation floor: the threshold must be at
|
||||
# least the configured update interval, or the cache could never span
|
||||
# even one failed poll.
|
||||
CONF_SNAPSHOT_STALENESS = "snapshot_staleness"
|
||||
DEFAULT_SNAPSHOT_STALENESS = 3 * DEFAULT_UPDATE_INTERVAL
|
||||
|
||||
# Notification automations (Feature 11). The notify target is a free-text
|
||||
# Home Assistant service name (e.g. "notify.mobile_app_dads_phone") the
|
||||
# household fills in — never a hard-coded personal target; the times are
|
||||
|
||||
@@ -23,7 +23,6 @@ from .const import (
|
||||
CONF_NOTIFY_TARGET,
|
||||
CONF_PANEL_IDLE_TIMEOUT,
|
||||
CONF_PANEL_TOKEN,
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
@@ -34,7 +33,6 @@ from .const import (
|
||||
DEFAULT_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_PANEL_IDLE_TIMEOUT,
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
MIN_UPDATE_INTERVAL,
|
||||
@@ -52,18 +50,8 @@ def _parse_time(value: str) -> bool:
|
||||
return TIME_PATTERN.fullmatch(value) is not None
|
||||
|
||||
|
||||
def _async_validate(
|
||||
user_input: dict[str, Any],
|
||||
current: dict[str, Any] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Validate user input and return field-level errors instead of raising.
|
||||
|
||||
``current`` carries the stored values (entry options → entry data →
|
||||
defaults) so a raw submit that sets one field but omits a sibling it
|
||||
is validated against (the staleness threshold vs. the update
|
||||
interval) can still check the effective pair; raw submits omitting
|
||||
BOTH keys keep their stored values untouched.
|
||||
"""
|
||||
def _async_validate(user_input: dict[str, Any]) -> dict[str, str]:
|
||||
"""Validate user input and return field-level errors instead of raising."""
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
horizon_days = user_input.get(CONF_HORIZON_DAYS)
|
||||
@@ -98,33 +86,6 @@ def _async_validate(
|
||||
):
|
||||
errors[CONF_UPDATE_INTERVAL] = "invalid"
|
||||
|
||||
# The last-good staleness threshold (Feature 18) is OPTIONAL in raw
|
||||
# submits the same way: a missing key keeps the current value. It
|
||||
# must be a positive int, and at least the EFFECTIVE update interval
|
||||
# (the one this submit carries, else the stored or default one) — a
|
||||
# threshold shorter than the poll cadence could never serve even one
|
||||
# cached snapshot.
|
||||
staleness = user_input.get(CONF_SNAPSHOT_STALENESS)
|
||||
if staleness is not None and (
|
||||
isinstance(staleness, bool)
|
||||
or not isinstance(staleness, int)
|
||||
or staleness < 1
|
||||
):
|
||||
errors[CONF_SNAPSHOT_STALENESS] = "invalid"
|
||||
elif staleness is not None and not errors.get(CONF_UPDATE_INTERVAL):
|
||||
stored_interval = (current or {}).get(CONF_UPDATE_INTERVAL)
|
||||
effective_interval = update_interval
|
||||
if effective_interval is None and (
|
||||
isinstance(stored_interval, int)
|
||||
and not isinstance(stored_interval, bool)
|
||||
and stored_interval >= MIN_UPDATE_INTERVAL
|
||||
):
|
||||
effective_interval = stored_interval
|
||||
if effective_interval is None:
|
||||
effective_interval = DEFAULT_UPDATE_INTERVAL
|
||||
if staleness < effective_interval:
|
||||
errors[CONF_SNAPSHOT_STALENESS] = "invalid_staleness"
|
||||
|
||||
# The notification section (Feature 11) is OPTIONAL in raw submits
|
||||
# the same way: a missing key keeps the current value. The three
|
||||
# times are strict HH:MM; the notify target is a non-empty HA
|
||||
@@ -218,14 +179,6 @@ def _build_schema(
|
||||
vol.Required(
|
||||
CONF_UPDATE_INTERVAL, default=current[CONF_UPDATE_INTERVAL]
|
||||
): int,
|
||||
# The last-good staleness threshold (Feature 18): how long the
|
||||
# coordinator keeps serving the cached snapshot after the API
|
||||
# stops answering. Schema-validated submits always carry it
|
||||
# (the default pre-fills from the stored value); raw callers
|
||||
# omitting it keep their stored value (see _async_validate).
|
||||
vol.Required(
|
||||
CONF_SNAPSHOT_STALENESS, default=current[CONF_SNAPSHOT_STALENESS]
|
||||
): int,
|
||||
vol.Required(
|
||||
CONF_NOTIFY_TARGET, default=current[CONF_NOTIFY_TARGET]
|
||||
): str,
|
||||
@@ -338,7 +291,7 @@ class NestQuestOptionsFlow(config_entries.OptionsFlowWithConfigEntry):
|
||||
),
|
||||
)
|
||||
|
||||
errors = _async_validate(user_input, self._current_values())
|
||||
errors = _async_validate(user_input)
|
||||
# The admin ids are validated only when the key is present:
|
||||
# schema-validated submits always carry it (vol.Optional's
|
||||
# default fills from the current allowlist), while raw callers
|
||||
@@ -401,10 +354,6 @@ class NestQuestOptionsFlow(config_entries.OptionsFlowWithConfigEntry):
|
||||
CONF_UPDATE_INTERVAL,
|
||||
self._current_values()[CONF_UPDATE_INTERVAL],
|
||||
),
|
||||
CONF_SNAPSHOT_STALENESS: user_input.get(
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
self._current_values()[CONF_SNAPSHOT_STALENESS],
|
||||
),
|
||||
}
|
||||
# The notification section (Feature 11) stores the household's
|
||||
# choices the same fall-back-to-current way, so raw submits
|
||||
@@ -449,7 +398,6 @@ class NestQuestOptionsFlow(config_entries.OptionsFlowWithConfigEntry):
|
||||
(CONF_DAY_ROLLOVER_TIME, DEFAULT_DAY_ROLLOVER_TIME),
|
||||
(CONF_PANEL_IDLE_TIMEOUT, DEFAULT_PANEL_IDLE_TIMEOUT),
|
||||
(CONF_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL),
|
||||
(CONF_SNAPSHOT_STALENESS, DEFAULT_SNAPSHOT_STALENESS),
|
||||
(CONF_NOTIFY_TARGET, ""),
|
||||
(CONF_MORNING_SUMMARY_TIME, DEFAULT_MORNING_SUMMARY_TIME),
|
||||
(CONF_AFTERNOON_REMINDER_TIME, DEFAULT_AFTERNOON_REMINDER_TIME),
|
||||
|
||||
@@ -6,10 +6,7 @@ call time through the injected ``find_runtime`` callable. Permission
|
||||
checks are Feature 09 later tasks — this module only validates payload
|
||||
shape and forwards to the Feature 03/06/08 business layers (the
|
||||
presence writes included, through :mod:`.presence_management` — the
|
||||
ONE implementation the API admin plane shares). Since Feature 18 the
|
||||
integration is a client of the NestQuest API service, so
|
||||
``complete_quest`` proxies to the API's panel complete route through
|
||||
the entry's shared API client instead of writing any database.
|
||||
ONE implementation the API admin plane shares).
|
||||
``export_history_csv`` is registered with a schema but raises until
|
||||
Feature 13. ``regenerate`` is supplied by the caller so
|
||||
the Feature 07 handler stays the one in ``__init__``.
|
||||
@@ -29,7 +26,6 @@ from . import children as children_layer
|
||||
from . import completion as completion_layer
|
||||
from . import presence_management as presence_management_layer
|
||||
from . import quest_definitions as quest_definitions_layer
|
||||
from .api_client import NestQuestApiError
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
DOMAIN_SERVICES,
|
||||
@@ -46,7 +42,7 @@ from .const import (
|
||||
SERVICE_UNCOMPLETE_QUEST,
|
||||
SERVICE_UPDATE_QUEST_DEFINITION,
|
||||
)
|
||||
from .events import fire_quest_uncompleted
|
||||
from .events import fire_quest_completed, fire_quest_uncompleted
|
||||
from .permissions import permission_gate
|
||||
from .recurrence import ScheduleRule
|
||||
from .service_policy import SERVICE_POLICY
|
||||
@@ -305,50 +301,22 @@ def _complete_quest(
|
||||
async def _handler(call: Any) -> None:
|
||||
runtime = _require_runtime(hass, find_runtime)
|
||||
instance_id = call.data["instance_id"]
|
||||
# The panel contract (decision 9): a tap completes as the
|
||||
# tapped child profile, the only actor shape the API's panel
|
||||
# route accepts. The payload schema is unchanged — the panel
|
||||
# cards call it with instance_id, actor=panel, actor_child_id.
|
||||
actor = _actor_kwargs(call)
|
||||
if actor["actor_source"] != ACTOR_PANEL:
|
||||
raise HomeAssistantError(
|
||||
"nestquest.complete_quest completes through the API's "
|
||||
"panel route as the tapped child profile; actor must "
|
||||
"be 'panel' with actor_child_id"
|
||||
)
|
||||
# The entry's ONE shared API client (built at setup): the
|
||||
# coordinator's snapshot poll, the SSE subscription, and this
|
||||
# proxy all ride the same instance. An entry with no panel
|
||||
# token runs the unconfigured stub, which has no completion
|
||||
# surface — fail fast with a clear, token-free message.
|
||||
complete_instance = getattr(
|
||||
getattr(runtime.coordinator, "api_client", None),
|
||||
"complete_instance",
|
||||
None,
|
||||
# ``appended`` is decided under the same lock as the write, so
|
||||
# a concurrent duplicate call (a double tap) can not produce a
|
||||
# second transition event: the loser appends nothing.
|
||||
result = await completion_layer.complete_instance(
|
||||
runtime.database,
|
||||
instance_id,
|
||||
**_actor_kwargs(call),
|
||||
)
|
||||
if complete_instance is None:
|
||||
raise HomeAssistantError(
|
||||
"NestQuest API is not configured; cannot complete a "
|
||||
"quest"
|
||||
if result.appended:
|
||||
await fire_quest_completed(
|
||||
hass,
|
||||
runtime.database,
|
||||
instance_id,
|
||||
was_on_time=result.was_on_time,
|
||||
)
|
||||
try:
|
||||
await complete_instance(instance_id, actor["actor_child_id"])
|
||||
except NestQuestApiError as err:
|
||||
# The typed API failure surfaces as a service error the
|
||||
# caller sees — never swallowed, never retried here. The
|
||||
# typed message names method, path, and status only; the
|
||||
# panel token never appears in it.
|
||||
raise HomeAssistantError(
|
||||
f"NestQuest quest completion failed: {err}"
|
||||
) from err
|
||||
# NO local completion write and NO local event: the API service
|
||||
# emits the transition on its SSE stream and the integration's
|
||||
# subscription re-fires it on the bus — firing it here too
|
||||
# would double-fire. The immediate refresh keeps the old
|
||||
# behaviour where the sensors reflect the completion the
|
||||
# moment the service call returns instead of waiting for the
|
||||
# poll interval.
|
||||
await _refresh_entities(runtime)
|
||||
await _refresh_entities(runtime)
|
||||
|
||||
return _with_errors(_handler)
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
"horizon_days": "Generation horizon (days)",
|
||||
"day_rollover_time": "Day rollover time (HH:MM)",
|
||||
"panel_idle_timeout": "Panel idle timeout (seconds)",
|
||||
"snapshot_staleness": "Last-good snapshot staleness (seconds)",
|
||||
"api_base_url": "NestQuest API base URL (http://host:port)",
|
||||
"panel_token": "Panel service token",
|
||||
"admin_user_ids": "Admin users (parents)"
|
||||
@@ -34,7 +33,6 @@
|
||||
"invalid": "Invalid value.",
|
||||
"invalid_time": "Time must use 24-hour HH:MM format.",
|
||||
"invalid_url": "Enter the API base URL as a full http:// or https:// URL with a host.",
|
||||
"invalid_staleness": "Last-good snapshot staleness must be at least the update interval.",
|
||||
"no_admins": "Select at least one admin user; an empty allowlist would lock everyone out.",
|
||||
"invalid_admin": "Invalid admin selection."
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
"horizon_days": "Generation horizon (days)",
|
||||
"day_rollover_time": "Day rollover time (HH:MM)",
|
||||
"panel_idle_timeout": "Panel idle timeout (seconds)",
|
||||
"snapshot_staleness": "Last-good snapshot staleness (seconds)",
|
||||
"api_base_url": "NestQuest API base URL (http://host:port)",
|
||||
"panel_token": "Panel service token",
|
||||
"admin_user_ids": "Admin users (parents)"
|
||||
@@ -34,7 +33,6 @@
|
||||
"invalid": "Invalid value.",
|
||||
"invalid_time": "Time must use 24-hour HH:MM format.",
|
||||
"invalid_url": "Enter the API base URL as a full http:// or https:// URL with a host.",
|
||||
"invalid_staleness": "Last-good snapshot staleness must be at least the update interval.",
|
||||
"no_admins": "Select at least one admin user; an empty allowlist would lock everyone out.",
|
||||
"invalid_admin": "Invalid admin selection."
|
||||
}
|
||||
|
||||
+3
-127
@@ -757,16 +757,6 @@ class LazyLocalSnapshotClient:
|
||||
coordinator reconstructs from a byte-identical payload without any
|
||||
network or FastAPI machinery.
|
||||
|
||||
``complete_instance`` bridges the panel complete route the same
|
||||
way (the ``nestquest.complete_quest`` proxy calls it through the
|
||||
API client): it resolves the entry's database and delegates to the
|
||||
SAME core completion the API route delegates to, with the panel
|
||||
actor shape, and answers the route's ``{"status": ...}`` body.
|
||||
Like the real API service it publishes its transition events on
|
||||
the SSE stream — NOT on the Home Assistant bus and NOT from the
|
||||
service handler; tests that assert bus events drive them through
|
||||
the SSE subscription the way production delivers them.
|
||||
|
||||
The resolution is LAZY on purpose: the coordinator's factory runs
|
||||
mid-setup, before the runtime record exists, so the first refresh
|
||||
(and any refresh while the entry is torn down) serves an EMPTY but
|
||||
@@ -777,29 +767,6 @@ class LazyLocalSnapshotClient:
|
||||
self._hass = hass
|
||||
self._entry_id = entry_id
|
||||
self.calls = 0
|
||||
#: Every ``(instance_id, CompletionResult)`` this stand-in
|
||||
# produced, in call order — tests read ``appended`` /
|
||||
# ``was_on_time`` off these to check the completion verdicts.
|
||||
self.completions = []
|
||||
#: The SSE frames the stand-in published for its completions
|
||||
# (the API service's stream content), drained by
|
||||
#: :func:`refire_api_transitions`.
|
||||
self.published_frames = []
|
||||
|
||||
def _live_runtime(self):
|
||||
"""The entry's runtime record, or ``None`` before/after setup."""
|
||||
from custom_components.nestquest.const import DOMAIN as NQ_DOMAIN
|
||||
|
||||
runtime = self._hass.data.get(NQ_DOMAIN, {}).get(self._entry_id)
|
||||
database = getattr(runtime, "database", None)
|
||||
if database is None or not getattr(database, "connected", True):
|
||||
return None
|
||||
return runtime
|
||||
|
||||
def _live_database(self):
|
||||
"""The entry's open database, or ``None`` before/after setup."""
|
||||
runtime = self._live_runtime()
|
||||
return None if runtime is None else runtime.database
|
||||
|
||||
async def get_snapshot(self):
|
||||
import datetime
|
||||
@@ -809,14 +776,14 @@ class LazyLocalSnapshotClient:
|
||||
from custom_components.nestquest.core import snapshot as core_snapshot
|
||||
|
||||
self.calls += 1
|
||||
runtime = self._live_runtime()
|
||||
if runtime is None:
|
||||
runtime = self._hass.data.get(NQ_DOMAIN, {}).get(self._entry_id)
|
||||
database = getattr(runtime, "database", None)
|
||||
if database is None or not getattr(database, "connected", True):
|
||||
return {
|
||||
"today_iso": datetime.date.today().isoformat(),
|
||||
"cycle_day": 0,
|
||||
"children": [],
|
||||
}
|
||||
database = runtime.database
|
||||
settings = getattr(runtime, "settings", None)
|
||||
# The HA-LOCAL now, the same single clock read the production
|
||||
# coordinator used to hand the builder: the hass stub's
|
||||
@@ -846,44 +813,6 @@ class LazyLocalSnapshotClient:
|
||||
],
|
||||
}
|
||||
|
||||
async def complete_instance(self, instance_id: int, actor_child_id: int):
|
||||
"""The panel complete route's stand-in: complete through the
|
||||
SAME core completion the route delegates to, panel actor
|
||||
shape, publish the route's SSE transition frames (built by the
|
||||
same core builders, appended completions only — see
|
||||
``api/routes_panel.py``), and answer the route's
|
||||
``{"status": ...}`` body."""
|
||||
import datetime
|
||||
|
||||
from custom_components.nestquest.completion import complete_instance
|
||||
from custom_components.nestquest.core import events as core_events
|
||||
|
||||
result = await complete_instance(
|
||||
self._live_database(),
|
||||
instance_id,
|
||||
actor_source="panel",
|
||||
actor_child_id=actor_child_id,
|
||||
)
|
||||
self.completions.append((instance_id, result))
|
||||
if result.appended:
|
||||
# The route publishes the transition the moment the core
|
||||
# write lands (appended completions only), evaluating the
|
||||
# day-complete rule against the API host's local date —
|
||||
# the frames queue here for the SSE stream to carry.
|
||||
event_type, payload = await core_events.build_quest_completed_event(
|
||||
self._live_database(),
|
||||
instance_id,
|
||||
was_on_time=result.was_on_time,
|
||||
)
|
||||
self.published_frames.append((event_type, payload))
|
||||
now = datetime.datetime.now().astimezone()
|
||||
day_complete = await core_events.build_child_day_complete_event(
|
||||
self._live_database(), payload, today=now.date()
|
||||
)
|
||||
if day_complete is not None:
|
||||
self.published_frames.append(day_complete)
|
||||
return {"status": str(result)}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def coordinator_serves_local_snapshot():
|
||||
@@ -929,59 +858,6 @@ def set_coordinator_client(entry, client):
|
||||
return client
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
"""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
|
||||
database 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 datetime
|
||||
|
||||
import pytest
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from conftest import (
|
||||
LazyLocalSnapshotClient,
|
||||
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_ADMIN_USER_IDS,
|
||||
CONF_PANEL_TOKEN,
|
||||
DOMAIN,
|
||||
EVENT_CHILD_DAY_COMPLETE,
|
||||
EVENT_QUEST_COMPLETED,
|
||||
SERVICE_COMPLETE_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
|
||||
|
||||
ADMIN_CTX = {"user_id": "admin-1"}
|
||||
|
||||
|
||||
class _RecordingApiClient(LazyLocalSnapshotClient):
|
||||
"""Snapshot-only stand-in that RECORDS completion calls.
|
||||
|
||||
``complete_instance`` deliberately performs NO database write: the
|
||||
API service is remote, and the assertions below must be able to
|
||||
prove the service handler itself completed nothing locally.
|
||||
"""
|
||||
|
||||
def __init__(self, hass, entry_id: str) -> None:
|
||||
super().__init__(hass, entry_id)
|
||||
self.complete_calls: list[tuple[int, int]] = []
|
||||
|
||||
async def complete_instance(
|
||||
self, instance_id: int, actor_child_id: int
|
||||
) -> dict:
|
||||
self.complete_calls.append((instance_id, actor_child_id))
|
||||
return {"status": "done"}
|
||||
|
||||
|
||||
class _FailingApiClient(_RecordingApiClient):
|
||||
"""A stand-in whose completion fails the way the client types it."""
|
||||
|
||||
def __init__(self, hass, entry_id: str, error: NestQuestApiError) -> None:
|
||||
super().__init__(hass, entry_id)
|
||||
self._error = error
|
||||
|
||||
async def complete_instance(
|
||||
self, instance_id: int, actor_child_id: int
|
||||
) -> dict:
|
||||
self.complete_calls.append((instance_id, actor_child_id))
|
||||
raise self._error
|
||||
|
||||
|
||||
async def _setup_seeded_entry(hass, make_entry, client):
|
||||
"""Wire, script, and set up an entry with one child's daily quest."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
data={
|
||||
CONF_ADMIN_USER_IDS: [ADMIN_CTX["user_id"]],
|
||||
CONF_PANEL_TOKEN: "secret-panel-token",
|
||||
}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
set_coordinator_client(entry, client)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
database = entry.runtime_data.database
|
||||
from custom_components.nestquest.children import create_child
|
||||
|
||||
child = await create_child(database, "Ada")
|
||||
today = datetime.date.today()
|
||||
await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
ScheduleRule.from_dict(
|
||||
{"rule_type": "daily", "start_date": today.isoformat()}
|
||||
),
|
||||
[child.id],
|
||||
["morning"],
|
||||
)
|
||||
end = (today + datetime.timedelta(days=3)).isoformat()
|
||||
await materialize(database, today.isoformat(), end, today=today)
|
||||
instances = await QuestInstancesDao(database).list_by_date_range(
|
||||
child.id, today.isoformat(), today.isoformat()
|
||||
)
|
||||
assert instances
|
||||
return entry, client, child, instances[0]
|
||||
|
||||
|
||||
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, completes NOTHING locally, fires NO
|
||||
local event, and refreshes the coordinator immediately."""
|
||||
entry, client, child, instance = await _setup_seeded_entry(
|
||||
hass, make_entry, _RecordingApiClient(hass, "test_entry")
|
||||
)
|
||||
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": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
|
||||
assert client.complete_calls == [(instance.id, child.id)]
|
||||
# No local completion: the instance is still open in the local
|
||||
# database — only the API service writes (through its own client).
|
||||
from custom_components.nestquest.completion import instance_state
|
||||
|
||||
assert (
|
||||
await instance_state(entry.runtime_data.database, instance.id)
|
||||
== "open"
|
||||
)
|
||||
# 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 completed or fired
|
||||
locally, and no refresh for a mutation that never happened."""
|
||||
entry, client, child, instance = await _setup_seeded_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
_FailingApiClient(hass, "test_entry", error),
|
||||
)
|
||||
refreshes = _record_refreshes(entry)
|
||||
|
||||
with pytest.raises(HomeAssistantError, match=fragment) as excinfo:
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
# 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 == [(instance.id, child.id)]
|
||||
from custom_components.nestquest.completion import instance_state
|
||||
|
||||
assert (
|
||||
await instance_state(entry.runtime_data.database, instance.id)
|
||||
== "open"
|
||||
)
|
||||
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
|
||||
|
||||
entry, _client, child, instance = await _setup_seeded_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": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
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."""
|
||||
entry, client, child, instance = await _setup_seeded_entry(
|
||||
hass, make_entry, _RecordingApiClient(hass, "test_entry")
|
||||
)
|
||||
|
||||
with pytest.raises(HomeAssistantError, match="actor must be 'panel'"):
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance.id,
|
||||
"actor": "user",
|
||||
"actor_user_id": ADMIN_CTX["user_id"],
|
||||
},
|
||||
context=ADMIN_CTX,
|
||||
)
|
||||
assert client.complete_calls == []
|
||||
+9
-196
@@ -12,7 +12,6 @@ cycle day, and the unconfigured / failed-fetch behaviour.
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -24,9 +23,7 @@ from custom_components.nestquest.api_client import (
|
||||
NestQuestApiError,
|
||||
)
|
||||
from custom_components.nestquest.const import (
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DOMAIN,
|
||||
)
|
||||
@@ -70,23 +67,6 @@ class StubSnapshotClient:
|
||||
return outcome
|
||||
|
||||
|
||||
class FakeMonotonic:
|
||||
"""A deterministic stand-in for the staleness clock.
|
||||
|
||||
The coordinator reads elapsed time through
|
||||
:func:`custom_components.nestquest.coordinator._monotonic`; tests
|
||||
patch that seam with an instance of this class and advance ``now``
|
||||
by whole seconds, so the staleness window is exercised without any
|
||||
real waiting.
|
||||
"""
|
||||
|
||||
def __init__(self, start: float = 1000.0) -> None:
|
||||
self.now = start
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.now
|
||||
|
||||
|
||||
#: A fixture panel snapshot (the documented Feature 16 route shape):
|
||||
#: two children — Ada owes one, owes none of it yet, is away today with
|
||||
#: a returns date; Bo completed his only quest and is present.
|
||||
@@ -360,20 +340,13 @@ async def test_coordinator_entities_read_the_api_snapshot(hass, make_entry) -> N
|
||||
await async_unload_entry(hass, entry)
|
||||
|
||||
|
||||
async def test_coordinator_failed_fetch_marks_unavailable(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""A failed fetch (transport failure or non-2xx — both typed) PAST
|
||||
the staleness threshold is a FAILED refresh pass: the update pass
|
||||
converts the typed error to UpdateFailed (the exception HA's
|
||||
coordinator machinery records as a failed pass, chaining the typed
|
||||
error as ``__cause__``), the refresh records the failure instead of
|
||||
raising, and data keeps its last good value. (Within the threshold
|
||||
the last-good cache serves instead — the staleness tests below.)"""
|
||||
import custom_components.nestquest.coordinator as coordinator_module
|
||||
|
||||
clock = FakeMonotonic()
|
||||
monkeypatch.setattr(coordinator_module, "_monotonic", clock)
|
||||
async def test_coordinator_failed_fetch_marks_unavailable(hass, make_entry) -> None:
|
||||
"""A failed fetch (transport failure or non-2xx — both typed) is a
|
||||
FAILED refresh pass: the update pass converts the typed error to
|
||||
UpdateFailed (the exception HA's coordinator machinery records as a
|
||||
failed pass, chaining the typed error as ``__cause__``), the refresh
|
||||
records the failure instead of raising, and data keeps its last
|
||||
good value."""
|
||||
error = NestQuestApiError(
|
||||
"NestQuest API GET /api/v1/panel/snapshot failed with HTTP 503",
|
||||
status=503,
|
||||
@@ -386,11 +359,8 @@ async def test_coordinator_failed_fetch_marks_unavailable(
|
||||
assert coordinator.data is not None
|
||||
assert coordinator.last_update_success is True
|
||||
|
||||
# The next pass hits the scripted failure AFTER the cache went
|
||||
# stale — one second past the shipped 900 s default threshold: the
|
||||
# update pass converts the typed error to UpdateFailed, with the
|
||||
# typed error chained.
|
||||
clock.now += DEFAULT_SNAPSHOT_STALENESS + 1
|
||||
# The next pass hits the scripted failure: the update pass converts
|
||||
# the typed error to UpdateFailed, with the typed error chained.
|
||||
with pytest.raises(UpdateFailed, match="HTTP 503") as excinfo:
|
||||
await coordinator._async_update_data()
|
||||
assert isinstance(excinfo.value.__cause__, NestQuestApiError)
|
||||
@@ -406,163 +376,6 @@ async def test_coordinator_failed_fetch_marks_unavailable(
|
||||
assert isinstance(coordinator.last_exception.__cause__, NestQuestApiError)
|
||||
|
||||
|
||||
async def test_coordinator_serves_cached_snapshot_within_staleness(
|
||||
hass, make_entry, monkeypatch, caplog
|
||||
) -> None:
|
||||
"""API down WITHIN the staleness threshold: the failed fetch serves
|
||||
the last-good cache — the pass succeeds with the SAME snapshot, so
|
||||
``last_update_success`` stays True (entities remain available) and
|
||||
the outage is logged as a clear warning, never silently."""
|
||||
import custom_components.nestquest.coordinator as coordinator_module
|
||||
|
||||
clock = FakeMonotonic()
|
||||
monkeypatch.setattr(coordinator_module, "_monotonic", clock)
|
||||
error = NestQuestApiError(
|
||||
"NestQuest API GET /api/v1/panel/snapshot failed with HTTP 503",
|
||||
status=503,
|
||||
)
|
||||
# Setup's first refresh consumes the good snapshot; the two test
|
||||
# passes hit the scripted failure.
|
||||
client = StubSnapshotClient(FIXTURE_SNAPSHOT, error, error)
|
||||
_entry, coordinator = await _wire_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
client,
|
||||
options={CONF_UPDATE_INTERVAL: 300, CONF_SNAPSHOT_STALENESS: 900},
|
||||
)
|
||||
# The successful first pass cached the snapshot (stamped at the
|
||||
# fake clock's start).
|
||||
first = coordinator.data
|
||||
assert first is not None
|
||||
assert coordinator.last_update_success is True
|
||||
|
||||
# The API goes down 900 s after that success — exactly the
|
||||
# threshold, still WITHIN the inclusive window: the pass serves the
|
||||
# cached snapshot instead of failing.
|
||||
clock.now += 900
|
||||
with caplog.at_level(
|
||||
logging.WARNING, logger="custom_components.nestquest"
|
||||
):
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.last_update_success is True
|
||||
assert coordinator.data is first
|
||||
assert coordinator.data.children[0].child_name == "Ada"
|
||||
# The fetch WAS attempted (and failed) — the cache is a fallback,
|
||||
# not a replacement for polling.
|
||||
assert client.calls == 2
|
||||
assert any(
|
||||
"last-good" in record.getMessage() for record in caplog.records
|
||||
)
|
||||
|
||||
|
||||
async def test_coordinator_recovers_without_reload_after_outage(
|
||||
hass, make_entry, monkeypatch
|
||||
) -> None:
|
||||
"""The full outage arc: within the threshold the cache serves, past
|
||||
it the entities go unavailable, and when the API comes back the
|
||||
next pass succeeds with the FRESH snapshot, re-arms the cache, and
|
||||
the entities recover — without any config-entry reload."""
|
||||
import custom_components.nestquest.coordinator as coordinator_module
|
||||
|
||||
clock = FakeMonotonic()
|
||||
monkeypatch.setattr(coordinator_module, "_monotonic", clock)
|
||||
outage = NestQuestApiError(
|
||||
"NestQuest API GET /api/v1/panel/snapshot failed with HTTP 503",
|
||||
status=503,
|
||||
)
|
||||
post_recovery_outage = NestQuestApiError(
|
||||
"NestQuest API GET /api/v1/panel/snapshot failed with HTTP 502",
|
||||
status=502,
|
||||
)
|
||||
fresh = {**FIXTURE_SNAPSHOT, "cycle_day": 4}
|
||||
client = StubSnapshotClient(
|
||||
FIXTURE_SNAPSHOT, outage, outage, fresh, post_recovery_outage
|
||||
)
|
||||
_entry, coordinator = await _wire_entry(
|
||||
hass,
|
||||
make_entry,
|
||||
client,
|
||||
options={CONF_UPDATE_INTERVAL: 300, CONF_SNAPSHOT_STALENESS: 900},
|
||||
)
|
||||
first = coordinator.data
|
||||
assert first.cycle_day == 3
|
||||
|
||||
# Within the threshold: the outage serves the cache.
|
||||
clock.now += 300
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.last_update_success is True
|
||||
assert coordinator.data is first
|
||||
|
||||
# Past the threshold: the outage fails the pass (unavailable).
|
||||
clock.now += 901
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.last_update_success is False
|
||||
|
||||
# The API returns: the next pass succeeds with the fresh snapshot
|
||||
# and no reload was involved anywhere.
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.last_update_success is True
|
||||
fresh_data = coordinator.data
|
||||
assert fresh_data.cycle_day == 4
|
||||
assert hass.registry.reloaded == []
|
||||
|
||||
# The success re-armed the cache with the FRESH stamp: another
|
||||
# outage within the threshold serves the new snapshot now, not the
|
||||
# pre-outage one.
|
||||
clock.now += 300
|
||||
await coordinator.async_refresh()
|
||||
assert coordinator.last_update_success is True
|
||||
assert coordinator.data is fresh_data
|
||||
assert client.calls == 5
|
||||
|
||||
|
||||
async def test_setup_creates_coordinator_with_configured_staleness(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The staleness threshold rides the entry options into the
|
||||
coordinator, alongside the update interval."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
options={CONF_UPDATE_INTERVAL: 60, CONF_SNAPSHOT_STALENESS: 600}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
assert coordinator._staleness_seconds == 600
|
||||
|
||||
|
||||
async def test_setup_staleness_below_interval_falls_back_to_default(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""A stored threshold below the update interval (a raw hand-edited
|
||||
option) never reaches the coordinator as-is: it falls back to the
|
||||
shipped default, which still spans the configured interval."""
|
||||
entry = wire_entry_to_registry(
|
||||
make_entry(
|
||||
options={CONF_UPDATE_INTERVAL: 600, CONF_SNAPSHOT_STALENESS: 60}
|
||||
),
|
||||
hass.registry,
|
||||
)
|
||||
assert await async_setup_entry(hass, entry) is True
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
assert coordinator._staleness_seconds == DEFAULT_SNAPSHOT_STALENESS
|
||||
|
||||
|
||||
async def test_coordinator_staleness_floor_never_below_interval(hass) -> None:
|
||||
"""A threshold below the interval falls back to whichever of
|
||||
default/interval is larger, so the cache can always span at least
|
||||
one failed poll (here the interval exceeds the shipped default)."""
|
||||
coordinator = NestQuestCoordinator(
|
||||
hass,
|
||||
entry_id="floor",
|
||||
api_client=StubSnapshotClient(),
|
||||
update_interval_seconds=1800,
|
||||
staleness_seconds=60,
|
||||
)
|
||||
assert coordinator._staleness_seconds == 1800
|
||||
|
||||
|
||||
async def test_failed_first_refresh_does_not_crash_setup(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
import datetime
|
||||
import re
|
||||
|
||||
from conftest import refire_api_transitions, wire_entry_to_registry
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import (
|
||||
@@ -154,11 +154,6 @@ async def test_entity_and_event_matrix(hass, make_entry) -> None:
|
||||
"actor_child_id": ada.id,
|
||||
},
|
||||
)
|
||||
# The transition events arrive over the API's SSE stream (the
|
||||
# subscription re-fires them), never from the service handler.
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_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"])
|
||||
@@ -239,10 +234,6 @@ async def test_payload_schema_matches_the_documented_contract(
|
||||
"actor_child_id": ada.id,
|
||||
},
|
||||
)
|
||||
# The completed event arrives over the API's SSE stream.
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
payload = hass.bus.fired(EVENT_QUEST_COMPLETED)[0]
|
||||
for key, check in (
|
||||
("child_id", lambda v: isinstance(v, int)),
|
||||
|
||||
+26
-116
@@ -1,21 +1,9 @@
|
||||
"""Tests for the NestQuest bus events (Feature 10, task 6).
|
||||
|
||||
Since Feature 18 the integration is a client of the NestQuest API
|
||||
service: ``nestquest.complete_quest`` proxies to the API's panel
|
||||
complete route and 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 them. The service-driven tests below therefore deliver the
|
||||
frames through :func:`conftest.refire_api_transitions` (the
|
||||
production event path, driven synchronously) before asserting the
|
||||
bus; the shim-level tests drive :mod:`custom_components.nestquest
|
||||
.events` directly, the way its remaining callers do.
|
||||
"""
|
||||
"""Tests for the NestQuest bus events (Feature 10, task 6)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from conftest import refire_api_transitions, wire_entry_to_registry
|
||||
from conftest import wire_entry_to_registry
|
||||
|
||||
from custom_components.nestquest import async_setup_entry
|
||||
from custom_components.nestquest.children import create_child
|
||||
@@ -98,11 +86,6 @@ async def test_quest_completed_fires_with_documented_payload(
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": instance_id, "actor": "panel", "actor_child_id": child.id},
|
||||
)
|
||||
# The completed event arrives over the API's SSE stream (the
|
||||
# subscription re-fires it), never from the service handler.
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
fired = hass.bus.fired(EVENT_QUEST_COMPLETED)
|
||||
assert len(fired) == 1
|
||||
payload = fired[0]
|
||||
@@ -128,15 +111,6 @@ async def test_recomplete_no_op_fires_nothing(hass, make_entry) -> None:
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{"instance_id": instance_id, "actor": "panel", "actor_child_id": child.id},
|
||||
)
|
||||
# The no-op verdict is decided in the API's completion layer: the
|
||||
# second call appended nothing, so the API published no second
|
||||
# frame and the bus stays at exactly one event.
|
||||
client = entry.runtime_data.coordinator.api_client
|
||||
assert [result.appended for _id, result in client.completions] == [
|
||||
True,
|
||||
False,
|
||||
]
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
assert len(hass.bus.fired(EVENT_QUEST_COMPLETED)) == 1
|
||||
|
||||
|
||||
@@ -154,9 +128,6 @@ async def test_child_day_complete_fires_when_day_clears(
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
day_complete = hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)
|
||||
assert len(day_complete) == 1, "exactly one day-complete per cleared day"
|
||||
payload = day_complete[0]
|
||||
@@ -182,12 +153,6 @@ async def test_child_day_complete_does_not_fire_partway(
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
# The API publishes the completion but not a day-complete (the
|
||||
# child's day is not clear yet); the subscription re-fires only
|
||||
# what was published.
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
assert hass.bus.fired(EVENT_CHILD_DAY_COMPLETE) == []
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
@@ -198,9 +163,6 @@ async def test_child_day_complete_does_not_fire_partway(
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
assert len(hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)) == 1
|
||||
|
||||
|
||||
@@ -261,15 +223,6 @@ async def test_appended_verdict_is_atomic_under_duplicate_calls(
|
||||
for _ in range(2)
|
||||
]
|
||||
await asyncio.gather(*calls)
|
||||
# The API's completion layer (the same core lock) decides the
|
||||
# verdict: one call appended, the duplicate did not — so the API
|
||||
# published exactly one frame and the bus carries one event.
|
||||
client = entry.runtime_data.coordinator.api_client
|
||||
assert len(client.completions) == 2
|
||||
assert [result.appended for _id, result in client.completions].count(
|
||||
True
|
||||
) == 1
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
assert len(hass.bus.fired(EVENT_QUEST_COMPLETED)) == 1
|
||||
|
||||
|
||||
@@ -310,9 +263,6 @@ async def test_day_complete_ignored_for_backdated_completion(
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
assert len(hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)) == 1
|
||||
|
||||
await _complete(
|
||||
@@ -330,19 +280,12 @@ async def test_day_complete_ignored_for_backdated_completion(
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
# The service call on the already-done future instance is a no-op
|
||||
# inside the API's completion layer: nothing appended, nothing
|
||||
# published, nothing re-fired — today's single announcement stands.
|
||||
client = entry.runtime_data.coordinator.api_client
|
||||
assert client.completions[-1][1].appended is False
|
||||
await refire_api_transitions(hass, entry, client)
|
||||
assert len(hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)) == 1, (
|
||||
"a back-dated/future completion must not re-announce today"
|
||||
)
|
||||
# The direct business-layer call published nothing (only the API's
|
||||
# completion path publishes), and the follow-up service call on
|
||||
# the now-done future instance was a no-op: today's single
|
||||
# completion stands.
|
||||
# The direct business-layer call fired nothing (only the service
|
||||
# path fires), and the follow-up service call on the now-done
|
||||
# future instance was a no-op: today's single completion stands.
|
||||
assert len(hass.bus.fired(EVENT_QUEST_COMPLETED)) == len(instances)
|
||||
|
||||
|
||||
@@ -381,10 +324,6 @@ async def test_completion_updates_entities_immediately(
|
||||
assert remaining_after == len(instances) - 1, (
|
||||
"sensor must reflect the completion without a manual refresh"
|
||||
)
|
||||
# The transition events arrive over the API's SSE stream.
|
||||
await refire_api_transitions(
|
||||
hass, entry, entry.runtime_data.coordinator.api_client
|
||||
)
|
||||
assert len(hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)) == (
|
||||
1 if len(instances) == 1 else 0
|
||||
)
|
||||
@@ -599,32 +538,17 @@ async def test_shim_fires_completed_before_day_complete(hass, make_entry) -> Non
|
||||
"""The shim fires ``nestquest_quest_completed`` BEFORE
|
||||
``nestquest_child_day_complete`` (the pre-extraction ordering), so
|
||||
a failure in the day-complete DB reads cannot suppress the
|
||||
completed event. Asserted by bus event ORDER, not just counts.
|
||||
|
||||
Driven directly: since Feature 18 the completion service proxies
|
||||
to the API (whose event ordering is tested in test_api_sse.py);
|
||||
this targets the shim module itself, the way its remaining
|
||||
callers invoke it.
|
||||
"""
|
||||
from custom_components.nestquest.completion import (
|
||||
complete_instance as _complete,
|
||||
)
|
||||
from custom_components.nestquest.events import fire_quest_completed
|
||||
|
||||
completed event. Asserted by bus event ORDER, not just counts."""
|
||||
entry, child, instances = await _setup_and_seed(hass, make_entry)
|
||||
database = entry.runtime_data.database
|
||||
for instance in instances:
|
||||
result = await _complete(
|
||||
database,
|
||||
instance.id,
|
||||
actor_source="panel",
|
||||
actor_child_id=child.id,
|
||||
)
|
||||
await fire_quest_completed(
|
||||
hass,
|
||||
database,
|
||||
instance.id,
|
||||
was_on_time=result.was_on_time,
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
ordered = [
|
||||
etype for etype, _payload in hass.bus.events
|
||||
@@ -808,31 +732,21 @@ async def test_day_complete_fully_cleared_today_yields_event(
|
||||
async def test_shim_day_complete_uses_ha_local_timezone(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The shim's day-complete rule reads ``hass.config.time_zone``
|
||||
and derives ``today`` in HA-local time, not UTC.
|
||||
"""The day-complete rule reads ``hass.config.time_zone`` and
|
||||
derives ``today`` in HA-local time, not UTC.
|
||||
|
||||
Picks a zone whose current local date differs from UTC, seeds an
|
||||
instance for THAT zone's today (not UTC's today), fires the shim
|
||||
directly for a completion of that instance, and asserts
|
||||
instance for THAT zone's today (not UTC's today), completes it
|
||||
through the service path, and asserts
|
||||
``nestquest_child_day_complete`` fires — proving the local date
|
||||
reached the day-complete rule. If no candidate zone has a
|
||||
different date right now (only possible inside the ~1h window
|
||||
around 12:00 UTC when all zones share one date), the test skips
|
||||
rather than run vacuously.
|
||||
|
||||
Driven directly: since Feature 18 the completion service proxies
|
||||
to the API (whose day-complete ``today`` is the API host's local
|
||||
date, tested in test_api_sse.py); this targets the shim module
|
||||
itself, the way its remaining callers invoke it.
|
||||
"""
|
||||
import datetime as _dt
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from custom_components.nestquest.completion import (
|
||||
complete_instance as _complete,
|
||||
)
|
||||
from custom_components.nestquest.events import fire_quest_completed
|
||||
|
||||
utc_today = _dt.datetime.now(_dt.timezone.utc).date()
|
||||
far_zone = None
|
||||
far_today = None
|
||||
@@ -861,19 +775,15 @@ async def test_shim_day_complete_uses_ha_local_timezone(
|
||||
entry, child, instances = await _setup_and_seed(
|
||||
hass, make_entry, seed_date=far_today
|
||||
)
|
||||
database = entry.runtime_data.database
|
||||
for instance in instances:
|
||||
result = await _complete(
|
||||
database,
|
||||
instance.id,
|
||||
actor_source="panel",
|
||||
actor_child_id=child.id,
|
||||
)
|
||||
await fire_quest_completed(
|
||||
hass,
|
||||
database,
|
||||
instance.id,
|
||||
was_on_time=result.was_on_time,
|
||||
await hass.services.call(
|
||||
DOMAIN,
|
||||
SERVICE_COMPLETE_QUEST,
|
||||
{
|
||||
"instance_id": instance.id,
|
||||
"actor": "panel",
|
||||
"actor_child_id": child.id,
|
||||
},
|
||||
)
|
||||
day_complete = hass.bus.fired(EVENT_CHILD_DAY_COMPLETE)
|
||||
assert len(day_complete) == 1, (
|
||||
|
||||
@@ -28,7 +28,6 @@ from custom_components.nestquest.const import (
|
||||
CONF_NOTIFY_TARGET,
|
||||
CONF_PANEL_IDLE_TIMEOUT,
|
||||
CONF_PANEL_TOKEN,
|
||||
CONF_SNAPSHOT_STALENESS,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
@@ -36,7 +35,6 @@ from custom_components.nestquest.const import (
|
||||
DEFAULT_END_OF_DAY_REPORT_TIME,
|
||||
DEFAULT_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_PANEL_TOKEN,
|
||||
DEFAULT_SNAPSHOT_STALENESS,
|
||||
DEFAULT_UPDATE_INTERVAL,
|
||||
DEFAULT_DAY_ROLLOVER_TIME,
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
@@ -61,7 +59,6 @@ VALID_INPUT = {
|
||||
FULL_INPUT = {
|
||||
**VALID_INPUT,
|
||||
CONF_UPDATE_INTERVAL: DEFAULT_UPDATE_INTERVAL,
|
||||
CONF_SNAPSHOT_STALENESS: DEFAULT_SNAPSHOT_STALENESS,
|
||||
CONF_NOTIFY_TARGET: "",
|
||||
CONF_MORNING_SUMMARY_TIME: DEFAULT_MORNING_SUMMARY_TIME,
|
||||
CONF_AFTERNOON_REMINDER_TIME: DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
@@ -249,7 +246,6 @@ def test_options_flow_schema_applies_stored_defaults() -> None:
|
||||
CONF_DAY_ROLLOVER_TIME: "05:45",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 120,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_SNAPSHOT_STALENESS: 450,
|
||||
CONF_NOTIFY_TARGET: "notify.mobile_app_test",
|
||||
CONF_MORNING_SUMMARY_TIME: "07:00",
|
||||
CONF_AFTERNOON_REMINDER_TIME: "14:00",
|
||||
@@ -262,7 +258,6 @@ def test_options_flow_schema_applies_stored_defaults() -> None:
|
||||
CONF_DAY_ROLLOVER_TIME: "05:45",
|
||||
CONF_PANEL_IDLE_TIMEOUT: 120,
|
||||
CONF_UPDATE_INTERVAL: 90,
|
||||
CONF_SNAPSHOT_STALENESS: 450,
|
||||
CONF_NOTIFY_TARGET: "notify.mobile_app_test",
|
||||
CONF_MORNING_SUMMARY_TIME: "07:00",
|
||||
CONF_AFTERNOON_REMINDER_TIME: "14:00",
|
||||
@@ -906,112 +901,3 @@ def test_options_flow_strings_cover_api_section(
|
||||
assert data.get(key), f"Missing field name for '{key}'"
|
||||
assert strings["options"]["errors"]["invalid_url"]
|
||||
assert translations_en["options"] == strings["options"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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 timing 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 legacy keys 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"]
|
||||
|
||||
Reference in New Issue
Block a user