Manual timezone is the single source of local-time truth (task 7e173881) (#285)
Co-authored-by: dev_agent <dev_agent@cubecraftlabs.com> Co-committed-by: dev_agent <dev_agent@cubecraftlabs.com>
This commit was merged in pull request #285.
This commit is contained in:
@@ -910,6 +910,7 @@ def coordinator_client_from_test_override():
|
||||
{
|
||||
"today_iso": datetime.date.today().isoformat(),
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": [],
|
||||
}
|
||||
)
|
||||
|
||||
@@ -41,6 +41,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from api import host_zone
|
||||
from tests.admin_jwt_harness import (
|
||||
ADMIN_KEY,
|
||||
KID,
|
||||
@@ -60,9 +61,14 @@ _dao_meta = importlib.import_module("nestquest_core.dao_meta")
|
||||
#: independent of the core constant.
|
||||
SETTINGS_META_KEY = "settings"
|
||||
|
||||
#: The API host's own zone, pinned for every test (:func:`settings_client`):
|
||||
#: the ``effective_timezone`` while no zone is stored.
|
||||
API_HOST_ZONE = "Australia/Perth"
|
||||
|
||||
#: The all-defaults effective settings a fresh database reports — the
|
||||
#: documented eleven fields, asserted literally so the payload contract is
|
||||
#: pinned here, independent of the core constants.
|
||||
#: documented eleven fields plus the read-only ``effective_timezone``,
|
||||
#: asserted literally so the payload contract is pinned here, independent
|
||||
#: of the core constants.
|
||||
DEFAULT_SETTINGS = {
|
||||
"horizon_days": 14,
|
||||
"day_rollover_time": "00:00",
|
||||
@@ -75,22 +81,34 @@ DEFAULT_SETTINGS = {
|
||||
"end_of_day_report_enabled": True,
|
||||
"celebration_enabled": True,
|
||||
"timezone": "",
|
||||
"effective_timezone": API_HOST_ZONE,
|
||||
}
|
||||
|
||||
|
||||
def _with_zone(zone: str) -> dict:
|
||||
"""The default settings with ``zone`` stored, as the API reports them."""
|
||||
return {
|
||||
**DEFAULT_SETTINGS,
|
||||
"timezone": zone,
|
||||
"effective_timezone": zone or API_HOST_ZONE,
|
||||
}
|
||||
|
||||
|
||||
def _admin_headers() -> dict[str, str]:
|
||||
"""The Authorization header of a valid nestquest-admins JWT."""
|
||||
return {"Authorization": f"Bearer {make_token()}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def settings_client(temp_db_path: str) -> SimpleNamespace:
|
||||
async def settings_client(temp_db_path: str, monkeypatch) -> SimpleNamespace:
|
||||
"""An admin-plane app client plus its live database.
|
||||
|
||||
The same runner the children tests use (stubbed JWKS, no network);
|
||||
the fixture also exposes the app's ONE database connection so tests
|
||||
can read (or corrupt) the stored settings document itself.
|
||||
can read (or corrupt) the stored settings document itself. The API
|
||||
host's zone is pinned to :data:`API_HOST_ZONE`.
|
||||
"""
|
||||
monkeypatch.setattr(host_zone, "host_timezone", lambda: API_HOST_ZONE)
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
yield SimpleNamespace(
|
||||
@@ -147,7 +165,9 @@ async def test_update_persists_and_the_next_read_reflects_it(
|
||||
SETTINGS_META_KEY
|
||||
)
|
||||
assert raw is not None
|
||||
assert json.loads(raw) == expected
|
||||
stored = dict(expected)
|
||||
del stored["effective_timezone"] # derived on read, never stored
|
||||
assert json.loads(raw) == stored
|
||||
|
||||
|
||||
async def test_partial_update_merges_onto_the_current_settings(
|
||||
@@ -254,7 +274,7 @@ async def test_manual_timezone_patch_persists_and_is_returned(
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
expected = {**DEFAULT_SETTINGS, "timezone": zone}
|
||||
expected = _with_zone(zone)
|
||||
assert patched.json() == expected
|
||||
|
||||
reread = await client.get(
|
||||
@@ -285,7 +305,7 @@ async def test_timezone_alone_sticks_on_a_fresh_database(
|
||||
reread = await client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
assert reread.json() == {**DEFAULT_SETTINGS, "timezone": zone}
|
||||
assert reread.json() == _with_zone(zone)
|
||||
|
||||
|
||||
async def test_timezone_configured_is_an_unknown_field(
|
||||
@@ -319,7 +339,7 @@ async def test_stored_legacy_timezone_configured_key_is_ignored(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {**DEFAULT_SETTINGS, "timezone": "America/Chicago"}
|
||||
assert response.json() == _with_zone("America/Chicago")
|
||||
|
||||
|
||||
# --- validation: rejected values never change the stored settings -------
|
||||
|
||||
@@ -37,7 +37,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from api import routes_admin, routes_panel
|
||||
from api import host_zone, routes_admin, routes_panel
|
||||
from api.nestquest_core import core_snapshot
|
||||
from tests.admin_jwt_harness import (
|
||||
ADMIN_KEY,
|
||||
@@ -101,6 +101,8 @@ async def snapshot_household(
|
||||
|
||||
monkeypatch.setattr(routes_admin, "_local_now", _admin_now)
|
||||
monkeypatch.setattr(routes_panel, "_local_now", lambda: pinned_now)
|
||||
# The API host runs UTC, the zone of the pinned clock.
|
||||
monkeypatch.setattr(host_zone, "host_timezone", lambda: "UTC")
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
yield SimpleNamespace(
|
||||
@@ -165,7 +167,10 @@ async def test_admin_jwt_returns_documented_snapshot(
|
||||
|
||||
Every field is asserted as an explicit literal, with ONE clock
|
||||
read for the request. With no missed view in the real snapshot,
|
||||
the admin body equals the panel body for the same household.
|
||||
the admin body equals the panel body for the same household — the
|
||||
panel body additionally carries the effective ``timezone`` its cards
|
||||
format the visible date and clock in (none stored here: the UTC
|
||||
host's own zone).
|
||||
"""
|
||||
client = snapshot_household.client
|
||||
seed = snapshot_household.seed
|
||||
@@ -241,7 +246,7 @@ async def test_admin_jwt_returns_documented_snapshot(
|
||||
"/api/v1/panel/snapshot", headers=_panel_headers()
|
||||
)
|
||||
assert panel.status_code == 200
|
||||
assert panel.json() == body
|
||||
assert panel.json() == {**body, "timezone": "UTC"}
|
||||
|
||||
|
||||
async def test_admin_keeps_missed_instance_panel_omits_it(
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""The API host's zone and the effective application timezone (task 7e173881).
|
||||
|
||||
With no zone stored the API reads its clock in the host's local time, so
|
||||
:func:`api.host_zone.effective_timezone` names that host zone — resolved
|
||||
the way the C library resolves local time — for the panel and admin app
|
||||
to format in. Every host configuration here is a temporary file tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from api import host_zone
|
||||
|
||||
|
||||
def _host(tmp_path: Path, *, link: str | None = None, name: str | None = None):
|
||||
"""A fake ``/etc``: ``localtime`` linked into a zoneinfo tree at
|
||||
``link``, and/or an ``/etc/timezone`` file holding ``name``."""
|
||||
localtime = tmp_path / "etc" / "localtime"
|
||||
timezone_file = tmp_path / "etc" / "timezone"
|
||||
localtime.parent.mkdir(parents=True)
|
||||
if link is not None:
|
||||
target = tmp_path / "usr" / "share" / "zoneinfo" / link
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_bytes(b"TZif")
|
||||
localtime.symlink_to(target)
|
||||
if name is not None:
|
||||
timezone_file.write_text(f"{name}\n", encoding="utf-8")
|
||||
return {"timezone_file": timezone_file, "localtime": localtime}
|
||||
|
||||
|
||||
def test_tz_environment_variable_wins(tmp_path: Path) -> None:
|
||||
paths = _host(tmp_path, link="Europe/Paris")
|
||||
assert host_zone.host_timezone({"TZ": "Asia/Kolkata"}, **paths) == "Asia/Kolkata"
|
||||
assert host_zone.host_timezone({"TZ": ":Asia/Kolkata"}, **paths) == "Asia/Kolkata"
|
||||
assert host_zone.host_timezone({"TZ": ""}, **paths) == "UTC"
|
||||
|
||||
|
||||
def test_localtime_link_names_the_zone(tmp_path: Path) -> None:
|
||||
paths = _host(tmp_path, link="America/Argentina/Buenos_Aires")
|
||||
assert host_zone.host_timezone({}, **paths) == "America/Argentina/Buenos_Aires"
|
||||
|
||||
|
||||
def test_etc_timezone_names_a_copied_localtime(tmp_path: Path) -> None:
|
||||
paths = _host(tmp_path, name="Pacific/Auckland")
|
||||
paths["localtime"].write_bytes(b"TZif")
|
||||
assert host_zone.host_timezone({}, **paths) == "Pacific/Auckland"
|
||||
|
||||
|
||||
def test_unconfigured_host_runs_utc(tmp_path: Path) -> None:
|
||||
assert host_zone.host_timezone({}, **_host(tmp_path)) == "UTC"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tz", ["EST+5", "Not/AZone", ":/etc/localtime"])
|
||||
def test_an_unnamed_host_zone_is_empty(tmp_path: Path, tz: str) -> None:
|
||||
assert host_zone.host_timezone({"TZ": tz}, **_host(tmp_path)) == ""
|
||||
|
||||
|
||||
def test_unnamed_copied_localtime_is_empty(tmp_path: Path) -> None:
|
||||
paths = _host(tmp_path)
|
||||
paths["localtime"].write_bytes(b"TZif")
|
||||
assert host_zone.host_timezone({}, **paths) == ""
|
||||
|
||||
|
||||
def test_effective_timezone_is_the_stored_zone_else_the_host_zone(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(host_zone, "host_timezone", lambda: "Europe/Dublin")
|
||||
assert host_zone.effective_timezone("America/Chicago") == "America/Chicago"
|
||||
assert host_zone.effective_timezone("") == "Europe/Dublin"
|
||||
@@ -32,7 +32,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from api import routes_admin, routes_panel
|
||||
from api import host_zone, routes_admin, routes_panel
|
||||
from api import scheduler as scheduler_module
|
||||
from api.database import _executor
|
||||
from api.scheduler import MissedSweepScheduler, _delay_seconds
|
||||
@@ -92,6 +92,7 @@ async def household(temp_db_path: str, monkeypatch) -> SimpleNamespace:
|
||||
seed=seed,
|
||||
clock=clock,
|
||||
database=runner.app.state.db.database,
|
||||
app=runner.app,
|
||||
)
|
||||
|
||||
|
||||
@@ -532,6 +533,146 @@ async def test_scheduler_rechecks_settings_before_sweeping(
|
||||
await database.close()
|
||||
|
||||
|
||||
# --- the admin settings route is the scheduler's writer (task 7e173881) ------
|
||||
#
|
||||
# ``PATCH /api/v1/admin/settings`` is the only settings writer: it holds
|
||||
# the scheduler's settings lock across the write and tells the scheduler,
|
||||
# so a saved zone or rollover re-plans a sleeping scheduler.
|
||||
|
||||
|
||||
async def _sleeping_scheduler(household: SimpleNamespace):
|
||||
"""Swap in a scheduler on the pinned clock; return it and its delays.
|
||||
|
||||
Waits until it sleeps on its first plan.
|
||||
"""
|
||||
await household.app.state.sweep_scheduler.stop()
|
||||
delays: list[float] = []
|
||||
slept = asyncio.Condition()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
async with slept:
|
||||
delays.append(seconds)
|
||||
slept.notify_all()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
household.database,
|
||||
clock=lambda: household.clock["now"],
|
||||
sleep=sleep_stub,
|
||||
)
|
||||
household.app.state.sweep_scheduler = scheduler
|
||||
scheduler.start()
|
||||
|
||||
async def wait_for_sleeps(count: int) -> None:
|
||||
async with slept:
|
||||
await asyncio.wait_for(
|
||||
slept.wait_for(lambda: len(delays) == count), timeout=5
|
||||
)
|
||||
|
||||
await wait_for_sleeps(1)
|
||||
return scheduler, delays, wait_for_sleeps
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("changes", "replanned_delay"),
|
||||
[
|
||||
# 13:00 UTC is 09:00 EDT: New York midnight is 15 hours away.
|
||||
({"timezone": HOUSEHOLD_ZONE}, _NEW_YORK_MIDNIGHT_DELAY),
|
||||
# Still UTC: 13:00 to a 14:30 rollover is 90 minutes.
|
||||
({"day_rollover_time": "14:30"}, 90 * 60),
|
||||
],
|
||||
ids=["timezone", "day_rollover_time"],
|
||||
)
|
||||
async def test_admin_settings_patch_replans_a_sleeping_scheduler(
|
||||
household: SimpleNamespace, changes: dict, replanned_delay: float
|
||||
) -> None:
|
||||
household.clock["now"] = _utc(13, 0)
|
||||
scheduler, delays, wait_for_sleeps = await _sleeping_scheduler(household)
|
||||
try:
|
||||
response = await household.client.patch(
|
||||
"/api/v1/admin/settings", json=changes, headers=_admin_headers()
|
||||
)
|
||||
assert response.status_code == 200
|
||||
await wait_for_sleeps(2)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert delays == [
|
||||
pytest.approx(_UTC_MIDNIGHT_DELAY),
|
||||
pytest.approx(replanned_delay),
|
||||
]
|
||||
|
||||
|
||||
async def test_admin_saved_zone_is_authoritative_across_surfaces(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""ONE instant, read by every surface in exactly the admin's zone.
|
||||
|
||||
Asia/Kolkata (UTC+05:30) matches neither the UTC host nor any other
|
||||
zone in play. 04:30:01 UTC is 10:00:01 there: the 10:00 quest is
|
||||
overdue on both snapshots (it would not be in UTC, 04:30), the
|
||||
household day is the 26th, and the scheduler sleeps the 299 s to a
|
||||
10:05 rollover (UTC would be 5h35m).
|
||||
"""
|
||||
household.clock["now"] = _utc(4, 30, 1)
|
||||
scheduler, delays, wait_for_sleeps = await _sleeping_scheduler(household)
|
||||
try:
|
||||
response = await household.client.patch(
|
||||
"/api/v1/admin/settings",
|
||||
json={"timezone": "Asia/Kolkata", "day_rollover_time": "10:05"},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
await wait_for_sleeps(2)
|
||||
for plane in ("panel", "admin"):
|
||||
today_iso, instance = await _pack_bag(household, plane)
|
||||
assert today_iso == TODAY.isoformat(), plane
|
||||
assert instance["overdue"] is True, plane
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert delays[1] == pytest.approx(299)
|
||||
|
||||
|
||||
async def test_empty_zone_publishes_the_api_host_zone_to_panel_and_admin(
|
||||
household: SimpleNamespace, monkeypatch
|
||||
) -> None:
|
||||
"""With no zone stored, the API reads the host's local time — and the
|
||||
panel snapshot and the admin settings both publish that host's own
|
||||
zone, so the cards and the admin app format in the API's zone, never
|
||||
Home Assistant's or the browser's.
|
||||
|
||||
The host runs Pacific/Auckland: 12:30 UTC on the 26th is already
|
||||
00:30 on the 27th there, so the API's household day is the 27th while
|
||||
a UTC Home Assistant or browser would still read the 26th. Once the
|
||||
admin saves a zone, both publish exactly that zone.
|
||||
"""
|
||||
host = "Pacific/Auckland"
|
||||
monkeypatch.setattr(host_zone, "host_timezone", lambda: host)
|
||||
household.clock["now"] = _utc(12, 30).astimezone(ZoneInfo(host))
|
||||
|
||||
panel = await household.client.get(
|
||||
"/api/v1/panel/snapshot", headers=_panel_headers()
|
||||
)
|
||||
assert panel.status_code == 200
|
||||
settings = await _admin_settings(household)
|
||||
assert settings["timezone"] == ""
|
||||
assert panel.json()["timezone"] == settings["effective_timezone"] == host
|
||||
# The published zone reproduces the API's own household day.
|
||||
assert panel.json()["today_iso"] == "2026-09-27"
|
||||
assert (
|
||||
_utc(12, 30).astimezone(ZoneInfo(host)).date().isoformat()
|
||||
== panel.json()["today_iso"]
|
||||
)
|
||||
|
||||
await _set_zone(household, "America/Chicago")
|
||||
panel = await household.client.get(
|
||||
"/api/v1/panel/snapshot", headers=_panel_headers()
|
||||
)
|
||||
settings = await _admin_settings(household)
|
||||
assert settings["timezone"] == "America/Chicago"
|
||||
assert panel.json()["timezone"] == settings["effective_timezone"]
|
||||
assert settings["effective_timezone"] == "America/Chicago"
|
||||
|
||||
|
||||
# --- settings writes are serialised with planning and sweeping (TZ-003) ------
|
||||
#
|
||||
# A zone write racing the loop's own settings reads must never leave a
|
||||
|
||||
@@ -60,6 +60,7 @@ def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ def _empty_snapshot() -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -93,6 +93,7 @@ class FakeMonotonic:
|
||||
FIXTURE_SNAPSHOT = {
|
||||
"today_iso": _today_iso(),
|
||||
"cycle_day": 3,
|
||||
"timezone": "",
|
||||
"children": [
|
||||
{
|
||||
"child_id": 1,
|
||||
@@ -793,8 +794,37 @@ async def test_snapshot_from_api_payload_empty_household() -> None:
|
||||
"""An empty household (no children) is a valid snapshot: empty
|
||||
children tuple, cycle day passes through."""
|
||||
snapshot = snapshot_from_api_payload(
|
||||
{"today_iso": "2026-09-23", "cycle_day": 0, "children": []}
|
||||
{
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": [],
|
||||
}
|
||||
)
|
||||
assert snapshot.children == ()
|
||||
assert snapshot.cycle_day == 0
|
||||
assert snapshot.today_iso == "2026-09-23"
|
||||
|
||||
|
||||
#: The panel snapshot exactly as an API from before the ``timezone`` field
|
||||
#: serves it: an integration upgraded ahead of its API still reads this.
|
||||
LEGACY_SNAPSHOT = {
|
||||
key: value for key, value in FIXTURE_SNAPSHOT.items() if key != "timezone"
|
||||
}
|
||||
|
||||
|
||||
async def test_coordinator_reads_a_legacy_payload_without_timezone(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""An older API omits ``timezone``: every refresh still builds the
|
||||
snapshot (the cards then fall back to Home Assistant's zone)."""
|
||||
assert "timezone" not in LEGACY_SNAPSHOT
|
||||
client = StubSnapshotClient(LEGACY_SNAPSHOT)
|
||||
_entry, coordinator = await _wire_entry(hass, make_entry, client)
|
||||
assert coordinator.last_update_success is True
|
||||
|
||||
snapshot = await coordinator._async_update_data()
|
||||
assert snapshot.timezone == ""
|
||||
assert snapshot.cycle_day == 3
|
||||
assert [child.child_name for child in snapshot.children] == ["Ada", "Bo"]
|
||||
assert snapshot_from_api_payload(LEGACY_SNAPSHOT).timezone == ""
|
||||
|
||||
@@ -332,6 +332,7 @@ async def test_build_snapshot_explicit_values(hass, make_entry, tmp_path) -> Non
|
||||
return {
|
||||
"today_iso": built.today_iso,
|
||||
"cycle_day": built.cycle_day,
|
||||
"timezone": built.timezone,
|
||||
"children": [
|
||||
{
|
||||
"child_id": child.child_id,
|
||||
|
||||
@@ -67,6 +67,7 @@ def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ def _payload(children, cycle_day=0) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": cycle_day,
|
||||
"timezone": "",
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
|
||||
+106
-32
@@ -567,6 +567,8 @@ def _render_party_board(
|
||||
states: dict,
|
||||
url: str | None = None,
|
||||
click_plate: str | None = None,
|
||||
now: str | None = None,
|
||||
tz: str | None = None,
|
||||
) -> dict:
|
||||
"""Render the built bundle's party board and return its plates.
|
||||
|
||||
@@ -575,7 +577,9 @@ def _render_party_board(
|
||||
mounts the card with the given config and hass snapshot, optionally
|
||||
taps the named plate, and prints the ordered plates its shadow DOM
|
||||
renders, which of them are tappable buttons, and the pathname after
|
||||
the optional tap.
|
||||
the optional tap. ``now`` pins the card's clock to an ISO instant
|
||||
and ``tz`` sets the node process's ``TZ`` — the panel browser's
|
||||
local zone.
|
||||
"""
|
||||
assert BUNDLE_PATH.is_file(), "bundle missing: run cd frontend && npm run build"
|
||||
assert RENDER_HARNESS.is_file()
|
||||
@@ -589,12 +593,15 @@ def _render_party_board(
|
||||
spec["url"] = url
|
||||
if click_plate is not None:
|
||||
spec["click_plate"] = click_plate
|
||||
if now is not None:
|
||||
spec["now"] = now
|
||||
completed = subprocess.run(
|
||||
["node", str(RENDER_HARNESS)],
|
||||
input=json.dumps(spec),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
env={**os.environ, "TZ": tz} if tz is not None else None,
|
||||
)
|
||||
assert completed.returncode == 0, (
|
||||
f"render harness failed: {completed.stderr}"
|
||||
@@ -1102,13 +1109,12 @@ def test_quest_log_meta_line_keeps_its_meta_class() -> None:
|
||||
``meta ${late ? "late" : nothing}``, Lit dropped the whole class
|
||||
attribute for every quest that was not late, leaving the due line
|
||||
unstyled. The rendered markup must carry ``class="meta"`` on time and
|
||||
``class="meta late"`` overdue — overdue by the panel's pinned clock
|
||||
(07:15 local: the 07:00 quest is late, the 08:15 one is not)."""
|
||||
``class="meta late"`` overdue — overdue as the API snapshot says."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
|
||||
def quest(instance_id: int, title: str, due_time: str) -> dict:
|
||||
def quest(instance_id: int, title: str, overdue: bool) -> dict:
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": instance_id,
|
||||
@@ -1116,9 +1122,9 @@ def test_quest_log_meta_line_keeps_its_meta_class() -> None:
|
||||
"title": title,
|
||||
"icon": None,
|
||||
"window": "morning",
|
||||
"due_time": due_time,
|
||||
"due_time": "08:15",
|
||||
"state": "open",
|
||||
"overdue": False,
|
||||
"overdue": overdue,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
@@ -1131,8 +1137,8 @@ def test_quest_log_meta_line_keeps_its_meta_class() -> None:
|
||||
child_id=1,
|
||||
present=True,
|
||||
instances=[
|
||||
quest(41, "Make Bed", "08:15"),
|
||||
quest(42, "Brush Teeth", "07:00"),
|
||||
quest(41, "Make Bed", overdue=False),
|
||||
quest(42, "Brush Teeth", overdue=True),
|
||||
],
|
||||
),
|
||||
}
|
||||
@@ -1140,8 +1146,6 @@ def test_quest_log_meta_line_keeps_its_meta_class() -> None:
|
||||
generated["views"][1]["cards"][0],
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
now="2026-09-29T11:15:00Z",
|
||||
tz="America/New_York",
|
||||
)
|
||||
metas = {}
|
||||
for card in result["html"].split('data-instance-id="')[1:]:
|
||||
@@ -1175,19 +1179,22 @@ def _quest_metas(html: str) -> dict[str, tuple[str, str]]:
|
||||
return metas
|
||||
|
||||
|
||||
def test_quest_log_overdue_follows_the_panel_local_clock() -> None:
|
||||
"""Overdue is decided by the panel's own local clock, not the API's
|
||||
``overdue`` flag. The owner saw 8:15 AM quests read OVERDUE at 7:15 AM
|
||||
America/New_York: the API's flag had been computed on a UTC wall clock
|
||||
(11:15). Here the API still says ``overdue: true`` and Home
|
||||
Assistant reports ``time_zone`` UTC, yet at 07:15 local the 08:15 quest
|
||||
is due, at 08:15 (and 08:16, via the card's own clock tick) it is
|
||||
overdue, and a quest with no due time is never overdue."""
|
||||
def test_quest_log_overdue_follows_the_api_snapshot_not_the_panel_clock() -> None:
|
||||
"""The stored application timezone is the single source of local-time
|
||||
truth: the API computes each instance's ``overdue`` in that zone and
|
||||
the card renders exactly that, whatever the panel browser's own clock
|
||||
or zone says. Here the browser runs in Pacific/Auckland and its clock
|
||||
is pinned (and later ticked) to instants where every due time has, or
|
||||
has not yet, arrived on its local wall clock — the card must still
|
||||
show the snapshot's state: the ``overdue: true`` 08:15 quest reads
|
||||
OVERDUE even though the browser reads long before 08:15, and the
|
||||
``overdue: false`` 07:00 quest stays due even though the browser reads
|
||||
long after 07:00."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
|
||||
def quest(instance_id: int, title: str, due_time: str | None) -> dict:
|
||||
def quest(instance_id: int, title: str, due_time: str, overdue: bool) -> dict:
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": instance_id,
|
||||
@@ -1197,7 +1204,7 @@ def test_quest_log_overdue_follows_the_panel_local_clock() -> None:
|
||||
"window": "morning",
|
||||
"due_time": due_time,
|
||||
"state": "open",
|
||||
"overdue": True,
|
||||
"overdue": overdue,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
@@ -1210,29 +1217,96 @@ def test_quest_log_overdue_follows_the_panel_local_clock() -> None:
|
||||
child_id=1,
|
||||
present=True,
|
||||
instances=[
|
||||
quest(42, "Brush Teeth", "08:15"),
|
||||
quest(43, "Feed Fish", None),
|
||||
quest(42, "Brush Teeth", "08:15", overdue=True),
|
||||
quest(43, "Feed Fish", "07:00", overdue=False),
|
||||
],
|
||||
),
|
||||
}
|
||||
# 2026-09-29T17:00Z is 06:00 NZDT on the 30th: before both due times.
|
||||
# 2026-09-29T23:00Z is 12:00 NZDT: after both.
|
||||
result = _render_quest_log(
|
||||
generated["views"][1]["cards"][0],
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
now="2026-09-29T11:15:00Z",
|
||||
advance_to=["2026-09-29T12:15:00Z", "2026-09-29T12:16:00Z"],
|
||||
tz="America/New_York",
|
||||
now="2026-09-29T17:00:00Z",
|
||||
advance_to=["2026-09-29T23:00:00Z"],
|
||||
tz="Pacific/Auckland",
|
||||
)
|
||||
due_by = ('class="meta"', "Due by 8:15 AM")
|
||||
overdue = ('class="meta late"', "Overdue · due 8:15 AM")
|
||||
not_due = ('class="meta"', "Due today")
|
||||
at_0715, at_0815, at_0816 = (
|
||||
due_by = ('class="meta"', "Due by 7:00 AM")
|
||||
before, (after,) = (
|
||||
_quest_metas(result["html"]),
|
||||
*(_quest_metas(tick["html"]) for tick in result["ticks"]),
|
||||
[_quest_metas(tick["html"]) for tick in result["ticks"]],
|
||||
)
|
||||
assert before == {"42": overdue, "43": due_by}, before
|
||||
assert after == {"42": overdue, "43": due_by}, after
|
||||
|
||||
|
||||
def test_panel_date_and_clock_follow_the_stored_application_timezone() -> None:
|
||||
"""The stored application timezone is the single source of local-time
|
||||
truth for the panel's visible date and clock too: the household rollup
|
||||
publishes it (``timezone`` — the API's effective zone) and both cards
|
||||
format in it — the party
|
||||
board's kicker and dock date and clock, the quest log's header date —
|
||||
even though Home Assistant's zone and the panel browser's zone are both
|
||||
UTC. At 2026-09-29T23:30Z it is still Tuesday 11:30 PM in UTC but
|
||||
already Wednesday 12:30 PM in Pacific/Auckland (NZDT)."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
states = _three_child_states()
|
||||
states["sensor.nestquest_household_quests_due_today"]["attributes"][
|
||||
"timezone"
|
||||
] = "Pacific/Auckland"
|
||||
now = "2026-09-29T23:30:00Z"
|
||||
|
||||
def text(html: str) -> str:
|
||||
return re.sub(r"<!--.*?-->", "", html).replace("\u202f", " ")
|
||||
|
||||
def board_date_and_clock(html: str) -> tuple[str, str, str]:
|
||||
found = re.search(
|
||||
r'<p class="kicker">The Party · (.*?)</p>.*?'
|
||||
r'<span class="date">(.*?)</span>.*?<span class="clock">(.*?)</span>',
|
||||
text(html),
|
||||
re.DOTALL,
|
||||
)
|
||||
assert found is not None, html
|
||||
return found.group(1), found.group(2), found.group(3)
|
||||
|
||||
board = _render_party_board(
|
||||
generated["views"][0]["cards"][0], states, now=now, tz="UTC"
|
||||
)["html"]
|
||||
assert board_date_and_clock(board) == (
|
||||
"Wednesday, Sep 30",
|
||||
"Wednesday, Sep 30",
|
||||
"12:30 PM",
|
||||
)
|
||||
|
||||
log = _render_quest_log(
|
||||
generated["views"][1]["cards"][0],
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
now=now,
|
||||
tz="UTC",
|
||||
)["html"]
|
||||
sub = re.search(r'<p class="sub">\s*(.*?) ·', text(log), re.DOTALL)
|
||||
assert sub is not None, log
|
||||
assert sub.group(1) == "Wednesday, Sep 30"
|
||||
|
||||
# With no zone stored the API publishes its host's own zone, so the
|
||||
# rollup always carries one; only a rollup without it (an API older
|
||||
# than the field) falls back to Home Assistant's zone (UTC here).
|
||||
del states["sensor.nestquest_household_quests_due_today"]["attributes"][
|
||||
"timezone"
|
||||
]
|
||||
fallback = _render_party_board(
|
||||
generated["views"][0]["cards"][0], states, now=now, tz="UTC"
|
||||
)["html"]
|
||||
assert board_date_and_clock(fallback) == (
|
||||
"Tuesday, Sep 29",
|
||||
"Tuesday, Sep 29",
|
||||
"11:30 PM",
|
||||
)
|
||||
assert at_0715 == {"42": due_by, "43": not_due}, at_0715
|
||||
assert at_0815 == {"42": overdue, "43": not_due}, at_0815
|
||||
assert at_0816 == {"42": overdue, "43": not_due}, at_0816
|
||||
|
||||
|
||||
def test_quest_log_crest_matches_the_spec_geometry() -> None:
|
||||
|
||||
@@ -76,6 +76,7 @@ def _payload(children) -> dict:
|
||||
return {
|
||||
"today_iso": _today_iso(),
|
||||
"cycle_day": 0,
|
||||
"timezone": "",
|
||||
"children": list(children),
|
||||
}
|
||||
|
||||
@@ -569,6 +570,22 @@ async def test_household_due_sensor_publishes_the_ordered_child_roster(
|
||||
}
|
||||
|
||||
|
||||
async def test_household_due_sensor_publishes_the_stored_zone(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
"""The rollup carries the snapshot's stored application zone verbatim
|
||||
(the panel cards format their date and clock in it); ``""`` — no zone
|
||||
stored — passes through unchanged for the cards' documented fallback."""
|
||||
zoned = {**_seeded_payload(), "timezone": "Pacific/Auckland"}
|
||||
entry, coordinator, _client = await _setup_entry(
|
||||
hass, make_entry, zoned, _seeded_payload()
|
||||
)
|
||||
rollup = hass.entities["nestquest_household_quests_due_today"]
|
||||
assert rollup.extra_state_attributes["timezone"] == "Pacific/Auckland"
|
||||
await coordinator.async_refresh()
|
||||
assert rollup.extra_state_attributes["timezone"] == ""
|
||||
|
||||
|
||||
async def test_household_roster_tracks_the_snapshot_on_refresh(
|
||||
hass, make_entry
|
||||
) -> None:
|
||||
|
||||
@@ -151,7 +151,12 @@ DOCUMENTED_FIELDS = {
|
||||
|
||||
#: 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": []}
|
||||
MINIMAL_SNAPSHOT = {
|
||||
"today_iso": "2026-09-23",
|
||||
"cycle_day": 1,
|
||||
"timezone": "",
|
||||
"children": [],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user