From eeb7ba64830af6578ed8ab9f06671eb43220c2c4 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 3 Jul 2026 19:13:08 +0000 Subject: [PATCH] Use the generic walker in the Lovelace repair --- .../repairs/unknown_entity_references.py | 248 +----------- .../repairs/test_unknown_entity_references.py | 373 +----------------- 2 files changed, 24 insertions(+), 597 deletions(-) diff --git a/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py index 9b5a447215..27b9c741b4 100644 --- a/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py @@ -15,11 +15,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER -from ....entity_filtering import ( - async_filter_known_entity_ids, - async_get_all_entity_ids, - split_comma_separated_entity_ids, -) +from ....dashboard_extraction import extract_entities_from_dashboard_node +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair if TYPE_CHECKING: @@ -126,248 +123,13 @@ async def async_inspect(self) -> None: @callback def __async_extract_entities(self, config: dict[str, Any]) -> dict[str, int | str]: - """Extract entities from a dashboard config.""" + """Extract entities from a dashboard config, keyed by their view path.""" entities: dict[str, int | str] = {} if isinstance(config, dict) and (views := config.get("views")): for view_index, view in enumerate(views): if not isinstance(view, dict): continue view_path: int | str = view.get("path") or view_index - for entity_id_raw in self.__async_extract_entities_from_view(view): - for entity_id in split_comma_separated_entity_ids(entity_id_raw): - if entity_id not in entities: - entities[entity_id] = view_path - return entities - - @callback - def __async_extract_entities_from_view(self, config: dict[Any]) -> set[str]: - """Extract entities from a view config.""" - entities = set() - if badges := config.get("badges"): - for badge in badges: - entities.update(self.__async_extract_entities_from_badge(badge)) - if cards := config.get("cards"): - for card in cards: - entities.update(self.__async_extract_entities_from_card(card)) - if sections := config.get("sections"): - for section in sections: - entities.update(self.__async_extract_entities_from_section(section)) - return entities - - @callback - def __async_extract_entities_from_section(self, config: dict[Any]) -> set[str]: - """Extract entities from a section config.""" - entities = set() - if cards := config.get("cards"): - for card in cards: - entities.update(self.__async_extract_entities_from_card(card)) - return entities - - @callback - def __async_extract_common(self, config: dict[str, Any] | str) -> set[str]: - """Extract entities from common dashboard config.""" - entities: set[str] = set() - - if not isinstance(config, dict): - return entities - - for key in ("camera_image", "entity", "entities", "entity_id"): - if entity := config.get(key): - if isinstance(entity, str): - entities.add(entity) - if isinstance(entity, list): - for item in entity: - if isinstance(item, str): - entities.add(item) - elif ( - isinstance(item, dict) - and "entity" in item - and isinstance(item["entity"], str) - ): - entities.add(item["entity"]) - if ( - isinstance(entity, dict) - and "entity" in entity - and isinstance(entity["entity"], str) - ): - entities.add(entity["entity"]) - return entities - - @callback - def __async_extract_entities_from_badge( - self, - config: dict[str, Any] | str, - ) -> set[str]: - """Extract entities from a dashboard badge config.""" - if isinstance(config, str): - return {config} - if isinstance(config, dict): - if (entity_id := config.get("entity")) and isinstance(entity_id, str): - return {config["entity"]} - if (entities := config.get("entities")) and isinstance(entities, list): - extracted = [] - for entity in entities: - if isinstance(entity, str): - extracted.append(entity) - elif ( - isinstance(entity, dict) - and "entity" in entity - and isinstance(entity["entity"], str) - ): - extracted.append(entity["entity"]) - return set(extracted) - return set() - - @callback - # pylint: disable-next=too-many-branches - def __async_extract_entities_from_card( # noqa: C901, PLR0912 - self, - config: dict[str, Any], - ) -> set[str]: - """Extract entities from a dashboard card config.""" - if not isinstance(config, dict): - return set() - - entities = self.__async_extract_common(config) - entities.update(self.__async_extract_entities_from_actions(config)) - - if condition := config.get("condition"): - entities.update( - self.__async_extract_entities_from_condition(condition), - ) - - if card := config.get("card"): - entities.update(self.__async_extract_entities_from_card(card)) - - if cards := config.get("cards"): - for card in cards: - entities.update(self.__async_extract_entities_from_card(card)) - - for key in ("header", "footer"): - if header_footer := config.get(key): - entities.update( - self.__async_extract_entities_from_header_footer(header_footer), - ) - - if elements := config.get("elements"): - for element in elements: - entities.update(self.__async_extract_entities_from_element(element)) - - # Mushroom - if chips := config.get("chips"): - for chip in chips: - entities.update(self.__async_extract_entities_from_mushroom_chip(chip)) - - # Heading card - if badges := config.get("badges"): - for badge in badges: - if isinstance(badge, dict): - entities.update(self.__async_extract_common(badge)) - entities.update(self.__async_extract_entities_from_actions(badge)) - - visibility = config.get("visibility") - if isinstance(visibility, list): - for condition in visibility: - if isinstance(condition, dict): - entities.update( - self.__async_extract_entities_from_condition(condition) - ) - - return entities - - @callback - def __async_extract_entities_from_actions(self, config: dict[str, Any]) -> set[str]: - """Extract entities from a dashboard config containing actions.""" - entities = set() - for key in ( - "tap_action", - "hold_action", - "double_tap_action", - "subtitle_tap_action", - ): - if isinstance(config, dict) and (action := config.get(key)): - entities.update(self.__async_extract_entities_from_action(action)) - return entities - - @callback - def __async_extract_entities_from_action(self, config: dict[str, Any]) -> set[str]: - """Extract entities from a dashboard action config.""" - entities = set() - for key in ("service_data", "target"): - if ( - isinstance(config, dict) - and (target := config.get(key)) - and isinstance(target, dict) - and (entity_id := target.get("entity_id")) - ): - if isinstance(entity_id, str): - entities.add(entity_id) - if isinstance(entity_id, list): - entities.update(entity_id) - return entities - - @callback - def __async_extract_entities_from_condition( - self, - config: dict[str, Any], - ) -> set[str]: - """Extract entities from a dashboard element config.""" - if "entity" in config and isinstance(config["entity"], str): - return {config["entity"]} - return set() - - @callback - def __async_extract_entities_from_element(self, config: dict[str, Any]) -> set[str]: - """Extract entities from a dashboard element config.""" - if not isinstance(config, dict): - return set() - - entities = self.__async_extract_common(config) - entities.update(self.__async_extract_entities_from_actions(config)) - entities.update(self.__async_extract_entities_from_action(config)) - - if conditions := config.get("conditions"): - for condition in conditions: - entities.update(self.__async_extract_entities_from_condition(condition)) - - if elements := config.get("elements"): - for element in elements: - entities.update(self.__async_extract_entities_from_element(element)) - - visibility = config.get("visibility") - if isinstance(visibility, list): - for condition in visibility: - if isinstance(condition, dict): - entities.update( - self.__async_extract_entities_from_condition(condition) - ) - - return entities - - @callback - def __async_extract_entities_from_header_footer( - self, - config: dict[str, Any], - ) -> set[str]: - """Extract entities from a dashboard haeder footer config.""" - entities = self.__async_extract_common(config) - entities.update(self.__async_extract_entities_from_actions(config)) - return entities - - @callback - def __async_extract_entities_from_mushroom_chip( - self, - config: dict[str, Any], - ) -> set[str]: - """Extract entities from mushroom chips.""" - if not isinstance(config, dict): - return set() - entities = self.__async_extract_common(config) - if chip := config.get("chip"): - entities.update( - self.__async_extract_entities_from_mushroom_chip(chip), - ) - if conditions := config.get("conditions"): - for condition in conditions: - entities.update(self.__async_extract_entities_from_condition(condition)) + for entity_id in extract_entities_from_dashboard_node(view): + entities.setdefault(entity_id, view_path) return entities diff --git a/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py b/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py index 5b9f2ee017..8726d7bd5d 100644 --- a/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py +++ b/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py @@ -1,14 +1,9 @@ -"""Golden-path tests for the Lovelace entity-reference extractor. +"""Tests for the Lovelace repair's dashboard-level entity extraction. -The dashboard walker in -``custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py`` -is the only place where Spook converts Lovelace YAML into a flat set of entity -IDs. These tests pin down its current behavior so the upcoming flattening into a -single recursive walker cannot regress it silently. - -The extraction methods are name-mangled private methods on ``SpookRepair``; -tests call them through the mangled attribute names, which is intentional — the -mission says "lock down the riskiest logic before any refactor". +The repair maps each referenced entity to the view it appears in, for the +issue's edit link. The generic per-node extraction itself is covered by +``tests/test_dashboard_extraction.py``; these tests cover the repair's +view-path bookkeeping on top of it. """ # pylint: disable=protected-access,wrong-import-order @@ -17,8 +12,6 @@ from types import SimpleNamespace from typing import TYPE_CHECKING, Any -from homeassistant.const import EVENT_STATE_CHANGED -from homeassistant.core import State from custom_components.spook.ectoplasms.lovelace.repairs.unknown_entity_references import ( SpookRepair, @@ -40,21 +33,6 @@ def _extract(repair: SpookRepair, config: dict[str, Any]) -> dict[str, int | str return repair._SpookRepair__async_extract_entities(config) # noqa: SLF001 # type: ignore[attr-defined] -def _extract_card(repair: SpookRepair, config: dict[str, Any]) -> set[str]: - """Call the name-mangled card-level extractor.""" - return repair._SpookRepair__async_extract_entities_from_card(config) # noqa: SLF001 # type: ignore[attr-defined] - - -def _extract_badge(repair: SpookRepair, config: Any) -> set[str]: - """Call the name-mangled badge-level extractor.""" - return repair._SpookRepair__async_extract_entities_from_badge(config) # noqa: SLF001 # type: ignore[attr-defined] - - -def _extract_element(repair: SpookRepair, config: dict[str, Any]) -> set[str]: - """Call the name-mangled element-level extractor.""" - return repair._SpookRepair__async_extract_entities_from_element(config) # noqa: SLF001 # type: ignore[attr-defined] - - def test_dashboard_with_no_views_returns_empty(repair: SpookRepair) -> None: """A dashboard with no ``views`` key yields no entities.""" assert _extract(repair, {}) == {} @@ -197,336 +175,23 @@ def async_create_issue(**kwargs: Any) -> None: ) -def test_card_single_entity_field(repair: SpookRepair) -> None: - """A card with a plain ``entity`` field is captured.""" - assert _extract_card(repair, {"type": "entity", "entity": "light.kitchen"}) == { - "light.kitchen" - } - - -def test_card_entities_list_mixed_forms(repair: SpookRepair) -> None: - """A card's ``entities`` list accepts strings and ``{"entity": ...}`` dicts.""" - config = { - "type": "entities", - "entities": [ - "light.kitchen", - {"entity": "switch.lamp"}, - {"entity": "sensor.temperature", "name": "Temp"}, - ], - } - assert _extract_card(repair, config) == { - "light.kitchen", - "switch.lamp", - "sensor.temperature", - } - - -def test_card_camera_image(repair: SpookRepair) -> None: - """The ``camera_image`` common field is captured.""" - assert _extract_card( - repair, {"type": "picture-entity", "camera_image": "camera.front"} - ) == {"camera.front"} - - -def test_card_nested_card_and_cards(repair: SpookRepair) -> None: - """``card`` (single) and ``cards`` (list) are both walked.""" - config = { - "type": "conditional", - "card": {"type": "entity", "entity": "light.kitchen"}, - "cards": [ - {"type": "entity", "entity": "switch.lamp"}, - {"type": "entity", "entity": "sensor.temperature"}, - ], - } - assert _extract_card(repair, config) == { - "light.kitchen", - "switch.lamp", - "sensor.temperature", - } - - -def test_card_tap_action_target(repair: SpookRepair) -> None: - """A ``tap_action`` with a target entity is captured.""" - config = { - "type": "button", - "tap_action": { - "action": "call-service", - "service": "light.toggle", - "target": {"entity_id": "light.kitchen"}, - }, - } - assert _extract_card(repair, config) == {"light.kitchen"} - +def test_dashboard_covers_custom_card_structures(repair: SpookRepair) -> None: + """Entities buried in a custom card structure are now reached. -def test_card_hold_action_service_data(repair: SpookRepair) -> None: - """A ``hold_action`` with service_data entities is captured.""" + The old per-card walker only recursed into known shapes; the generic + walker finds references anywhere. + """ config = { - "type": "button", - "hold_action": { - "action": "call-service", - "service": "light.turn_on", - "service_data": {"entity_id": ["light.kitchen", "light.living_room"]}, - }, - } - assert _extract_card(repair, config) == { - "light.kitchen", - "light.living_room", - } - - -def test_card_condition_entity(repair: SpookRepair) -> None: - """A card's ``condition.entity`` is captured.""" - config = { - "type": "conditional", - "condition": {"entity": "input_boolean.guest", "state": "on"}, - "card": {"type": "entity", "entity": "light.kitchen"}, - } - assert _extract_card(repair, config) == { - "input_boolean.guest", - "light.kitchen", - } - - -def test_card_visibility_conditions(repair: SpookRepair) -> None: - """A card's ``visibility`` list of conditions is captured.""" - config = { - "type": "entity", - "entity": "light.kitchen", - "visibility": [ - {"condition": "state", "entity": "input_boolean.guest", "state": "on"}, - ], - } - assert _extract_card(repair, config) == { - "light.kitchen", - "input_boolean.guest", - } - - -def test_card_header_and_footer(repair: SpookRepair) -> None: - """Header and footer common fields are captured.""" - config = { - "type": "entities", - "header": {"type": "picture", "camera_image": "camera.front"}, - "footer": {"type": "graph", "entity": "sensor.power"}, - "entities": ["light.kitchen"], - } - assert _extract_card(repair, config) == { - "camera.front", - "sensor.power", - "light.kitchen", - } - - -def test_card_picture_elements_walked(repair: SpookRepair) -> None: - """``elements`` on a picture-elements card are walked into.""" - config = { - "type": "picture-elements", - "elements": [ - {"type": "state-icon", "entity": "light.kitchen"}, - { - "type": "service-button", - "tap_action": { - "action": "call-service", - "service": "switch.toggle", - "target": {"entity_id": "switch.lamp"}, - }, - }, - ], - } - assert _extract_card(repair, config) == {"light.kitchen", "switch.lamp"} - - -def test_card_mushroom_chips(repair: SpookRepair) -> None: - """Mushroom chips and their conditions contribute entities.""" - config = { - "type": "custom:mushroom-chips-card", - "chips": [ - {"type": "entity", "entity": "sensor.temperature"}, + "views": [ { - "type": "template", - "entity": "switch.lamp", - "conditions": [ - {"entity": "input_boolean.guest"}, + "path": "home", + "cards": [ + { + "type": "custom:fancy-card", + "rows": [{"widget": {"entity": "sensor.custom"}}], + }, ], - }, - ], - } - assert _extract_card(repair, config) == { - "sensor.temperature", - "switch.lamp", - "input_boolean.guest", - } - - -def test_heading_card_badges(repair: SpookRepair) -> None: - """Heading card badges contribute entities and action targets.""" - config = { - "type": "heading", - "badges": [ - {"type": "entity", "entity": "sensor.temperature"}, - { - "type": "entity", - "entity": "binary_sensor.door", - "tap_action": { - "action": "call-service", - "service": "light.turn_on", - "target": {"entity_id": "light.kitchen"}, - }, - }, - ], - } - - assert _extract_card(repair, config) == { - "sensor.temperature", - "binary_sensor.door", - "light.kitchen", - } - - -def test_card_non_dict_returns_empty(repair: SpookRepair) -> None: - """A non-dict card config returns an empty set.""" - assert _extract_card(repair, "string-card") == set() # type: ignore[arg-type] - - -def test_badge_string_form(repair: SpookRepair) -> None: - """A bare string badge is treated as the entity itself.""" - assert _extract_badge(repair, "sensor.temperature") == {"sensor.temperature"} - - -def test_badge_entity_dict(repair: SpookRepair) -> None: - """A badge with an ``entity`` field is captured.""" - assert _extract_badge(repair, {"entity": "sensor.temperature"}) == { - "sensor.temperature" - } - - -def test_badge_entities_list(repair: SpookRepair) -> None: - """A badge with an ``entities`` list captures all forms.""" - config = { - "entities": [ - "sensor.a", - {"entity": "sensor.b"}, + } ] } - assert _extract_badge(repair, config) == {"sensor.a", "sensor.b"} - - -def test_badge_unknown_shape_returns_empty(repair: SpookRepair) -> None: - """An unrecognized badge shape yields an empty set.""" - assert _extract_badge(repair, {"foo": "bar"}) == set() - assert _extract_badge(repair, 42) == set() - - -def test_element_with_nested_elements(repair: SpookRepair) -> None: - """``elements`` nested inside an element are walked recursively.""" - config = { - "type": "state-badge", - "entity": "sensor.outside", - "elements": [ - {"type": "state-icon", "entity": "light.kitchen"}, - ], - } - assert _extract_element(repair, config) == { - "sensor.outside", - "light.kitchen", - } - - -def test_element_with_visibility(repair: SpookRepair) -> None: - """An element's ``visibility`` conditions contribute entities.""" - config = { - "type": "state-icon", - "entity": "light.kitchen", - "visibility": [ - {"condition": "state", "entity": "input_boolean.guest", "state": "on"}, - ], - } - assert _extract_element(repair, config) == { - "light.kitchen", - "input_boolean.guest", - } - - -def test_element_action_target(repair: SpookRepair) -> None: - """An element acting as its own action (``service_data``) contributes.""" - config = { - "type": "service-button", - "service": "switch.toggle", - "service_data": {"entity_id": "switch.lamp"}, - } - assert _extract_element(repair, config) == {"switch.lamp"} - - -def test_element_non_dict_returns_empty(repair: SpookRepair) -> None: - """A non-dict element returns an empty set.""" - assert _extract_element(repair, "not a dict") == set() # type: ignore[arg-type] - - -async def test_state_only_entity_addition_rechecks_dashboard_repairs( - hass: HomeAssistant, -) -> None: - """Test state-only entities trigger dashboard repair rechecks.""" - hass.data["lovelace"] = SimpleNamespace(dashboards={}) - repair = SpookRepair(hass) - await repair.async_activate() - repair.inspect_debouncer.async_shutdown() - calls = 0 - - def async_schedule_call() -> None: - """Capture scheduled inspections.""" - nonlocal calls - calls += 1 - - repair.inspect_debouncer = SimpleNamespace( - async_schedule_call=async_schedule_call, - async_shutdown=lambda: None, - ) - - hass.bus.async_fire( - EVENT_STATE_CHANGED, - { - "entity_id": "input_text.radio_sender", - "old_state": None, - "new_state": State("input_text.radio_sender", "Studio Brussel"), - }, - ) - await hass.async_block_till_done() - - assert calls == 1 - - await repair.async_deactivate() - - -async def test_state_only_entity_update_does_not_recheck_dashboard_repairs( - hass: HomeAssistant, -) -> None: - """Test normal state changes do not trigger dashboard repair rechecks.""" - hass.data["lovelace"] = SimpleNamespace(dashboards={}) - repair = SpookRepair(hass) - await repair.async_activate() - repair.inspect_debouncer.async_shutdown() - calls = 0 - - def async_schedule_call() -> None: - """Capture scheduled inspections.""" - nonlocal calls - calls += 1 - - repair.inspect_debouncer = SimpleNamespace( - async_schedule_call=async_schedule_call, - async_shutdown=lambda: None, - ) - - hass.bus.async_fire( - EVENT_STATE_CHANGED, - { - "entity_id": "input_text.radio_sender", - "old_state": State("input_text.radio_sender", "Studio Brussel"), - "new_state": State("input_text.radio_sender", "NPO Radio 2"), - }, - ) - await hass.async_block_till_done() - - assert calls == 0 - - await repair.async_deactivate() + assert _extract(repair, config) == {"sensor.custom": "home"}