Feature 20: Zero-Config Panel Dashboard (#180)

Co-authored-by: dev_agent <17+dev_agent@code.cubecraftcreations.com>
Co-committed-by: dev_agent <17+dev_agent@code.cubecraftcreations.com>
This commit was merged in pull request #180.
This commit is contained in:
2026-09-23 12:27:35 -04:00
committed by approver_agent
parent 6059a67122
commit ee8ef6dcac
21 changed files with 2801 additions and 223 deletions
+68
View File
@@ -24,16 +24,20 @@ from __future__ import annotations
import asyncio
import importlib.util
import inspect
import re
import sys
import tempfile
import unicodedata
import weakref
from dataclasses import dataclass
from html.entities import name2codepoint
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
from unidecode import unidecode as _unidecode
from tests.admin_jwt_harness import ADMIN_KEY, KID, AdminRunner, jwks_for
@@ -46,6 +50,7 @@ _HA_MODULES = (
"homeassistant.config_entries",
"homeassistant.data_entry_flow",
"homeassistant.exceptions",
"homeassistant.util",
"homeassistant.helpers",
"homeassistant.helpers.config_validation",
"homeassistant.helpers.entity",
@@ -94,6 +99,7 @@ for _parent, _child in (
("homeassistant", "data_entry_flow"),
("homeassistant", "core"),
("homeassistant", "exceptions"),
("homeassistant", "util"),
("homeassistant", "helpers"),
("homeassistant.helpers", "config_validation"),
("homeassistant.helpers", "entity"),
@@ -218,6 +224,68 @@ _exceptions_mock.ConfigEntryNotReady = ConfigEntryNotReady
_exceptions_mock.Unauthorized = Unauthorized
# ---------------------------------------------------------------------------
# homeassistant.util.slugify: a faithful stand-in for the real slugifier.
#
# Real HA (2024.6) wraps python-slugify's frozen legacy pipeline and answers
# its "unknown" sentinel when a non-empty name slugs to nothing. The stub
# mirrors that pipeline step for step — quotes to dashes, NFKD-normalize,
# TRANSLITERATE through unidecode (the backend python-slugify's "auto" mode
# prefers, and a dev dependency here), decode HTML entities, NFKD again,
# lowercase, drop quotes, fold runs of non-[a-z0-9-] to one dash, collapse
# and strip dashes, then map dashes to the requested separator — and was
# verified byte-for-byte against real python-slugify across Latin, Cyrillic,
# CJK and Greek household-name shapes. Transliteration is the point: HA
# derives the per-child entity ids from a name like "京子" as
# "nestquest_jing_zi_…", so the roster's slugs must transliterate too,
# never dropping characters into "unknown". Deliberately NOT truncating:
# real slugify caps nothing; the entity registry truncates the full
# entity_id instead.
# ---------------------------------------------------------------------------
_HA_QUOTE_PATTERN = re.compile(r"[']+")
_HA_CHAR_ENTITY_PATTERN = re.compile(r"&(%s);" % "|".join(name2codepoint))
_HA_DECIMAL_PATTERN = re.compile(r"&#(\d+);")
_HA_HEX_PATTERN = re.compile(r"&#x([\da-fA-F]+);")
_HA_NUMBERS_PATTERN = re.compile(r"(?<=\d),(?=\d)")
_HA_DISALLOWED_CHARS_PATTERN = re.compile(r"[^-a-zA-Z0-9]+")
_HA_DUPLICATE_DASH_PATTERN = re.compile(r"-{2,}")
def _ha_slugify(text: str | None, *, separator: str = "_") -> str:
"""Faithful homeassistant.util.slugify stand-in (see section above)."""
if text == "" or text is None:
return ""
text = str(text)
text = _HA_QUOTE_PATTERN.sub("-", text)
text = unicodedata.normalize("NFKD", text)
text = _unidecode(text)
text = _HA_CHAR_ENTITY_PATTERN.sub(
lambda match: chr(name2codepoint[match.group(1)]), text
)
try:
text = _HA_DECIMAL_PATTERN.sub(
lambda match: chr(int(match.group(1))), text
)
except (ValueError, OverflowError):
pass
try:
text = _HA_HEX_PATTERN.sub(
lambda match: chr(int(match.group(1), 16)), text
)
except (ValueError, OverflowError):
pass
text = unicodedata.normalize("NFKD", text)
text = text.lower()
text = _HA_QUOTE_PATTERN.sub("", text)
text = _HA_NUMBERS_PATTERN.sub("", text)
text = _HA_DISALLOWED_CHARS_PATTERN.sub("-", text)
text = _HA_DUPLICATE_DASH_PATTERN.sub("-", text).strip("-")
return "unknown" if text == "" else text.replace("-", separator)
_ha_mock("homeassistant.util").slugify = _ha_slugify
@dataclass
class DeviceInfo:
"""Stand-in for homeassistant.helpers.entity.DeviceInfo.
+246
View File
@@ -12,12 +12,100 @@ from custom_components.nestquest.const import (
DOMAIN as DOMAIN_CONST,
SERVICE_COMPLETE_QUEST,
)
from custom_components.nestquest.dashboard import (
DASHBOARD_STRATEGY_TYPE,
DASHBOARD_URL_PATH,
async_register_dashboard,
)
def _wire(entry, registry):
return wire_entry_to_registry(entry, registry)
class FakeDashboardStore:
"""Stand-in for a per-dashboard CONTENT manager (LovelaceStorage).
In the real API the dashboard CONFIG (the strategy reference) is
saved through THIS manager's ``async_save``, NOT through the
metadata collection — so every strategy-save assertion reads here.
"""
def __init__(self) -> None:
self.saved: list[dict] = []
self.config: dict | None = None
async def async_save(self, config: dict) -> None:
self.saved.append(dict(config))
self.config = dict(config)
class FakeDashboardsCollection:
"""Stand-in mirroring the REAL Lovelace dashboards API shapes.
Faithful to ``homeassistant/components/lovelace`` +
``helpers/collection.py``: ``async_items()`` is a SYNC ``@callback``
(ObservableCollection.async_items returns list(data.values())),
``async_create_item`` IS async, and — mirroring lovelace's
``storage_dashboard_changed`` listener — a successful create
registers a fresh CONTENT manager under
``hass.data["lovelace"]["dashboards"][url_path]``, which is where
the dashboard config is then saved. Records ``async_create_item``
calls so tests can assert exactly what the setup path registered —
and that a reload registers nothing more.
"""
def __init__(self, hass, items=None) -> None:
self.hass = hass
self.items = list(items or [])
self.created: list[dict] = []
#: url_path -> content manager, mirroring the real listener's
# registrations (pre-existing items included).
self.stores: dict[str, FakeDashboardStore] = {}
def async_items(self):
"""SYNC, like the real ``ObservableCollection.async_items``."""
return list(self.items)
async def async_create_item(self, item_config: dict) -> None:
# The real collection awaits validation and change notification
# around the item insertion; yield first so two concurrent
# callers without a single-flight guard would BOTH get here.
await asyncio.sleep(0)
self.created.append(dict(item_config))
self.items.append(dict(item_config))
self.stores[item_config["url_path"]] = FakeDashboardStore()
self.hass.data["lovelace"]["dashboards"][item_config["url_path"]] = (
self.stores[item_config["url_path"]]
)
def _install_dashboard_collection(
hass, items=None
) -> FakeDashboardsCollection:
"""Install the REAL-API-shaped lovelace surfaces on the hass stub.
Mirrors what lovelace's ``async_setup`` leaves behind in storage
mode: ``hass.data["lovelace"]`` is a DICT with the metadata
collection under ``dashboards_collection`` and the per-url_path
CONTENT managers under ``dashboards``. Any pre-existing item gets
a content manager, exactly as lovelace's change listener would
have registered one when the dashboard was created.
"""
collection = FakeDashboardsCollection(hass, items)
hass.data["lovelace"] = {
"mode": "storage",
"dashboards": {},
"dashboards_collection": collection,
}
for item in collection.items:
url_path = item.get("url_path")
store = FakeDashboardStore()
collection.stores[url_path] = store
hass.data["lovelace"]["dashboards"][url_path] = store
return collection
async def test_setup_stores_runtime_data_in_hass_data(hass, make_entry) -> None:
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
@@ -271,3 +359,161 @@ async def test_unload_shuts_coordinator_even_when_listener_removal_raises() -> N
assert entry.runtime_data is None
assert DOMAIN_CONST not in hass.data
assert hass.time_change.size == 0
async def test_setup_creates_the_panel_dashboard(hass, make_entry) -> None:
"""A fresh install gets the storage-mode strategy dashboard via the
REAL two-step Lovelace sequence: the METADATA (url_path, title,
icon, sidebar, single-word allowance — nothing else: the real
create schema rejects unknown keys like ``strategy``) through the
collection, then the dashboard CONFIG (the strategy reference)
through the fresh dashboard's content manager."""
collection = _install_dashboard_collection(hass)
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
# Step 1: the metadata create through the collection.
assert len(collection.created) == 1
created = collection.created[0]
assert created["url_path"] == DASHBOARD_URL_PATH
assert created["title"]
assert created["show_in_sidebar"] is True
assert created["allow_single_word"] is True
assert "icon" in created
# The create payload carries METADATA only: a ``strategy`` key is
# rejected by the real collection's create schema (the silent
# no-op the first implementation shipped).
assert "strategy" not in created
assert "mode" not in created
# Step 2: the strategy CONFIG saved through the content manager
# the create registered, with the custom strategy type.
store = hass.data["lovelace"]["dashboards"][DASHBOARD_URL_PATH]
assert store is collection.stores[DASHBOARD_URL_PATH]
assert store.saved == [{"strategy": {"type": DASHBOARD_STRATEGY_TYPE}}]
assert store.config == {"strategy": {"type": DASHBOARD_STRATEGY_TYPE}}
async def test_setup_reload_does_not_duplicate_the_dashboard(
hass, make_entry
) -> None:
"""A reload (or a second entry) must not create a second dashboard:
the one under the stable url_path is reused as-is — BOTH steps are
skipped, so the strategy config is not re-saved either."""
collection = _install_dashboard_collection(hass)
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
assert len(collection.created) == 1
store = hass.data["lovelace"]["dashboards"][DASHBOARD_URL_PATH]
assert len(store.saved) == 1
# A reload: setup again on the same hass (the reload cycle) —
# the existing dashboard must be left alone.
await async_unload_entry(hass, entry)
assert await async_setup_entry(hass, entry) is True
assert len(collection.created) == 1
assert len(store.saved) == 1
# And a second entry on the same install.
other = _wire(make_entry(entry_id="other"), hass.registry)
assert await async_setup_entry(hass, other) is True
assert len(collection.created) == 1
assert len(store.saved) == 1
async def test_setup_leaves_an_existing_user_dashboard_alone(
hass, make_entry
) -> None:
"""A dashboard already occupying the stable url_path — the user's
own — is never overwritten, deleted or duplicated: no metadata
create AND no strategy save against its content manager."""
users_dashboard = {"url_path": DASHBOARD_URL_PATH, "title": "My Board"}
collection = _install_dashboard_collection(hass, items=[users_dashboard])
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
assert collection.created == []
assert collection.items[0] is users_dashboard
users_store = hass.data["lovelace"]["dashboards"][DASHBOARD_URL_PATH]
assert users_store.saved == []
assert users_store.config is None
async def test_setup_succeeds_without_the_dashboards_collection(
hass, make_entry, caplog
) -> None:
"""YAML mode / lovelace not loaded: log a warning, continue setup."""
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
assert entry.entry_id in hass.data[DOMAIN]
assert any(
"dashboard" in record.message.lower()
and record.levelname == "WARNING"
for record in caplog.records
)
async def test_setup_survives_a_failing_dashboards_collection(
hass, make_entry
) -> None:
"""A collection that refuses the create (permissions, admin-only)
logs a warning and setup still succeeds — entities come up."""
class _RefusingCollection(FakeDashboardsCollection):
async def async_create_item(self, item_config):
raise PermissionError("not an admin")
collection = _RefusingCollection(hass)
hass.data["lovelace"] = {
"mode": "storage",
"dashboards": {},
"dashboards_collection": collection,
}
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
assert collection.created == []
async def test_setup_survives_a_failing_content_manager_save(
hass, make_entry
) -> None:
"""A content manager that refuses the config save after the
metadata create succeeded (storage write failure) logs a warning
and setup still succeeds — the dashboard exists, the strategy
simply was not persisted through it."""
class _RefusingStore(FakeDashboardStore):
async def async_save(self, config):
raise OSError("disk full")
class _StorelessCreateCollection(FakeDashboardsCollection):
async def async_create_item(self, item_config):
await asyncio.sleep(0)
self.created.append(dict(item_config))
self.items.append(dict(item_config))
self.stores[item_config["url_path"]] = _RefusingStore()
self.hass.data["lovelace"]["dashboards"][
item_config["url_path"]
] = self.stores[item_config["url_path"]]
collection = _StorelessCreateCollection(hass)
hass.data["lovelace"] = {
"mode": "storage",
"dashboards": {},
"dashboards_collection": collection,
}
entry = _wire(make_entry(), hass.registry)
assert await async_setup_entry(hass, entry) is True
assert len(collection.created) == 1
store = hass.data["lovelace"]["dashboards"][DASHBOARD_URL_PATH]
assert store.saved == []
async def test_concurrent_registrations_create_the_dashboard_once(hass) -> None:
"""Two CONCURRENT registrations (the race two entry setups run)
must produce exactly ONE dashboard: the single-flight guard makes
the second caller's exists-check run after the first caller's
create completed, so it skips both steps. The fake's create
yields before recording, so without the guard both callers would
pass the exists-check and the dashboard would be created twice."""
collection = _install_dashboard_collection(hass)
results = await asyncio.gather(
async_register_dashboard(hass),
async_register_dashboard(hass),
)
assert results == [True, True]
assert len(collection.created) == 1
assert len(collection.stores[DASHBOARD_URL_PATH].saved) == 1
+730 -2
View File
@@ -5,16 +5,36 @@ the contract by reading the card sources and the built bundle, in the same
spirit as test_frontend.py. They cover the states decided in
design/PANEL-EMPTY-STATES.md and PANEL-SPEC.md, and guard the kid-facing
bundles against ever gaining a parent-only service call.
The cards additionally have render tests: they drive the jsdom harnesses in
frontend/tests — render-party-board.mjs imports the built bundle into a
jsdom window and reports the ordered plates the shadow DOM renders plus
where a crest tap navigates, and render-quest-log.mjs reports where the
quest log's idle return navigates — so the zero-config discovery and
navigation contracts are asserted against the bundle HACS ships.
The motion contract (PANEL-SPEC §3.3/§3.5/§4/§5 entrances and timings) and
the §1/§6 hard rules are asserted on the card sources in the motion
section below, and the quest-complete screen's countdown return is driven
end-to-end through the quest-log harness.
"""
from __future__ import annotations
import json
import re
import subprocess
from pathlib import Path
REPO_ROOT = Path(__file__).parent.parent
FRONTEND_CARDS_DIR = REPO_ROOT / "frontend" / "src" / "cards"
FRONTEND_DIR = REPO_ROOT / "frontend"
FRONTEND_CARDS_DIR = FRONTEND_DIR / "src" / "cards"
PARTY_BOARD = FRONTEND_CARDS_DIR / "party-board.ts"
QUEST_LOG = FRONTEND_CARDS_DIR / "quest-log.ts"
BUNDLE_PATH = REPO_ROOT / "custom_components" / "nestquest" / "www" / "nestquest-cards.js"
RENDER_HARNESS = FRONTEND_DIR / "tests" / "render-party-board.mjs"
QUEST_LOG_HARNESS = FRONTEND_DIR / "tests" / "render-quest-log.mjs"
STRATEGY_HARNESS = FRONTEND_DIR / "tests" / "render-strategy.mjs"
STRATEGY_SOURCE = FRONTEND_DIR / "src" / "strategy.ts"
PANEL_SOURCES = (PARTY_BOARD, QUEST_LOG)
@@ -38,11 +58,106 @@ ADMIN_ONLY_SERVICES = (
WINDOW_KEYS = ("morning", "afternoon", "evening")
WINDOW_NAMES = ("Morning", "Afternoon", "Evening")
# The approved token pair: the bundle must serve the design copy
# verbatim. The values below are what PANEL-SPEC times the panel with
# (§3.3 seal entrance, §4 dialog entrance, §3.2 press feedback) and the
# ink set §1 pins at >=4.5:1 on parchment.
DESIGN_TOKENS = REPO_ROOT / "design" / "tokens" / "nestquest-panel-tokens.css"
REWARD_TOKENS = (
REPO_ROOT
/ "custom_components"
/ "nestquest"
/ "www"
/ "nestquest-panel-tokens.css"
)
MOTION_TOKENS = {
"--nq-ease-out": "cubic-bezier(0, 0, .2, 1)",
"--nq-dur-micro": "120ms",
"--nq-dur-base": "200ms",
"--nq-dur-modal": "350ms",
}
PANEL_INK_TOKENS = {
"--nq-p-ink": "#2b1f14",
"--nq-p-ink-secondary": "#5c452a",
"--nq-p-ink-muted": "#6f6455",
"--nq-p-ink-away": "#4d4433",
"--nq-p-ink-late": "#8f1526",
"--nq-p-dock-ink": "#f7efdb",
"--nq-p-dock-ink-secondary": "#d8c9a6",
}
# Text colors the panel styles may use beyond the token inks: the
# spec's own literals (§2.1 pill, §3.3 seal check, §4 dialog body),
# glyphs on the brand gradient, gradient text fills (§2 wordmark, §5
# title), and the plate button inheriting its plate's ink.
APPROVED_NON_TOKEN_INKS = {
"inherit",
"transparent",
"#ffffff",
"rgba(255, 235, 235, 0.95)",
"#3f2f1c",
"#146b36",
"#157a3c",
}
#: Each card's styles live in one css template literal, keyed by the
#: constant that holds it.
STYLE_CONSTANTS = {
PARTY_BOARD: "boardStyles",
QUEST_LOG: "logStyles",
}
def _read(path: Path) -> str:
return path.read_text(encoding="utf-8")
def _style_literal(source: str, constant: str) -> str:
"""A card's css template literal — the styles between the backticks."""
marker = f"const {constant} = css`"
start = source.index(marker) + len(marker)
return source[start : source.index("`;", start)]
def _keyframes_block(style: str, name: str) -> str:
"""A @keyframes rule's text, from its name through its to-block."""
start = style.index(f"@keyframes {name}")
return style[start : style.index("}", style.index("to {", start))]
def _css_rules(style: str) -> list[tuple[str, str]]:
"""(selector, declarations) pairs for every rule in a card's styles.
Lit interpolations are blanked first so the clip-path/unsafeCSS
braces cannot confuse the parse; @keyframes' from/to count as rules
but carry no font-size, so the size checks skip them.
"""
flattened = re.sub(r"\$\{[^}]*\}", " ", style)
return re.findall(r"([^{}]+)\{([^{}]*)\}", flattened)
def _size_tokens(tokens: str) -> dict[str, int]:
"""Every px length token declared in the panel tokens."""
return {
name: int(px)
for name, px in re.findall(r"(--[a-z0-9-]+):\s*(\d+)px", tokens)
}
def _font_size_px(declaration: str, sizes: dict[str, int]) -> int | None:
"""A font-size value's pixel amount; None when it is neither a px
length nor one of the panel size tokens."""
declaration = declaration.strip()
if declaration.endswith("px"):
return round(float(declaration[:-2]))
match = re.fullmatch(r"var\((--[a-z0-9-]+)\)", declaration)
if match and match.group(1) in sizes:
return sizes[match.group(1)]
return None
def test_party_board_renders_present_and_away_plates() -> None:
source = _read(PARTY_BOARD)
assert "nestquest-party-board-card" in source
@@ -146,6 +261,198 @@ def test_quest_complete_trigger() -> None:
assert "complete_screen_seconds" in source
# --- Panel motion and hard rules (PANEL-SPEC §1, §3.3, §3.5, §4–§6) -----------
def test_panel_serves_the_exact_design_token_copy() -> None:
"""The bundle's served tokens are byte-for-byte the approved design
copy. The motion tokens time every panel entrance and the ink set is
the documented >=4.5:1 set — the cards only reference the tokens, so
a drifted value fails here before it can reach the panel."""
assert _read(REWARD_TOKENS) == _read(DESIGN_TOKENS)
tokens = _read(REWARD_TOKENS)
for declared in (MOTION_TOKENS, PANEL_INK_TOKENS):
for name, value in declared.items():
pattern = rf"^\s*{re.escape(name)}:\s*{re.escape(value)};"
assert re.search(pattern, tokens, re.MULTILINE), name
# The 22px meta floor is the declared panel minimum (§1).
assert re.search(
r"^\s*--nq-p-size-body:\s*22px;.*PANEL MINIMUM", tokens, re.MULTILINE
)
def test_quest_log_entrances_use_the_design_timing_and_easing() -> None:
"""PANEL-SPEC §3.3/§4: the seal enters with fade + scale(1.15 → 1)
over --nq-dur-base and the confirm dialog with fade + scale(.96 → 1)
over --nq-dur-modal, both --nq-ease-out; press feedback is scale(.98)
over --nq-dur-micro."""
style = _style_literal(_read(QUEST_LOG), STYLE_CONSTANTS[QUEST_LOG])
assert "animation: dialog-in var(--nq-dur-modal) var(--nq-ease-out);" in style
dialog = _keyframes_block(style, "dialog-in")
assert "opacity: 0;" in dialog and "transform: scale(0.96);" in dialog
assert "opacity: 1;" in dialog and "transform: scale(1);" in dialog
assert "animation: seal-in var(--nq-dur-base) var(--nq-ease-out);" in style
seal = _keyframes_block(style, "seal-in")
assert "opacity: 0;" in seal
# The per-card rotation is preserved through the stamp animation.
assert "transform: scale(1.15) rotate(var(--seal-rot, 0deg));" in seal
assert "transform: scale(1) rotate(var(--seal-rot, 0deg));" in seal
assert "animation: toast-in var(--nq-dur-base) var(--nq-ease-out);" in style
for selector in (
".quest.tappable:active",
"button.complete:active",
"button.confirm-button:active",
):
start = style.index(selector)
block = style[start : style.index("}", start)]
assert "transform: scale(0.98);" in block, selector
assert (
style.count("transition: transform var(--nq-dur-micro) var(--nq-ease-out);")
== 3
) # quest card, Complete button, confirm buttons
board_style = _style_literal(_read(PARTY_BOARD), STYLE_CONSTANTS[PARTY_BOARD])
start = board_style.index("button.plate:active")
block = board_style[start : board_style.index("}", start)]
assert "transform: scale(0.98);" in block
assert (
"transition: transform var(--nq-dur-micro) var(--nq-ease-out);" in board_style
)
def test_quest_complete_screen_times_the_12_second_return() -> None:
"""PANEL-SPEC §5: the 1c screen auto-returns to the board 12 s after
the day completes, driven by the per-second countdown line."""
source = _read(QUEST_LOG)
assert "asNumber(this._config?.complete_screen_seconds, 12)" in source
assert "this._countdown = this._completeSeconds();" in source
assert "}, 1000);" in source
assert "Returning to The Party in ${remaining} seconds" in source
# Zero reaches the idle-return navigation itself.
assert "this._returnToBoard();" in source
def test_idle_return_uses_the_40_second_design_timing() -> None:
"""PANEL-SPEC §3.5: 40 s with no touch returns to the party board;
any pointer or touch event re-arms the timer. The config knob only
shortens the default (tests do; the strategy never sets it)."""
source = _read(QUEST_LOG)
assert "asNumber(this._config?.idle_return_seconds, 40)" in source
for event in ("pointerdown", "touchstart"):
assert (
f'window.addEventListener("{event}", this._onActivity, true)' in source
), event
def test_panel_hard_rules_hold_in_the_card_sources() -> None:
"""PANEL-SPEC §1/§6 hard rules on both panel card sources: no hover
states (touch-only surface), no animation loops (entrances only,
each timed on a design duration token with --nq-ease-out), an inert
dock strip and pointer-none frames, the whole plate as one tap
target with the away plate control-free, and both the quest card
and its button opening the confirm dialog. The away plate's
navigation contract is asserted against the bundle by
test_away_plate_does_not_navigate."""
board = _read(PARTY_BOARD)
log = _read(QUEST_LOG)
for source in (board, log):
assert ":hover" not in source
assert "infinite" not in source
for animation in re.findall(r"animation:[^;]+;", source):
assert re.fullmatch(
r"animation: [a-z-]+ var\(--nq-dur-(?:micro|base|modal)\) "
r"var\(--nq-ease-out\);",
" ".join(animation.split()),
), animation
for transition in re.findall(r"transition:[^;]+;", source):
assert transition in (
"transition: transform var(--nq-dur-micro) var(--nq-ease-out);",
), transition
dock = re.search(r"\n \.dock \{([^}]*)\}", source)
assert dock is not None
assert "pointer-events: none" in dock.group(1)
assert "user-select: none" in dock.group(1)
frame = re.search(r"\n \.frame \{([^}]*)\}", source)
assert frame is not None
assert "pointer-events: none" in frame.group(1)
# Nothing in either dock's markup can be tapped: no handlers, no
# button, no focusable or role-bearing element.
board_dock = board[board.index("private _renderDock") :]
log_dock = log[
log.index("private _renderDock") : log.index("private _returnToBoard")
]
for markup in (board_dock, log_dock):
for tappable in ("@click", "@keydown", "<button", 'role="button"', "tabindex"):
assert tappable not in markup, tappable
# The whole plate is the tap target: the button wraps crest, name,
# pill, progress line and bar, and it is the board's only button.
plate = board[board.index('class="plate"') : board.index('class="plate away"')]
for part in (
'class="crest"',
'class="name"',
'class="pill"',
'class="progress-line"',
'class="bar"',
):
assert part in plate, part
assert board.count("<button") == 1
# The away plate is a plain div — nothing tappable, never navigates.
away = board[
board.index('class="plate away"') : board.index("private _openQuestLog")
]
assert "<button" not in away
assert "@click" not in away
# On the log, the whole quest card AND its button open the confirm
# dialog (§3.2); the sealed card renders no control at all.
quest = log[log.index("private _renderQuest") : log.index("private _renderRollup")]
assert quest.count("() => this._openConfirm(instance.id)") == 2
sealed_template = quest[
quest.index('class="quest sealed"') : quest.index('class="quest tappable"')
]
assert "@click" not in sealed_template
def test_panel_text_sizes_respect_the_22px_floor() -> None:
"""PANEL-SPEC §1: no body text below 22px. Every font-size in the
panel styles resolves against the panel size tokens or an explicit
px value, and the only text under the floor is the spec's own
tracked uppercase Cinzel labels (§3 header sub, §3.1 range, §3.4
roll-up label, §4 kicker, §5 stat labels) and the d20 mark numerals
the spec sizes by hand (§2, §3) — never a Nunito body line."""
sizes = _size_tokens(_read(REWARD_TOKENS))
for path in (PARTY_BOARD, QUEST_LOG):
style = _style_literal(_read(path), STYLE_CONSTANTS[path])
for selector, body in _css_rules(style):
declared = re.search(r"font-size:\s*([^;]+);", body)
if declared is None:
continue
px = _font_size_px(declared.group(1), sizes)
assert px is not None, (
f"{path.name}: {selector.strip()} {declared.group(1)}"
)
if px >= 22:
continue
assert (
"text-transform: uppercase" in body or ".d20-numeral" in selector
), f"{path.name}: {selector.strip()} is {px}px below the panel floor"
def test_panel_text_inks_come_from_the_token_set() -> None:
"""PANEL-SPEC §1: every ink is a token from the approved >=4.5:1 set
or one of the spec's own literals — no alpha-muted text is ever
introduced."""
declared = set(
re.findall(r"^\s*(--[a-z0-9-]+):", _read(REWARD_TOKENS), re.MULTILINE)
)
for path in (PARTY_BOARD, QUEST_LOG):
style = _style_literal(_read(path), STYLE_CONSTANTS[path])
for value in re.findall(r"(?<![-\w])color:\s*([^;]+);", style):
value = " ".join(value.split())
if value.startswith("var("):
assert value[4:-1] in declared, f"{path.name}: {value}"
else:
assert value in APPROVED_NON_TOKEN_INKS, f"{path.name}: {value}"
def test_panel_cards_reference_no_admin_only_services() -> None:
# Only the kid panel sources are scanned: the bundle also contains the
# sibling admin card, so its parent-only service names are expected there.
@@ -157,4 +464,425 @@ def test_panel_cards_reference_no_admin_only_services() -> None:
assert BUNDLE_PATH.is_file()
bundle = _read(BUNDLE_PATH)
assert "nestquest-party-board-card" in bundle
assert "nestquest-quest-log-card" in bundle
assert "nestquest-quest-log-card" in bundle
def test_party_board_discovers_children_from_the_household_roster() -> None:
"""Feature 20: with no child_order configured, the board discovers
the ordered child slugs from the household rollup's child_roster
attribute; explicit configuration still wins."""
source = _read(PARTY_BOARD)
assert "child_roster" in source
assert "sensor.nestquest_household_quests_due_today" in source
# Discovery only fills in for a MISSING child_order; a supplied
# order array is honoured verbatim before the discovered list is
# ever consulted.
assert "Array.isArray(order)" in source
assert "_discoveredChildSlugs()" in source
# --- Render tests (built bundle under jsdom) ---------------------------------
#: The seeded three-child household, in the API's sort order: Ada and
#: Bo share one daily quest (Bo is away today), Cory has none.
ROSTER = [
{"child_id": 1, "name": "Ada", "slug": "ada"},
{"child_id": 2, "name": "Bo", "slug": "bo"},
{"child_id": 3, "name": "Cory", "slug": "cory"},
]
def _state(state: str, **attributes) -> dict:
return {"state": state, "attributes": attributes}
def _three_child_states() -> dict:
"""The hass states a three-child household exposes.
Entity ids follow the documented naming contract
(design/ENTITIES-AND-SERVICES.md §1): the household rollup and the
per-child sensors slugged from the child names.
"""
return {
"sensor.nestquest_household_quests_due_today": _state(
"2",
children={"1": 1, "2": 1, "3": 0},
child_roster=ROSTER,
),
"sensor.nestquest_ada_quests_due_today": _state(
"1", child_name="Ada", present=True
),
"sensor.nestquest_ada_quests_completed_today": _state("0"),
"sensor.nestquest_ada_completion_pct_today": _state("0"),
"binary_sensor.nestquest_ada_present_today": _state("on"),
"sensor.nestquest_bo_quests_due_today": _state(
"1", child_name="Bo", present=False
),
"sensor.nestquest_bo_quests_completed_today": _state("0"),
"sensor.nestquest_bo_completion_pct_today": _state("0"),
"binary_sensor.nestquest_bo_present_today": _state("off"),
"sensor.nestquest_cory_quests_due_today": _state(
"0", child_name="Cory", present=True
),
"sensor.nestquest_cory_quests_completed_today": _state("0"),
"sensor.nestquest_cory_completion_pct_today": _state("100"),
"binary_sensor.nestquest_cory_present_today": _state("on"),
}
def _render_party_board(
config: dict,
states: dict,
url: str | None = None,
click_plate: str | None = None,
) -> dict:
"""Render the built bundle's party board and return its plates.
Drives frontend/tests/render-party-board.mjs: the harness imports
the committed bundle (the artifact HACS ships) into a jsdom window,
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.
"""
assert BUNDLE_PATH.is_file(), "bundle missing: run cd frontend && npm run build"
assert RENDER_HARNESS.is_file()
spec = {
"bundle": str(BUNDLE_PATH),
"tag": "nestquest-party-board-card",
"config": config,
"hass": {"config": {"time_zone": "UTC"}, "states": states},
}
if url is not None:
spec["url"] = url
if click_plate is not None:
spec["click_plate"] = click_plate
completed = subprocess.run(
["node", str(RENDER_HARNESS)],
input=json.dumps(spec),
capture_output=True,
text=True,
timeout=120,
)
assert completed.returncode == 0, (
f"render harness failed: {completed.stderr}"
)
return json.loads(completed.stdout)
def test_party_board_renders_discovered_children_in_sort_order() -> None:
"""No child_order key: three plates render in the roster's sort
order (the coordinator snapshot's order), one per child."""
result = _render_party_board(
{"type": "custom:nestquest-party-board-card"},
_three_child_states(),
)
assert result["plates"] == [
{"name": "Ada", "kind": "present"},
{"name": "Bo", "kind": "away"},
{"name": "Cory", "kind": "present"},
]
def test_explicit_child_order_still_wins_over_discovery() -> None:
"""A supplied child_order keeps working: it overrides the household
roster's order and limits the plates to the configured slugs."""
result = _render_party_board(
{
"type": "custom:nestquest-party-board-card",
"child_order": ["bo", "ada"],
},
_three_child_states(),
)
assert [plate["name"] for plate in result["plates"]] == ["Bo", "Ada"]
assert "Cory" not in [plate["name"] for plate in result["plates"]]
# --- Dashboard strategy tests -------------------------------------------------
STRATEGY_NAME = "nestquest-party"
def _generate_dashboard(config: dict, states: dict, url: str | None = None) -> dict:
"""Generate the strategy's dashboard from the built bundle.
Drives frontend/tests/render-strategy.mjs: the harness imports the
committed bundle into a jsdom window at the given dashboard URL and
prints the views ``window.customStrategies["nestquest-party"].
generate(config, hass)`` returns.
"""
assert BUNDLE_PATH.is_file(), "bundle missing: run cd frontend && npm run build"
assert STRATEGY_HARNESS.is_file()
spec = {
"bundle": str(BUNDLE_PATH),
"url": url or "http://homeassistant.local/nestquest/party",
"config": config,
"hass": {"config": {"time_zone": "UTC"}, "states": states},
}
completed = subprocess.run(
["node", str(STRATEGY_HARNESS)],
input=json.dumps(spec),
capture_output=True,
text=True,
timeout=120,
)
assert completed.returncode == 0, (
f"strategy harness failed: {completed.stderr}"
)
return json.loads(completed.stdout)
def test_strategy_is_registered_on_the_bundle() -> None:
"""The strategy ships in the same bundle as the cards and registers
itself under window.customStrategies so a dashboard can use
strategy: { type: custom:nestquest-party }."""
source = _read(STRATEGY_SOURCE)
assert "customStrategies" in source
assert f'["{STRATEGY_NAME}"]' in source or f'"{STRATEGY_NAME}"' in source
bundle = _read(BUNDLE_PATH)
assert "nestquest-party" in bundle
def test_strategy_generates_views_for_three_children() -> None:
"""For the seeded three-child household the strategy generates one
party-board view plus one quest-log view per child in roster order,
with COMPUTED paths: the board view at the dashboard root, each log
view at the child's slug so quest-log.ts's childSlugFromPath reads
the child from the URL's last segment."""
result = _generate_dashboard({}, _three_child_states())
views = result["views"]
assert len(views) == 4
assert [view["path"] for view in views] == [
"party",
"ada",
"bo",
"cory",
]
assert [view["title"] for view in views] == [
"The Party",
"Ada's Quest Log",
"Bo's Quest Log",
"Cory's Quest Log",
]
def test_strategy_every_view_is_panel_type() -> None:
"""Every generated view carries ``type: "panel"``: Home Assistant
defaults an unspecified view to Masonry, which constrains the
1080px-tall NestQuest card to a narrow column (README's TouchHub
setup warns of exactly this); with a generated dashboard there is
no editor step left to set Panel by hand."""
result = _generate_dashboard({}, _three_child_states())
for view in result["views"]:
assert view["type"] == "panel"
def test_strategy_log_view_titles_use_the_roster_display_name() -> None:
"""Quest-log view titles come from the roster's ``name`` field (the
child's display name), not the lowercased entity-id slug; the slug
stays the view's path."""
result = _generate_dashboard(
{},
{
"sensor.nestquest_household_quests_due_today": _state(
"0",
child_roster=[
{"child_id": 7, "name": "Milo", "slug": "milo"},
],
),
},
)
views = result["views"]
assert len(views) == 2
assert views[1]["path"] == "milo"
assert views[1]["title"] == "Milo's Quest Log"
def test_strategy_passes_weather_entity_through_to_the_cards() -> None:
"""An explicit ``weather_entity`` in the strategy configuration is
passed through to the generated card configs (both the board and
the quest log render the weather dock when it is set)."""
result = _generate_dashboard(
{"weather_entity": "weather.home"},
_three_child_states(),
)
views = result["views"]
for view in views:
assert view["cards"][0]["weather_entity"] == "weather.home"
# And without it, no weather_entity key is emitted at all.
unset = _generate_dashboard({}, _three_child_states())
for view in unset["views"]:
assert "weather_entity" not in view["cards"][0]
def test_strategy_wires_navigation_between_the_views() -> None:
"""The board's quest_log_path and each log's board_path are computed
to the dashboard root the strategy renders at, so party-board.ts's
crest tap pushes <root>/<slug> and quest-log.ts's idle return goes
back to the board — neither path is configured by hand."""
dashboard_url = "http://homeassistant.local/nestquest"
root = "/nestquest"
result = _generate_dashboard(
{}, _three_child_states(), url=dashboard_url
)
views = result["views"]
board = views[0]["cards"][0]
assert board["type"] == "custom:nestquest-party-board-card"
assert board["quest_log_path"] == root
for slug, view in zip(("ada", "bo", "cory"), views[1:]):
assert view["cards"][0]["type"] == "custom:nestquest-quest-log-card"
assert view["cards"][0]["board_path"] == root
def test_strategy_zero_children_still_generates_the_board() -> None:
"""With an empty roster (NestQuest not set up yet) the strategy
renders the board view alone — the board card shows its own
"not set up yet" notice for an empty roster — and never crashes."""
result = _generate_dashboard({}, {})
assert len(result["views"]) == 1
assert result["views"][0]["path"] == "party"
def test_strategy_config_overrides_still_apply() -> None:
"""Explicit strategy configuration wins where the design allows: an
explicit url_path pins the computed dashboard root."""
result = _generate_dashboard(
{"url_path": "/wallboard"},
_three_child_states(),
)
root = "/wallboard"
assert result["views"][0]["cards"][0]["quest_log_path"] == root
for view in result["views"][1:]:
assert view["cards"][0]["board_path"] == root
# --- Navigation tests (strategy-computed paths under jsdom) -------------------
def _render_quest_log(
config: dict,
states: dict,
url: str,
idle_ms: int | None = None,
probe_ms: int | None = None,
) -> dict:
"""Render the built bundle's quest log and report its location.
Drives frontend/tests/render-quest-log.mjs: the harness imports the
committed bundle (the artifact HACS ships) into a jsdom window at
``url`` — the card resolves its child from the pathname's last
segment — waits the optional probe window and captures one snapshot
of the render mid-wait, then the optional idle window, and prints
the final pathname and rendered title (plus the probe snapshot when
``probe_ms`` was given).
"""
assert BUNDLE_PATH.is_file(), "bundle missing: run cd frontend && npm run build"
assert QUEST_LOG_HARNESS.is_file()
spec = {
"bundle": str(BUNDLE_PATH),
"url": url,
"config": config,
"hass": {"config": {"time_zone": "UTC"}, "states": states},
}
if idle_ms is not None:
spec["idle_ms"] = idle_ms
if probe_ms is not None:
spec["probe_ms"] = probe_ms
completed = subprocess.run(
["node", str(QUEST_LOG_HARNESS)],
input=json.dumps(spec),
capture_output=True,
text=True,
timeout=120,
)
assert completed.returncode == 0, (
f"quest-log harness failed: {completed.stderr}"
)
return json.loads(completed.stdout)
def test_present_crest_tap_navigates_to_the_child_quest_log() -> None:
"""Tapping a present crest pushes <dashboard root>/<slug>: the exact
URL the strategy computed for that child's quest log view (the log
then resolves its child from the path's last segment)."""
generated = _generate_dashboard(
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
)
board_config = generated["views"][0]["cards"][0]
result = _render_party_board(
board_config,
_three_child_states(),
url="http://homeassistant.local/nestquest",
click_plate="Ada",
)
# Only the present adventurers' plates are tappable buttons.
assert result["tappable"] == ["Ada", "Cory"]
assert result["location"] == "/nestquest/ada"
def test_away_plate_does_not_navigate() -> None:
"""Bo is away today: his plate is not a button, and tapping it leaves
the URL at the dashboard root — away adventurers cannot open a log."""
generated = _generate_dashboard(
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
)
board_config = generated["views"][0]["cards"][0]
result = _render_party_board(
board_config,
_three_child_states(),
url="http://homeassistant.local/nestquest",
click_plate="Bo",
)
assert "Bo" not in result["tappable"]
assert result["location"] == "/nestquest"
def test_quest_log_idle_return_navigates_to_the_board() -> None:
"""After the idle window the quest log returns to the board using the
strategy-computed board_path (the dashboard root) — and it resolved
Ada from the URL's last segment first. ``idle_return_seconds`` is
set by hand because the card's 40-second default is too slow for a
test; the strategy never generates that knob."""
generated = _generate_dashboard(
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
)
log_config = {**generated["views"][1]["cards"][0], "idle_return_seconds": 1}
result = _render_quest_log(
log_config,
_three_child_states(),
url="http://homeassistant.local/nestquest/ada",
idle_ms=2000,
)
assert result["headline"] == "Ada's Quest Log"
assert result["location"] == "/nestquest"
def test_quest_complete_screen_returns_to_the_board_after_the_countdown() -> None:
"""The 1c screen renders with its countdown line and auto-returns to
the strategy-computed board path when it reaches zero. The design
shows it for 12 s; the test shortens complete_screen_seconds to 1
the same way the idle test shortens idle_return_seconds."""
generated = _generate_dashboard(
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
)
log_config = {
**generated["views"][1]["cards"][0],
"complete_screen_seconds": 1,
}
states = {
**_three_child_states(),
"binary_sensor.nestquest_ada_all_done": _state("on"),
}
result = _render_quest_log(
log_config,
states,
url="http://homeassistant.local/nestquest/ada",
probe_ms=400,
idle_ms=2400,
)
# Mid-wait the complete screen is up with its countdown line…
assert result["probe"] is not None
assert result["probe"]["location"] == "/nestquest/ada"
assert "Quest complete" in result["probe"]["html"]
assert result["probe"]["countdown"] == "Returning to The Party in 1 seconds"
# …and at zero the card has returned to the party board.
assert result["location"] == "/nestquest"
+164
View File
@@ -12,6 +12,7 @@ from __future__ import annotations
import datetime
import pytest
from homeassistant.util import slugify
from conftest import StubSnapshotClient, set_coordinator_client, wire_entry_to_registry
@@ -19,6 +20,7 @@ from custom_components.nestquest import async_setup_entry, async_unload_entry
from custom_components.nestquest.const import DOMAIN
from custom_components.nestquest.sensor import (
MAX_STATE_LENGTH,
_slugify,
_state_within_limit,
)
@@ -539,3 +541,165 @@ async def test_household_rollups_sum_the_active_children(
assert cycle_day_entity.name == "NestQuest cycle day"
assert cycle_day_entity.native_value == 4
assert cycle_day_entity.extra_state_attributes["today"] == _today_iso()
async def test_household_due_sensor_publishes_the_ordered_child_roster(
hass, make_entry
) -> None:
"""Feature 20: the rollup carries the ordered child roster beside
the unchanged per-child ``children`` counts, so the panel cards can
discover the board without a configured child_order. The order is
the coordinator snapshot's (the API's sort_order, then id)."""
entry, _coordinator, _client = await _setup_entry(
hass, make_entry, _seeded_payload()
)
attributes = hass.entities[
"nestquest_household_quests_due_today"
].extra_state_attributes
assert attributes["child_roster"] == [
{"child_id": ADA, "name": "Ada", "slug": "ada"},
{"child_id": BO, "name": "Bo", "slug": "bo"},
{"child_id": CORY, "name": "Cory", "slug": "cory"},
]
# The pre-existing per-child counts attribute is untouched.
assert attributes["children"] == {
str(ADA): 1,
str(BO): 1,
str(CORY): 0,
}
async def test_household_roster_tracks_the_snapshot_on_refresh(
hass, make_entry
) -> None:
"""The roster re-derives from every snapshot: a reorder and a
rename in the API payload show up (with the re-derived slug) on the
next refresh, like the sensor names already do."""
reordered = _payload(
[
_child(CORY, "Cory"),
_child(ADA, "Ada", [_instance(7, ADA)]),
_child(BO, "Mirren", [_instance(8, BO)]),
]
)
entry, coordinator, _client = await _setup_entry(
hass, make_entry, _seeded_payload(), reordered
)
roster_entity = hass.entities["nestquest_household_quests_due_today"]
assert [entry["slug"] for entry in roster_entity.extra_state_attributes["child_roster"]] == [
"ada",
"bo",
"cory",
]
await coordinator.async_refresh()
assert roster_entity.extra_state_attributes["child_roster"] == [
{"child_id": CORY, "name": "Cory", "slug": "cory"},
{"child_id": ADA, "name": "Ada", "slug": "ada"},
{"child_id": BO, "name": "Mirren", "slug": "mirren"},
]
async def test_duplicate_display_names_get_registry_suffix_slugs(
hass, make_entry
) -> None:
"""Two children may share a nickname (the children layer allows
it); the roster's slugs then mirror the registry's collision
suffixing (_2, _3, ...) in snapshot order, so both plates resolve."""
payload = _payload(
[
_child(ADA, "Ada", [_instance(7, ADA)]),
_child(BO, "Ada"),
]
)
entry, _coordinator, _client = await _setup_entry(hass, make_entry, payload)
assert hass.entities[
"nestquest_household_quests_due_today"
].extra_state_attributes["child_roster"] == [
{"child_id": ADA, "name": "Ada", "slug": "ada"},
{"child_id": BO, "name": "Ada", "slug": "ada_2"},
]
async def test_empty_household_publishes_an_empty_roster(
hass, make_entry
) -> None:
"""An empty household is a valid 0: the roster is an empty list,
and the card's discovery of it renders the not-set-up notice."""
entry, _coordinator, _client = await _setup_entry(
hass, make_entry, _payload([])
)
attributes = hass.entities[
"nestquest_household_quests_due_today"
].extra_state_attributes
assert attributes["child_roster"] == []
assert attributes["children"] == {}
def test_slugify_mirrors_home_assistant_entity_id_derivation() -> None:
"""The roster slugs match homeassistant.util.slugify — the real
slugifier HA derives entity ids from, composed with the entity-id
length cap the entity registry applies to ``sensor.`` ids."""
assert _slugify("Ada") == "ada"
assert _slugify("Mary Jane") == "mary_jane"
assert _slugify("Mary-Jane") == "mary_jane"
assert _slugify("O'Brien") == "o_brien"
assert _slugify("Émilie") == "emilie"
assert _slugify("Åsa") == "asa"
assert _slugify(" Bo ") == "bo"
# HA's wrapper answers "unknown" when a name slugs to nothing.
assert _slugify(" ") == "unknown"
assert _slugify("?!?") == "unknown"
# The registry caps the entity_id at 64 characters, so the slugged
# object id alone is capped at 64 - len("sensor.").
assert _slugify("a" * 80) == "a" * (64 - len("sensor."))
def test_slugify_transliterates_non_latin_names_like_home_assistant() -> None:
"""HA's slugifier transliterates every script through unidecode,
so a non-Latin child name slugs to its romanization — never to the
``unknown`` sentinel — and the roster publishes the same slug HA's
entity-id derivation produces for that name."""
assert _slugify("Дана") == "dana"
assert _slugify("京子") == "jing_zi"
assert _slugify("Zoë") == "zoe"
async def test_non_latin_child_names_resolve_auto_discovery(
hass, make_entry
) -> None:
"""A non-Latin child name slugs through the real slugifier, so the
roster slug IS the object id of the per-child sensor's entity_id
and the cards' auto-discovery resolves that child.
HA derives the per-child entity id from the entity NAME ("NestQuest
京子 quests due today") with the same slugifier the roster uses, so
the two must agree exactly; the reviewed mirror dropped non-Latin
characters (slugging "京子" to "unknown"), so the cards built
"sensor.nestquest_unknown_…" ids that no entity had."""
payload = _payload(
[
_child(ADA, "Дана", [_instance(7, ADA)]),
_child(BO, "京子", [_instance(8, BO)]),
]
)
entry, _coordinator, _client = await _setup_entry(hass, make_entry, payload)
roster = hass.entities[
"nestquest_household_quests_due_today"
].extra_state_attributes["child_roster"]
assert roster == [
{"child_id": ADA, "name": "Дана", "slug": "dana"},
{"child_id": BO, "name": "京子", "slug": "jing_zi"},
]
for roster_entry in roster:
due_entity = _sensor(hass, roster_entry["child_id"], "quests_due_today")
assert due_entity.name == (
f"NestQuest {roster_entry['name']} quests due today"
)
# The entity id HA's registry derives for this entity (from the
# same slugifier) embeds exactly the slug the roster publishes:
# the card builds sensor.nestquest_<slug>_quests_due_today.
assert slugify(due_entity.name) == (
f"nestquest_{roster_entry['slug']}_quests_due_today"
)