From 5df56e50ec46d414c2c6f3028c6cdaf3264f7990 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:57:11 -0800 Subject: [PATCH] fix(controls): name the circuit or device in a control's error as Home Assistant shows it A failed write from a breaker, circuit priority, charger or adopted-device control named the circuit or device by a name captured at setup or taken from the panel, so a rename in Home Assistant never reached the error. The errors now read the entity's device entry when the message is built, through a shared _displayed_device_name; an added control always has a named device. An adopted device's card name is never empty any more: a nameless device whose declared type ends in a dot is named by its last type segment, else its id. --- CHANGELOG.md | 3 + custom_components/span_panel/adoption.py | 39 ++- custom_components/span_panel/entity.py | 21 +- custom_components/span_panel/helpers.py | 17 +- custom_components/span_panel/lock.py | 7 +- custom_components/span_panel/number.py | 10 +- custom_components/span_panel/select.py | 6 +- custom_components/span_panel/switch.py | 11 +- custom_components/span_panel/util.py | 17 +- tests/helpers.py | 45 +++ tests/test_adoption.py | 277 ++++++++++++--- tests/test_circuit_control.py | 19 +- tests/test_control_error_device_names.py | 425 +++++++++++++++++++++++ tests/test_control_gate.py | 48 +-- tests/test_evse_charge_limit.py | 30 +- tests/test_evse_lock.py | 3 +- tests/test_select.py | 70 ++-- 17 files changed, 862 insertions(+), 186 deletions(-) create mode 100644 tests/test_control_error_device_names.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cfd98fd..33ea9e2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ All notable changes to this project will be documented in this file. the panel to load and draws the panel once it has loaded**, where it showed "Unable to connect to SPAN Panel" until Retry was pressed or the dashboard was opened again. +- **An error from a breaker, circuit priority, charger or adopted-device control now names the circuit or device by the name you gave it in Home Assistant**, + where it kept the name the panel or the integration gave it. + ## [2.3.3] - 11/2026 **Install 2.3.3 before your panel updates to firmware r202645**, which gives the panel's circuits new device IDs: 2.3.3 carries every circuit entity, device, diff --git a/custom_components/span_panel/adoption.py b/custom_components/span_panel/adoption.py index d18eb403..22dfb5af 100644 --- a/custom_components/span_panel/adoption.py +++ b/custom_components/span_panel/adoption.py @@ -364,7 +364,7 @@ def adopted_device_info( identifiers={(DOMAIN, identifier)}, name=adopted_device_label(device), manufacturer=device.vendor_name or "Unknown", - model=device.model or humanised(device.device_type.rsplit(".", 1)[-1]), + model=device.model or _type_name(device.device_type), serial_number=device.serial_number, sw_version=device.software_version, hw_version=device.hardware_version, @@ -373,12 +373,30 @@ def adopted_device_info( def adopted_device_label(device: AdoptedDevice) -> str: - """Return the name this device is known by, on its card and in its errors. - - One function because the two have to agree: an error naming a device the - user cannot find in their device list is an error they cannot act on. + """Return the name this device's card is registered under, taken from the wire. + + It is what the device list shows until the user renames the device there. + Whatever names the device to a person names the card as Home Assistant + shows it instead (`util.device_display_name`): the errors its controls + raise, and the curation editor's heading, which falls back to this for a + device that has no card yet. An error naming a device the user cannot find + in their device list is an error they cannot act on. + + Never empty: the device's own name where it publishes one, else the last + non-empty segment of its `$type`, else its wire id. The type comes from a + publisher this integration does not model and can be malformed. The + library skips a device declaring none, but one ending in a dot has nothing + after it, and an empty name is worse than none: Core names a new card + after the panel's entry, a device that is not the panel, and blanks it on + the next load, leaving the user nothing to find it by. """ - return device.name or humanised(device.device_type.rsplit(".", 1)[-1]) + return device.name or _type_name(device.device_type) or device.device_id + + +def _type_name(device_type: str) -> str | None: + """Return the last non-empty segment of a dotted `$type`, humanised, or None where it has none.""" + segment = next((part for part in reversed(device_type.split(".")) if part), None) + return None if segment is None else humanised(segment) def humanised(wire_token: str) -> str: @@ -626,7 +644,6 @@ def __init__( ) self._node_id = declaration.node_id self._property_id = declaration.property_id - self._device_label = adopted_device_label(device) async def _publish(self, value: str) -> None: """Write one value and refresh, reporting both ways it can fail to happen. @@ -641,8 +658,10 @@ async def _publish(self, value: str) -> None: The messages name the property and the device rather than the circuit or the charger the curated keys name, because that is the whole identity an adopted device has: this integration models nothing about it beyond its - declaration, and the wire vocabulary is what the user will find in the - panel's own tree. + declaration. The property is named in the wire vocabulary, which is what + the user will find in the panel's own tree. The device is named as their + device list names it, which after a rename is not the wire's name -- see + `SpanPanelEntity._displayed_device_name`. No `hasattr` guard, unlike the curated controls. Those ask because a transport may not implement an optional protocol at all; this entity only @@ -658,7 +677,7 @@ async def _publish(self, value: str) -> None: not_delivered_key="adopted_control_not_delivered", placeholders={ "property": f"{self._node_id}/{self._property_id}", - "device": self._device_label, + "device": self._displayed_device_name(), }, ) await self.coordinator.async_request_refresh() diff --git a/custom_components/span_panel/entity.py b/custom_components/span_panel/entity.py index 3892f2a9..a153a8e4 100644 --- a/custom_components/span_panel/entity.py +++ b/custom_components/span_panel/entity.py @@ -32,7 +32,7 @@ from .field_paths import FieldPathDeclarationMixin from .id_builder import build_circuit_device_identifier from .naming import circuit_object_id_suffix -from .util import circuit_device_info, snapshot_to_device_info +from .util import circuit_device_info, device_display_name, snapshot_to_device_info _LOGGER = logging.getLogger(__name__) @@ -157,7 +157,9 @@ async def _async_control( user sees is `failed_key` / `not_delivered_key` with `placeholders`, which is why the reason is added here rather than at each call site: it is the one placeholder every one of these messages carries, and the one - a caller cannot know before the call. + a caller cannot know before the call. A placeholder that names the + circuit or device being commanded is `_displayed_device_name`'s answer, + so the message names it as the user's device list does. Returns the outcome for a caller that has something to say about a delivered command -- `no_op`, say, or the topic it went to. @@ -183,6 +185,21 @@ async def _async_control( return outcome + def _displayed_device_name(self) -> str: + """Return this entity's device as Home Assistant shows it, for a message that names it. + + The user's name for the device, else the one it is registered under + (`util.device_display_name`), read from the entity's `device_entry` when + the message is built, so a rename made since setup is the name it + carries. An added control always has a named device: Core links the + device before it adds the entity, and every device a control sits on is + registered under a name. + """ + device = self.device_entry + if device is None or not (name := device_display_name(device)): + raise RuntimeError(f"{self.entity_id} has no named device to report") + return name + async def async_added_to_hass(self) -> None: """Tell the coordinator which snapshot fields this entity reads. diff --git a/custom_components/span_panel/helpers.py b/custom_components/span_panel/helpers.py index d2568cef..85281918 100644 --- a/custom_components/span_panel/helpers.py +++ b/custom_components/span_panel/helpers.py @@ -326,15 +326,14 @@ def circuit_device_name(circuit: SpanCircuitSnapshot, circuit_id: str) -> str: def construct_circuit_label(circuit: SpanCircuitSnapshot | None, circuit_id: str) -> str: - """Name a circuit the way its owner knows it, for a message addressed to them. - - The panel's own name where there is one, and the tab identifier otherwise -- - which is what the entity itself was named from, so an error names the thing - the user is looking at rather than a wire UUID. A meter outside the panel - has no tabs, and takes `outside_meter_label`, as its own device does. - `None` is accepted because a circuit can drop out of a snapshot between a - command and its failure, and an error message is the worst possible place - to raise a second error. + """Name a circuit by the panel's name for it, for a message addressed to its owner. + + The panel's own name where there is one, and the tab identifier otherwise, + so a message names a circuit the user knows rather than a wire UUID. A + meter outside the panel has no tabs, and takes `outside_meter_label`, as + its own device does. `None` is accepted for a circuit the snapshot does + not hold, which `construct_shared_with_attribute` passes for a peer the + snapshot lacks. """ if circuit is not None and circuit.measures_outside_panel: return outside_meter_label(circuit_id) diff --git a/custom_components/span_panel/lock.py b/custom_components/span_panel/lock.py index e270ab3c..a09c76b9 100644 --- a/custom_components/span_panel/lock.py +++ b/custom_components/span_panel/lock.py @@ -96,7 +96,7 @@ def __init__( evse = snapshot.evse.get(evse_id, EMPTY_EVSE) use_circuit_numbers = data_coordinator.config_entry.options.get(USE_CIRCUIT_NUMBERS, False) display_suffix = resolve_evse_display_suffix(evse, snapshot, use_circuit_numbers) - # Named in the errors a person reads; `_evse_id` is the wire's node id. + # Named in the log line of each command; `_evse_id` is the wire's node id. self._charger_name = evse_display_name(evse, panel_name, display_suffix) self._attr_device_info = evse_device_info( @@ -158,14 +158,15 @@ async def _async_set(self, *, locked: bool) -> None: """Ask the panel to move the lock, through the control path every control shares. A refusal and an undelivered command both reach the caller; the state - stays what the charger reports until it republishes. + stays what the charger reports until it republishes. Either names the + charger as its card is shown, the user's name for it included. """ await self._async_control( self._description.set_fn(self.coordinator.client, self._evse_id, locked), command=f"a lock command for {self._charger_name}", failed_key="evse_lock_failed", not_delivered_key="evse_lock_not_delivered", - placeholders={"charger": self._charger_name}, + placeholders={"charger": self._displayed_device_name()}, ) await self.coordinator.async_request_refresh() diff --git a/custom_components/span_panel/number.py b/custom_components/span_panel/number.py index 2b965537..fee90eed 100644 --- a/custom_components/span_panel/number.py +++ b/custom_components/span_panel/number.py @@ -179,9 +179,9 @@ def __init__( use_circuit_numbers = data_coordinator.config_entry.options.get(USE_CIRCUIT_NUMBERS, False) display_suffix = resolve_evse_display_suffix(evse, snapshot, use_circuit_numbers) - # The charger's own name, kept because both ways this control can fail - # are reported to a person. `_evse_id` is the node id the wire uses; it - # names nothing the user can see on their dashboard. + # The charger's own name, for the log line of each command. `_evse_id` is + # the node id the wire uses; it names nothing the user can see on their + # dashboard. self._charger_name = evse_display_name(evse, panel_name, display_suffix) self._attr_device_info = evse_device_info( @@ -301,6 +301,8 @@ async def async_set_native_value(self, value: float) -> None: `_async_control` every control in this integration shares. A refusal never resolved an address; a `FAILED` outcome resolved one and was never handed over, which the library promises means it will not arrive later. + Either names the charger as its card is shown, the user's name for it + included. """ client = self.coordinator.client await self._async_control( @@ -308,7 +310,7 @@ async def async_set_native_value(self, value: float) -> None: command=f"a charge-current limit for {self._charger_name}", failed_key="evse_charge_limit_failed", not_delivered_key="evse_charge_limit_not_delivered", - placeholders={"charger": self._charger_name}, + placeholders={"charger": self._displayed_device_name()}, ) await self.coordinator.async_request_refresh() diff --git a/custom_components/span_panel/select.py b/custom_components/span_panel/select.py index 0cba04ab..74ae26d5 100644 --- a/custom_components/span_panel/select.py +++ b/custom_components/span_panel/select.py @@ -21,7 +21,6 @@ circuit_device_name, circuit_has_a_priority_select, construct_circuit_identifier_from_tabs, - construct_circuit_label, construct_tabs_attribute, construct_voltage_attribute, remove_withdrawn_controls, @@ -240,6 +239,9 @@ async def async_select_option(self, option: str) -> None: resolved an address and was never handed to the broker, which the library promises means it will not arrive later either. Both live in `_async_control`, which every control in this integration shares. + + The circuit is named as its own device is shown, the user's name for it + included. """ _LOGGER.debug("Selecting option: %s", option) client = self.coordinator.client @@ -250,7 +252,7 @@ async def async_select_option(self, option: str) -> None: command=f"a priority change for {self.entity_id}", failed_key="circuit_priority_failed", not_delivered_key="circuit_priority_not_delivered", - placeholders={"circuit": construct_circuit_label(self._get_circuit(), self.id)}, + placeholders={"circuit": self._displayed_device_name()}, ) await self.coordinator.async_request_refresh() diff --git a/custom_components/span_panel/switch.py b/custom_components/span_panel/switch.py index 1715bb5d..1d167039 100644 --- a/custom_components/span_panel/switch.py +++ b/custom_components/span_panel/switch.py @@ -31,7 +31,6 @@ circuit_device_name, circuit_has_a_breaker_switch, construct_circuit_identifier_from_tabs, - construct_circuit_label, construct_shared_with_attributes, construct_tabs_attribute, construct_voltage_attribute, @@ -316,6 +315,9 @@ async def _async_set_relay(self, state: str, *, is_on: bool) -> None: address, and a `FAILED` outcome that resolved one and was never handed over -- are raised by `_async_control`, which every control in this integration shares. + + The circuit is named as its own device is shown, the user's name for it + included. """ client = self.coordinator.client await self._async_control( @@ -323,12 +325,7 @@ async def _async_set_relay(self, state: str, *, is_on: bool) -> None: command=f"a relay command for {self.entity_id}", failed_key="circuit_relay_failed", not_delivered_key="circuit_relay_not_delivered", - placeholders={ - "circuit": construct_circuit_label( - self.coordinator.data.circuits.get(self._circuit_id), - self._circuit_id, - ) - }, + placeholders={"circuit": self._displayed_device_name()}, ) self._attr_is_on = is_on diff --git a/custom_components/span_panel/util.py b/custom_components/span_panel/util.py index 9c419e49..55dd7c4e 100644 --- a/custom_components/span_panel/util.py +++ b/custom_components/span_panel/util.py @@ -313,13 +313,16 @@ def evse_display_name( panel_name: str, display_suffix: str | None = None, ) -> str: - """Return what this charger is called wherever a person reads about it. - - Separate from the builder below because a charger is named in two places - that have to agree: its device card, and any message about it. The wire - calls a charger by its node id, which is what the panel needs and what - nobody reading a notification can act on -- so anything user-facing asks - here instead. + """Return the name a charger's device card is registered under. + + It is what the device list shows until the user renames the charger there. + The errors its controls raise name the card as Home Assistant shows it + (`SpanPanelEntity._displayed_device_name`) rather than by this. Separate + from the builder below because those controls keep it as `_charger_name`, + to name the charger in the log line of each command they send + (`command=`). The wire calls a charger by its node id, which is what the + panel needs and what nobody reading a message can act on, so nothing + user-facing names it by that. """ base_name = evse.model or "EV Charger" name = f"{base_name} ({display_suffix})" if display_suffix else base_name diff --git a/tests/helpers.py b/tests/helpers.py index f8ce4c9c..f2c83496 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock, patch from homeassistant import data_entry_flow +from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr @@ -28,6 +29,7 @@ from custom_components.span_panel.curation import CurationOverlay from custom_components.span_panel.sensor_definitions import PANEL_ENERGY_SENSORS from custom_components.span_panel.sensor_panel import SpanPanelEnergySensor +from custom_components.span_panel.switch import SpanPanelCircuitsSwitch from custom_components.span_panel.util import circuit_device_info from .factories import SpanPanelSnapshotFactory, pv_binding_for @@ -306,6 +308,49 @@ def coordinator_stand_in( return coordinator, entry +async def add_through_platform( + hass: HomeAssistant, entry: ConfigEntry, domain: str, entity: Entity +) -> MockEntityPlatform: + """Add one entity through a real platform, as setup adds it, and return the platform. + + Core links the entity to its device as it adds it, and that `device_entry` + is what a control names its device by in an error. An entity that was only + constructed has none, so a test that operates a control adds it here first. + + `entry` must be added to `hass` with the panel's device registered, as + `coordinator_stand_in` leaves it: the registry refuses a device for an + unknown entry, and Core drops an entity whose device names a parent that + does not exist, logging an error rather than raising. + """ + platform = MockEntityPlatform( + hass, domain=domain, platform_name=DOMAIN, logger=logging.getLogger(__name__) + ) + platform.config_entry = entry + await platform.async_add_entities([entity]) + await hass.async_block_till_done() + assert entity.device_entry is not None, f"the platform did not add {entity.unique_id}" + return platform + + +async def added_circuit_switch( + hass: HomeAssistant, circuit: SpanCircuitSnapshot +) -> tuple[MagicMock, SpanPanelCircuitsSwitch]: + """Return a circuit's breaker switch, added through a real platform, and its coordinator. + + The coordinator is `coordinator_stand_in`'s on a panel holding `circuit`, + with an async client and refresh for the switch to write through. Added + because a breaker error names the circuit by its device, which Core links + only as it adds the switch. + """ + snapshot = SpanPanelSnapshotFactory.create(circuits={circuit.circuit_id: circuit}) + coordinator, entry = coordinator_stand_in(hass, snapshot) + coordinator.client = AsyncMock() + coordinator.async_request_refresh = AsyncMock() + switch = SpanPanelCircuitsSwitch(coordinator, snapshot, circuit.circuit_id, PANEL_NAME) + await add_through_platform(hass, entry, "switch", switch) + return coordinator, switch + + @dataclass(frozen=True, slots=True) class MainMeterConsumedEnergy: """The main meter's Consumed Energy, live on a real sensor platform, and what feeds it.""" diff --git a/tests/test_adoption.py b/tests/test_adoption.py index 11f863b5..c1a690d4 100644 --- a/tests/test_adoption.py +++ b/tests/test_adoption.py @@ -9,6 +9,7 @@ from __future__ import annotations import ast +from collections.abc import Callable from dataclasses import replace import json from pathlib import Path @@ -17,10 +18,11 @@ from homeassistant.components.binary_sensor import BinarySensorDeviceClass from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass +from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, InvalidStateError -from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import device_registry as dr, entity_registry as er import pytest from pytest_homeassistant.common import MockConfigEntry from span_panel_api import AdoptedDevice, AdoptedProperty, PublishOutcome, PublishState @@ -31,7 +33,9 @@ CONTROL_PLATFORMS, DEVICE_CLASS_BY_UNIT, MAX_STATE_LENGTH, + AdoptedControl, AdoptedNumber, + AdoptedSwitch, adopted_control_count, adopted_identifier, adopted_unique_id, @@ -59,7 +63,7 @@ ) from .factories import SpanEvseSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for -from .helpers import register_panel_device +from .helpers import add_through_platform, register_panel_device if TYPE_CHECKING: from span_panel_api import SpanPanelSnapshot @@ -506,52 +510,28 @@ def test_a_number_takes_its_bounds_from_the_declaration(hass: HomeAssistant) -> assert (entity.native_min_value, entity.native_max_value, entity.native_step) == (10.0, 80.0, 5.0) -async def test_a_switch_publishes_the_vocabulary_homie_defines(hass: HomeAssistant) -> None: +async def test_a_switch_publishes_the_vocabulary_homie_defines( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: """`true` and `false`, not Home Assistant's `on` and `off`.""" - declaration = _property(node_id="relay", property_id="enabled", datatype="boolean", unit=None, settable=True) - snapshot = _snapshot(_device(properties=(declaration,))) - coordinator = MagicMock(data=snapshot) + coordinator, entity = await _live_adopted_switch(hass, registered_panel) coordinator.client.set_adopted_property = AsyncMock() - coordinator.async_request_refresh = AsyncMock() - (entity,) = create_adopted_switches( - coordinator, - snapshot, - dr.async_get(hass), - config_entry_id=ENTRY_ID, - panel_device_id="panel-device-id", - overlay=CurationOverlay.empty(), - ) await entity.async_turn_on() coordinator.client.set_adopted_property.assert_awaited_once_with("generator-1", "relay", "enabled", "true") -def _adopted_switch(hass: HomeAssistant) -> tuple[MagicMock, object]: - """One adopted switch and the coordinator whose client it writes through.""" - declaration = _property(node_id="relay", property_id="enabled", datatype="boolean", unit=None, settable=True) - snapshot = _snapshot(_device(properties=(declaration,))) - coordinator = MagicMock(data=snapshot) - coordinator.async_request_refresh = AsyncMock() - (entity,) = create_adopted_switches( - coordinator, - snapshot, - dr.async_get(hass), - config_entry_id=ENTRY_ID, - panel_device_id="panel-device-id", - overlay=CurationOverlay.empty(), - ) - return coordinator, entity - - -async def test_an_adopted_control_raises_when_the_command_was_not_delivered(hass: HomeAssistant) -> None: +async def test_an_adopted_control_raises_when_the_command_was_not_delivered( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: """A `FAILED` outcome is the promise that nothing will happen later. The library refuses such a write rather than letting paho queue it, so returning normally would tell the person who flipped the switch that their generator changed state when the command never left the process. """ - coordinator, entity = _adopted_switch(hass) + coordinator, entity = await _live_adopted_switch(hass, registered_panel) coordinator.client.set_adopted_property = AsyncMock( return_value=PublishOutcome( state=PublishState.FAILED, @@ -570,9 +550,11 @@ async def test_an_adopted_control_raises_when_the_command_was_not_delivered(hass coordinator.async_request_refresh.assert_not_awaited() -async def test_an_adopted_control_translates_the_librarys_refusal(hass: HomeAssistant) -> None: +async def test_an_adopted_control_translates_the_librarys_refusal( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: """A refusal reaches the caller in the user's language, like a curated one.""" - coordinator, entity = _adopted_switch(hass) + coordinator, entity = await _live_adopted_switch(hass, registered_panel) coordinator.client.set_adopted_property = AsyncMock( side_effect=SpanPanelServerError("No settable adopted property relay/enabled on device 'generator-1'") ) @@ -588,24 +570,198 @@ async def test_an_adopted_control_translates_the_librarys_refusal(hass: HomeAssi coordinator.async_request_refresh.assert_not_awaited() -async def test_a_number_publishes_an_integer_where_the_declaration_says_integer(hass: HomeAssistant) -> None: - """`5`, never `5.0`: a float literal is outside the declared datatype.""" - declaration = _property( - node_id="generator", property_id="setpoint", datatype="integer", fmt="0:100:5", settable=True, unit=None +# -- An adopted control's errors name its device as the device list does ---- + + +def _refused() -> AsyncMock: + """Return a write the library refuses, which never published anything.""" + return AsyncMock( + side_effect=SpanPanelServerError("No settable adopted property relay/enabled on device 'generator-1'") ) + + +def _not_delivered() -> AsyncMock: + """Return a write resolved to an address and never handed to the broker.""" + return AsyncMock( + return_value=PublishOutcome( + state=PublishState.FAILED, + topic=None, + value="true", + detail="broker not connected; refused rather than queued", + ) + ) + + +BOTH_WAYS_A_WRITE_FAILS = pytest.mark.parametrize( + ("failing_write", "translation_key"), + [(_refused, "adopted_control_failed"), (_not_delivered, "adopted_control_not_delivered")], + ids=["refused", "not-delivered"], +) + + +def _rename_generator(hass: HomeAssistant, entry_id: str, name: str) -> None: + """Rename the generator's card in Home Assistant, as the user does from its device page.""" + registry = dr.async_get(hass) + identifier = resolve_identifier(registry, PANEL_SERIAL, _device(), config_entry_id=entry_id) + card = registry.async_get_device_by_identifier((DOMAIN, identifier), entry_id) + assert card is not None, "the generator has no card to rename" + registry.async_update_device(card.id, name_by_user=name) + + +def _registered_generator( + hass: HomeAssistant, + registered_panel: tuple[str, str], + declaration: AdoptedProperty, + *, + renamed_to: str | None = None, +) -> tuple[ConfigEntry, SpanPanelSnapshot, MagicMock]: + """Register the card of a generator declaring one property, as setup registers it. + + Returns its entry, a snapshot carrying it, and a coordinator holding that + snapshot. `renamed_to` renames the generator after its card is registered + and before any control is set up, which is how a restart after a rename + finds it. + """ + entry_id, panel_device_id = registered_panel + entry = hass.config_entries.async_get_entry(entry_id) + assert entry is not None snapshot = _snapshot(_device(properties=(declaration,))) + async_register_adopted_devices(hass, entry_id, snapshot, panel_device_id=panel_device_id) + if renamed_to is not None: + _rename_generator(hass, entry_id, renamed_to) coordinator = MagicMock(data=snapshot) - coordinator.client.set_adopted_property = AsyncMock() coordinator.async_request_refresh = AsyncMock() + return entry, snapshot, coordinator + + +async def _enabled_and_added(hass: HomeAssistant, entry: ConfigEntry, domain: str, entity: AdoptedControl) -> None: + """Enable an adopted control's row, as its user does, and add it through a real platform. + Added because the name its errors carry is the one Core holds: a platform + gives the entity its `device_entry` as it adds it, and Core replaces it as + the device is renamed. Enabled first because every adopted entity registers + disabled, and a disabled entity is never added -- nor operated. + """ + assert entity.unique_id is not None + er.async_get(hass).async_get_or_create(domain, DOMAIN, entity.unique_id, config_entry=entry, disabled_by=None) + await add_through_platform(hass, entry, domain, entity) + + +async def _live_adopted_switch( + hass: HomeAssistant, registered_panel: tuple[str, str], *, renamed_to: str | None = None +) -> tuple[MagicMock, AdoptedSwitch]: + """One adopted switch, added to Home Assistant the way setup adds it, and its coordinator.""" + declaration = _property(node_id="relay", property_id="enabled", datatype="boolean", unit=None, settable=True) + entry, snapshot, coordinator = _registered_generator(hass, registered_panel, declaration, renamed_to=renamed_to) + (entity,) = create_adopted_switches( + coordinator, + snapshot, + dr.async_get(hass), + config_entry_id=entry.entry_id, + panel_device_id=registered_panel[1], + overlay=CurationOverlay.empty(), + ) + await _enabled_and_added(hass, entry, "switch", entity) + return coordinator, entity + + +async def _live_adopted_number( + hass: HomeAssistant, registered_panel: tuple[str, str], declaration: AdoptedProperty +) -> tuple[MagicMock, AdoptedNumber]: + """One adopted number for `declaration`, added the way setup adds it, and its coordinator.""" + entry, snapshot, coordinator = _registered_generator(hass, registered_panel, declaration) (entity,) = create_adopted_numbers( coordinator, snapshot, dr.async_get(hass), - config_entry_id=ENTRY_ID, - panel_device_id="panel-device-id", + config_entry_id=entry.entry_id, + panel_device_id=registered_panel[1], overlay=CurationOverlay.empty(), ) + await _enabled_and_added(hass, entry, "number", entity) + return coordinator, entity + + +async def _device_named_by_failed_write( + entity: AdoptedSwitch, coordinator: MagicMock, failing_write: Callable[[], AsyncMock], translation_key: str +) -> str: + """Operate the switch through a write that fails, and return the device its error names.""" + coordinator.client.set_adopted_property = failing_write() + + with pytest.raises(HomeAssistantError) as raised: + await entity.async_turn_on() + + assert raised.value.translation_key == translation_key + assert raised.value.translation_placeholders is not None + return raised.value.translation_placeholders["device"] + + +@BOTH_WAYS_A_WRITE_FAILS +async def test_an_adopted_controls_error_names_the_device_as_the_user_renamed_it( + hass: HomeAssistant, + registered_panel: tuple[str, str], + failing_write: Callable[[], AsyncMock], + translation_key: str, +) -> None: + """The user's device list shows the name they gave the generator, not the panel's. + + An error naming a device the user cannot find in that list is an error they + cannot act on, and after a rename the panel's own name is not in it. + """ + coordinator, entity = await _live_adopted_switch(hass, registered_panel, renamed_to="Shed Generator") + + assert await _device_named_by_failed_write(entity, coordinator, failing_write, translation_key) == ( + "Shed Generator" + ) + + +@BOTH_WAYS_A_WRITE_FAILS +async def test_an_adopted_controls_error_names_a_device_nobody_renamed_by_its_label( + hass: HomeAssistant, + registered_panel: tuple[str, str], + failing_write: Callable[[], AsyncMock], + translation_key: str, +) -> None: + """With no rename, the device list shows the label the card was registered under.""" + coordinator, entity = await _live_adopted_switch(hass, registered_panel) + + assert await _device_named_by_failed_write(entity, coordinator, failing_write, translation_key) == ( + "Backup Generator" + ) + + +@BOTH_WAYS_A_WRITE_FAILS +async def test_a_rename_after_setup_reaches_the_next_error( + hass: HomeAssistant, + registered_panel: tuple[str, str], + failing_write: Callable[[], AsyncMock], + translation_key: str, +) -> None: + """The name is read as the write is made, not captured as the entity is built. + + Renaming a device does not set its entities up again, so a name captured at + setup is the old one for as long as Home Assistant keeps running. + """ + coordinator, entity = await _live_adopted_switch(hass, registered_panel) + before = await _device_named_by_failed_write(entity, coordinator, failing_write, translation_key) + + _rename_generator(hass, registered_panel[0], "Shed Generator") + await hass.async_block_till_done() + after = await _device_named_by_failed_write(entity, coordinator, failing_write, translation_key) + + assert (before, after) == ("Backup Generator", "Shed Generator") + + +async def test_a_number_publishes_an_integer_where_the_declaration_says_integer( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: + """`5`, never `5.0`: a float literal is outside the declared datatype.""" + declaration = _property( + node_id="generator", property_id="setpoint", datatype="integer", fmt="0:100:5", settable=True, unit=None + ) + coordinator, entity = await _live_adopted_number(hass, registered_panel, declaration) + coordinator.client.set_adopted_property = AsyncMock() + await entity.async_set_native_value(45.0) coordinator.client.set_adopted_property.assert_awaited_once_with("generator-1", "generator", "setpoint", "45") @@ -668,6 +824,41 @@ def test_a_device_whose_whole_declaration_is_info_still_gets_a_card(hass: HomeAs assert registered.sw_version == "3.2.1" +def _registered_card_name(hass: HomeAssistant, registered_panel: tuple[str, str], device: AdoptedDevice) -> str | None: + """Register `device`'s card as setup does, and return the name it was registered under.""" + entry_id, panel_device_id = registered_panel + async_register_adopted_devices(hass, entry_id, _snapshot(device), panel_device_id=panel_device_id) + card = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, adopted_identifier(PANEL_SERIAL, device.device_id)), entry_id + ) + assert card is not None + return card.name + + +def test_a_nameless_device_whose_type_ends_in_a_dot_is_named_by_its_last_segment( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: + """A malformed `$type` from a publisher this integration does not model still names its card. + + The library skips only a device declaring no type at all, so a trailing + dot reaches the label. Its last segment was the empty string after the dot, + so Core named the new card after the panel's entry and blanked the name on + the next load. + """ + device = replace(_device(), name=None, device_type="energy.ebus.device.") + + assert _registered_card_name(hass, registered_panel, device) == "Device" + + +def test_a_nameless_device_whose_type_is_only_dots_is_named_by_its_id( + hass: HomeAssistant, registered_panel: tuple[str, str] +) -> None: + """Where the type has no segment to name the card from, its wire id does, which is never empty.""" + device = replace(_device(), name=None, device_type="...") + + assert _registered_card_name(hass, registered_panel, device) == "generator-1" + + def test_registration_freezes_the_anchor_before_any_entity_resolves_it(hass: HomeAssistant, registered_panel: tuple[str, str]) -> None: """Registering first is what makes the freeze single-valued. diff --git a/tests/test_circuit_control.py b/tests/test_circuit_control.py index d06a3fdf..01e7d1ff 100644 --- a/tests/test_circuit_control.py +++ b/tests/test_circuit_control.py @@ -16,6 +16,7 @@ ) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory +from .helpers import added_circuit_switch @pytest.fixture(autouse=True) @@ -84,9 +85,7 @@ async def test_switch_turn_on_operation(hass: HomeAssistant) -> None: name="Kitchen Outlets", relay_state="OPEN", ) - coordinator = _make_coordinator(hass, {"1": circuit}) - - switch = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") + coordinator, switch = await added_circuit_switch(hass, circuit) switch.async_write_ha_state = MagicMock() await switch.async_turn_on() @@ -102,9 +101,7 @@ async def test_switch_turn_off_operation(hass: HomeAssistant) -> None: name="Kitchen Outlets", relay_state="CLOSED", ) - coordinator = _make_coordinator(hass, {"1": circuit}) - - switch = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") + coordinator, switch = await added_circuit_switch(hass, circuit) switch.async_write_ha_state = MagicMock() await switch.async_turn_off() @@ -128,12 +125,10 @@ async def test_a_refused_relay_command_is_raised_and_leaves_the_switch_alone( name="Kitchen Outlets", relay_state="CLOSED", ) - coordinator = _make_coordinator(hass, {"1": circuit}) + coordinator, switch = await added_circuit_switch(hass, circuit) coordinator.client.set_circuit_relay = AsyncMock( side_effect=SpanPanelServerError("Circuit '1' declares its relay non-commandable") ) - - switch = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") switch.async_write_ha_state = MagicMock() with pytest.raises(HomeAssistantError) as raised: @@ -153,19 +148,17 @@ async def test_a_refused_relay_command_is_raised_and_leaves_the_switch_alone( async def test_a_refusal_names_an_unnamed_circuit_by_its_panel_positions( hass: HomeAssistant, ) -> None: - """The identifier the entity was named from, not the wire id.""" + """Its device is named by its breaker positions, not by the wire id.""" circuit = SpanCircuitSnapshotFactory.create( circuit_id="abc123", name="", relay_state="OPEN", tabs=[30, 32], ) - coordinator = _make_coordinator(hass, {"abc123": circuit}) + coordinator, switch = await added_circuit_switch(hass, circuit) coordinator.client.set_circuit_relay = AsyncMock( side_effect=SpanPanelServerError("Circuit 'abc123' declares its relay non-commandable") ) - - switch = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "abc123", "SPAN Panel") switch.async_write_ha_state = MagicMock() with pytest.raises(HomeAssistantError) as raised: diff --git a/tests/test_control_error_device_names.py b/tests/test_control_error_device_names.py new file mode 100644 index 00000000..8144b588 --- /dev/null +++ b/tests/test_control_error_device_names.py @@ -0,0 +1,425 @@ +"""A curated control's errors name its device as the user's device list does. + +A breaker switch and a priority select sit on their circuit's own device, and a +charger's lock and charge-current limit on the charger's. The user can rename +any of those devices in Home Assistant, which reloads nothing, and an error that +names the device by a name it no longer carries names one the user cannot find. +The adopted controls are held to the same in `test_adoption.py`. + +Every control here is set up by its platform's own `async_setup_entry` and added +through a real platform, because the name under test is the one Core holds: the +platform gives each entity its `device_entry` as it adds it, and Core replaces +that entry as the device is renamed. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable, Iterable +from dataclasses import dataclass, replace +from typing import Final +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.entity import Entity +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +import pytest +from pytest_homeassistant.common import MockConfigEntry, MockEntityPlatform +from span_panel_api import ControlTarget, PublishOutcome, PublishState, SpanPanelSnapshot +from span_panel_api.exceptions import SpanPanelServerError + +from custom_components.span_panel import SpanPanelRuntimeData, ensure_device_registered +from custom_components.span_panel.curation import CurationOverlay +from custom_components.span_panel.lock import SpanEvseLock, async_setup_entry as lock_setup +from custom_components.span_panel.number import SpanEvseNumber, async_setup_entry as number_setup +from custom_components.span_panel.runtime import SpanPanelConfigEntry +from custom_components.span_panel.select import ( + SpanPanelCircuitsSelect, + async_setup_entry as select_setup, +) +from custom_components.span_panel.switch import ( + SpanPanelCircuitsSwitch, + async_setup_entry as switch_setup, +) + +from .factories import ( + SpanCircuitSnapshotFactory, + SpanEvseSnapshotFactory, + SpanPanelSnapshotFactory, + pv_binding_for, +) +from .helpers import PANEL_NAME, add_panel_entry, add_through_platform +from .test_pv_device import _coordinator + +SERIAL: Final = "sp3-error-names-001" +KITCHEN: Final = "kitchen-outlets" +GARAGE: Final = "garage-feed" +ROOF: Final = "roof-array" +CHARGER: Final = "evse-garage" + + +def _panel() -> SpanPanelSnapshot: + """Return a panel with a controllable circuit, an unnamed solar one, and a charger fed by a third.""" + charger = replace( + SpanEvseSnapshotFactory.create(node_id=CHARGER, feed_circuit_id=GARAGE), + lock_control=ControlTarget( + topic=f"ebus/5/{CHARGER}/switch/lock-state/set", + device_id=CHARGER, + node_id="switch", + property_id="lock-state", + ), + lock_state_options=("LOCKED", "UNLOCKED"), + charge_current_limit_a=24, + charge_current_ceiling_a=32, + charge_current_limit_settable=True, + charge_current_limit_minimum_a=6, + charge_current_limit_maximum_a=32, + ) + circuits = ( + SpanCircuitSnapshotFactory.create( + circuit_id=KITCHEN, name="Kitchen Outlets", tabs=[2], is_user_controllable=True + ), + # At a breaker slot, which is what gives a solar circuit a breaker switch. + SpanCircuitSnapshotFactory.create( + circuit_id=ROOF, + name="", + tabs=[30, 32], + device_type="pv", + relative_position="DOWNSTREAM", + is_user_controllable=True, + ), + SpanCircuitSnapshotFactory.create( + circuit_id=GARAGE, name="Garage", tabs=[9, 11], is_user_controllable=False + ), + ) + return SpanPanelSnapshotFactory.create( + serial_number=SERIAL, + circuits={circuit.circuit_id: circuit for circuit in circuits}, + evse={CHARGER: charger}, + ) + + +SNAPSHOT: Final = _panel() + + +async def _turn_on(entity: Entity) -> None: + assert isinstance(entity, SpanPanelCircuitsSwitch) + await entity.async_turn_on() + + +async def _select_never(entity: Entity) -> None: + assert isinstance(entity, SpanPanelCircuitsSelect) + await entity.async_select_option("never") + + +async def _lock(entity: Entity) -> None: + assert isinstance(entity, SpanEvseLock) + await entity.async_lock() + + +async def _limit_to_16_a(entity: Entity) -> None: + assert isinstance(entity, SpanEvseNumber) + await entity.async_set_native_value(16.0) + + +@dataclass(frozen=True) +class _Family: + """One kind of control: its platform, how it is operated, and what its errors are keyed and named by.""" + + domain: str + setup: Callable[ + [HomeAssistant, SpanPanelConfigEntry, AddConfigEntryEntitiesCallback], Awaitable[None] + ] + operate: Callable[[Entity], Awaitable[None]] + client_write: str + placeholder: str + failed_key: str + not_delivered_key: str + shown_name: str + """What the user's device list calls the control's device before anyone renames it.""" + entity_type: type[Entity] + subject: str + """The circuit or charger, by wire id, whose control this family's test operates.""" + + +def _subject_of(entity: Entity) -> str | None: + """Return the circuit or charger, by wire id, that a control operates.""" + if isinstance(entity, SpanPanelCircuitsSwitch): + return entity._circuit_id + if isinstance(entity, SpanPanelCircuitsSelect): + return entity.id + if isinstance(entity, SpanEvseLock | SpanEvseNumber): + return entity._evse_id + return None + + +BREAKER: Final = _Family( + domain="switch", + setup=switch_setup, + operate=_turn_on, + client_write="set_circuit_relay", + placeholder="circuit", + failed_key="circuit_relay_failed", + not_delivered_key="circuit_relay_not_delivered", + shown_name="Kitchen Outlets", + entity_type=SpanPanelCircuitsSwitch, + subject=KITCHEN, +) +PRIORITY: Final = _Family( + domain="select", + setup=select_setup, + operate=_select_never, + client_write="set_circuit_priority", + placeholder="circuit", + failed_key="circuit_priority_failed", + not_delivered_key="circuit_priority_not_delivered", + shown_name="Kitchen Outlets", + entity_type=SpanPanelCircuitsSelect, + subject=KITCHEN, +) +CHARGER_LOCK: Final = _Family( + domain="lock", + setup=lock_setup, + operate=_lock, + client_write="set_evse_lock", + placeholder="charger", + failed_key="evse_lock_failed", + not_delivered_key="evse_lock_not_delivered", + shown_name="SPAN Panel SPAN Drive (Garage)", + entity_type=SpanEvseLock, + subject=CHARGER, +) +CHARGE_LIMIT: Final = _Family( + domain="number", + setup=number_setup, + operate=_limit_to_16_a, + client_write="set_evse_charge_limit", + placeholder="charger", + failed_key="evse_charge_limit_failed", + not_delivered_key="evse_charge_limit_not_delivered", + shown_name="SPAN Panel SPAN Drive (Garage)", + entity_type=SpanEvseNumber, + subject=CHARGER, +) + +EVERY_FAMILY_BOTH_WAYS: Final = pytest.mark.parametrize( + ("family", "resolved"), + [ + pytest.param( + family, resolved, id=f"{family.domain}-{'not-delivered' if resolved else 'refused'}" + ) + for family in (BREAKER, PRIORITY, CHARGER_LOCK, CHARGE_LIMIT) + for resolved in (False, True) + ], +) +"""Each family, through a write the library refuses and one never handed to the broker. + +`resolved` is True for the second: that write resolved an address and was never +delivered, where a refused one never resolved one. +""" + +BOTH_CIRCUIT_CONTROLS: Final = pytest.mark.parametrize( + "family", [BREAKER, PRIORITY], ids=["switch", "select"] +) +"""The two controls that name a circuit rather than a device of their own.""" + + +@dataclass +class _Live: + """One control added to Home Assistant, the coordinator its client hangs off, and its platform.""" + + control: Entity + coordinator: MagicMock + platform: MockEntityPlatform + + +async def _set_up(hass: HomeAssistant, entry: MockConfigEntry, family: _Family) -> _Live: + """Set the family's platform up as a load does, and add its control through a real platform. + + Only the control under test is added. The platform builds the others it + always builds -- the control lock's switch, the solar circuit's controls -- + and none of them bears on what this control's errors say. + """ + coordinator = _coordinator(hass, entry, SNAPSHOT) + coordinator.client = MagicMock() + entry.runtime_data = SpanPanelRuntimeData( + coordinator=coordinator, + panel_device_id=await ensure_device_registered(hass, entry, SNAPSHOT, PANEL_NAME), + curation=CurationOverlay.empty(), + pv_binding=pv_binding_for(SNAPSHOT), + setup_snapshot=SNAPSHOT, + ) + built: list[Entity] = [] + + def add_entities( + new_entities: Iterable[Entity], + update_before_add: bool = False, + *, + config_subentry_id: str | None = None, + ) -> None: + built.extend(new_entities) + + await family.setup(hass, entry, add_entities) + (control,) = [ + entity + for entity in built + if isinstance(entity, family.entity_type) and _subject_of(entity) == family.subject + ] + platform = await add_through_platform(hass, entry, family.domain, control) + return _Live(control, coordinator, platform) + + +def _rename(hass: HomeAssistant, live: _Live, name: str) -> None: + """Rename the control's device in Home Assistant, as the user does from its device page. + + A circuit's device is a child device, which the registry renames through + its own call; a charger's is a sub-device like any other. + """ + device = live.control.device_entry + assert device is not None + registry = dr.async_get(hass) + if isinstance(device, dr.ChildDeviceEntry): + registry.async_update_child_device(device.id, name_by_user=name) + else: + registry.async_update_device(device.id, name_by_user=name) + + +def _deliver(live: _Live, snapshot: SpanPanelSnapshot) -> None: + """Hand the control a snapshot the way the coordinator does, without the reload it may ask for.""" + assert isinstance(live.control, SpanPanelCircuitsSwitch | SpanPanelCircuitsSelect) + live.coordinator.data = snapshot + live.control._handle_coordinator_update() + + +def _failing_write(resolved: bool) -> AsyncMock: + """Return a write the library refuses, or one resolved and never handed to the broker.""" + if not resolved: + return AsyncMock( + side_effect=SpanPanelServerError("the panel declares this not commandable") + ) + return AsyncMock( + return_value=PublishOutcome( + state=PublishState.FAILED, + topic=None, + value="", + detail="broker not connected; refused rather than queued", + ) + ) + + +async def _named_by_failed_write(live: _Live, family: _Family, *, resolved: bool) -> str: + """Operate the control through a write that fails, and return the device its error names.""" + setattr(live.coordinator.client, family.client_write, _failing_write(resolved)) + + with pytest.raises(HomeAssistantError) as raised: + await family.operate(live.control) + + assert raised.value.translation_key == ( + family.not_delivered_key if resolved else family.failed_key + ) + placeholders = raised.value.translation_placeholders + assert placeholders is not None + return placeholders[family.placeholder] + + +@EVERY_FAMILY_BOTH_WAYS +async def test_an_error_names_the_device_as_the_user_renamed_it( + hass: HomeAssistant, family: _Family, resolved: bool +) -> None: + """The device was renamed before this setup, as a restart after a rename finds it.""" + entry = add_panel_entry(hass, "entry-renamed", SERIAL) + first = await _set_up(hass, entry, family) + _rename(hass, first, "Workshop Bench") + await first.platform.async_reset() + + live = await _set_up(hass, entry, family) + + assert await _named_by_failed_write(live, family, resolved=resolved) == "Workshop Bench" + + +@EVERY_FAMILY_BOTH_WAYS +async def test_a_rename_after_setup_reaches_the_next_error( + hass: HomeAssistant, family: _Family, resolved: bool +) -> None: + """Renaming a device sets none of its entities up again, so a name captured at setup stays old.""" + entry = add_panel_entry(hass, "entry-renamed-live", SERIAL) + live = await _set_up(hass, entry, family) + before = await _named_by_failed_write(live, family, resolved=resolved) + + _rename(hass, live, "Workshop Bench") + await hass.async_block_till_done() + after = await _named_by_failed_write(live, family, resolved=resolved) + + assert (before, after) == (family.shown_name, "Workshop Bench") + + +@EVERY_FAMILY_BOTH_WAYS +async def test_a_device_nobody_renamed_keeps_its_name( + hass: HomeAssistant, family: _Family, resolved: bool +) -> None: + """With no rename the error names the device by the name it was registered under.""" + entry = add_panel_entry(hass, "entry-not-renamed", SERIAL) + live = await _set_up(hass, entry, family) + + assert await _named_by_failed_write(live, family, resolved=resolved) == family.shown_name + + +@BOTH_CIRCUIT_CONTROLS +async def test_a_panel_rename_not_yet_reloaded_keeps_the_name_the_device_list_shows( + hass: HomeAssistant, family: _Family +) -> None: + """A circuit renamed in the SPAN app renames its device only on the reload that follows. + + Until that reload has run, the device and the device list still carry the + old name, so the error does too. Naming the panel's new name there would + name a device the user cannot yet find. Set up a second time, as a restart + finds an existing entity, so the update below is read as the rename it is + and asks for the reload. + """ + entry = add_panel_entry(hass, "entry-panel-rename", SERIAL) + first = await _set_up(hass, entry, family) + await first.platform.async_reset() + live = await _set_up(hass, entry, family) + renamed = replace(SNAPSHOT.circuits[KITCHEN], name="Kitchen Island") + + _deliver(live, replace(SNAPSHOT, circuits={**SNAPSHOT.circuits, KITCHEN: renamed})) + + live.coordinator.request_reload.assert_called_once() + assert await _named_by_failed_write(live, family, resolved=False) == "Kitchen Outlets" + + +@BOTH_CIRCUIT_CONTROLS +async def test_a_circuit_gone_from_the_snapshot_is_named_by_its_device( + hass: HomeAssistant, family: _Family +) -> None: + """A circuit can drop out of the snapshot between a command and its failure. + + The panel's label for it then has nothing to read but its wire id, which + names nothing the user can find. Its device is still there, under the name + the device list shows. + """ + entry = add_panel_entry(hass, "entry-circuit-gone", SERIAL) + live = await _set_up(hass, entry, family) + remaining = {cid: circuit for cid, circuit in SNAPSHOT.circuits.items() if cid != KITCHEN} + + _deliver(live, replace(SNAPSHOT, circuits=remaining)) + + assert await _named_by_failed_write(live, family, resolved=False) == "Kitchen Outlets" + + +@pytest.mark.parametrize("resolved", [False, True], ids=["refused", "not-delivered"]) +async def test_an_unnamed_solar_circuit_is_named_as_its_device_is( + hass: HomeAssistant, resolved: bool +) -> None: + """Its device is "Solar", the name its entities have carried since v1, not its breaker positions. + + An unnamed solar circuit is the one case where the panel's label for a + circuit and its device's name differ, so it is the case that shows which + of the two an error reads. + """ + solar_breaker = replace(BREAKER, subject=ROOF) + entry = add_panel_entry(hass, "entry-solar", SERIAL) + live = await _set_up(hass, entry, solar_breaker) + + assert await _named_by_failed_write(live, solar_breaker, resolved=resolved) == "Solar" diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py index 494da374..1c101eed 100644 --- a/tests/test_control_gate.py +++ b/tests/test_control_gate.py @@ -1001,27 +1001,17 @@ async def test_a_refused_relay_leaves_the_switch_where_it_was( Nothing changed on the panel, so no coordinator update is coming to correct an optimistic write — it would simply stay wrong. """ - from custom_components.span_panel.switch import SpanPanelCircuitsSwitch - - from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory + from .factories import SpanCircuitSnapshotFactory + from .helpers import added_circuit_switch circuit = SpanCircuitSnapshotFactory.create( circuit_id="1", name="Kitchen", relay_state="OPEN", is_user_controllable=True ) - coordinator = MagicMock() - coordinator.hass = hass - coordinator.data = SpanPanelSnapshotFactory.create(circuits={"1": circuit}) - coordinator.config_entry = MagicMock() - coordinator.config_entry.options = {} - coordinator.config_entry.title = "SPAN Panel" - coordinator.config_entry.data = {} - coordinator.client = MagicMock() + coordinator, entity = await added_circuit_switch(hass, circuit) coordinator.client.set_circuit_relay = AsyncMock( side_effect=ServiceValidationError("refused") ) - entity = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") - entity.hass = hass entity.async_write_ha_state = MagicMock() before = entity.is_on @@ -1043,21 +1033,13 @@ async def test_an_undelivered_relay_command_does_not_move_the_switch( later -- and it is worded as the different fact it is: this one resolved an address and was never handed to the broker. """ - from custom_components.span_panel.switch import SpanPanelCircuitsSwitch - - from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory + from .factories import SpanCircuitSnapshotFactory + from .helpers import added_circuit_switch circuit = SpanCircuitSnapshotFactory.create( circuit_id="1", name="Kitchen", relay_state="OPEN", is_user_controllable=True ) - coordinator = MagicMock() - coordinator.hass = hass - coordinator.data = SpanPanelSnapshotFactory.create(circuits={"1": circuit}) - coordinator.config_entry = MagicMock() - coordinator.config_entry.options = {} - coordinator.config_entry.title = "SPAN Panel" - coordinator.config_entry.data = {} - coordinator.client = MagicMock() + coordinator, entity = await added_circuit_switch(hass, circuit) coordinator.client.set_circuit_relay = AsyncMock( return_value=PublishOutcome( state=PublishState.FAILED, @@ -1067,8 +1049,6 @@ async def test_an_undelivered_relay_command_does_not_move_the_switch( ) ) - entity = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") - entity.hass = hass entity.async_write_ha_state = MagicMock() before = entity.is_on @@ -1096,21 +1076,13 @@ async def test_a_handed_over_relay_command_still_shows_the_requested_state( already have been acted on, so both keep the optimistic write that `FAILED` and a refusal are denied. """ - from custom_components.span_panel.switch import SpanPanelCircuitsSwitch - - from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory + from .factories import SpanCircuitSnapshotFactory + from .helpers import added_circuit_switch circuit = SpanCircuitSnapshotFactory.create( circuit_id="1", name="Kitchen", relay_state="OPEN", is_user_controllable=True ) - coordinator = MagicMock() - coordinator.hass = hass - coordinator.data = SpanPanelSnapshotFactory.create(circuits={"1": circuit}) - coordinator.config_entry = MagicMock() - coordinator.config_entry.options = {} - coordinator.config_entry.title = "SPAN Panel" - coordinator.config_entry.data = {} - coordinator.client = MagicMock() + coordinator, entity = await added_circuit_switch(hass, circuit) coordinator.client.set_circuit_relay = AsyncMock( return_value=PublishOutcome( state=state, @@ -1121,8 +1093,6 @@ async def test_a_handed_over_relay_command_still_shows_the_requested_state( ) ) - entity = SpanPanelCircuitsSwitch(coordinator, coordinator.data, "1", "SPAN Panel") - entity.hass = hass entity.async_write_ha_state = MagicMock() await entity.async_turn_on() diff --git a/tests/test_evse_charge_limit.py b/tests/test_evse_charge_limit.py index 3f2ace71..ff7a6cd2 100644 --- a/tests/test_evse_charge_limit.py +++ b/tests/test_evse_charge_limit.py @@ -69,7 +69,7 @@ ) from .captures_replay import HOMIE_PREFIX, replay from .factories import pv_binding_for -from .helpers import register_panel_device +from .helpers import add_through_platform, register_panel_device EVSE = "evse" EVSE_2 = "evse-2" @@ -286,6 +286,19 @@ def _for(created: Sequence[SpanEvseNumber], tree: dict[str, dict[str, str]], dev return matches[0] +async def _added_for( + hass: HomeAssistant, created: Sequence[SpanEvseNumber], tree: dict[str, dict[str, str]], device_id: str +) -> SpanEvseNumber: + """Return the number belonging to one charger, added through a real platform so it can be operated. + + A charge-limit error names the charger by its device, which Core links only + as it adds the number. + """ + entity = _for(created, tree, device_id) + await add_through_platform(hass, entity.coordinator.config_entry, "number", entity) + return entity + + def _refreshed(entity: SpanEvseNumber, snapshot: SpanPanelSnapshot | None) -> SpanEvseNumber: """Push a new snapshot through the coordinator update the way HA does.""" entity.coordinator.data = snapshot @@ -812,7 +825,7 @@ async def test_the_write_reaches_the_wire_as_one_publish(hass: HomeAssistant) -> tree = schema_one_tree() client, bridge = _live_client() created = await _created(hass, schema_one_snapshot(tree), client) - entity = _for(created, tree, EVSE) + entity = await _added_for(hass, created, tree, EVSE) asked = _published(tree, EVSE, CEILING_TOPIC) - 8 await entity.async_set_native_value(float(asked)) @@ -828,9 +841,10 @@ async def test_the_write_goes_to_the_charger_the_entity_belongs_to(hass: HomeAss tree = schema_one_tree() client, bridge = _live_client() created = await _created(hass, schema_one_snapshot(tree), client) + entity = await _added_for(hass, created, tree, EVSE_2) asked = _published(tree, EVSE_2, CEILING_TOPIC) - 8 - await _for(created, tree, EVSE_2).async_set_native_value(float(asked)) + await entity.async_set_native_value(float(asked)) bridge.publish.assert_called_once_with( f"ebus/5/{EVSE_2}/config/user-max-charge-current/set", str(asked) @@ -847,9 +861,10 @@ async def test_a_fractional_request_truncates_downward(hass: HomeAssistant) -> N tree = schema_one_tree() client, bridge = _live_client() created = await _created(hass, schema_one_snapshot(tree), client) + entity = await _added_for(hass, created, tree, EVSE) whole = _published(tree, EVSE, CEILING_TOPIC) - 8 - await _for(created, tree, EVSE).async_set_native_value(whole + 0.7) + await entity.async_set_native_value(whole + 0.7) bridge.publish.assert_called_once_with( f"ebus/5/{EVSE}/config/user-max-charge-current/set", str(whole) @@ -869,10 +884,11 @@ async def test_a_value_above_the_ceiling_is_refused_before_it_reaches_the_wire( tree = schema_one_tree() client, bridge = _live_client() created = await _created(hass, schema_one_snapshot(tree), client) + entity = await _added_for(hass, created, tree, EVSE) over = _published(tree, EVSE, CEILING_TOPIC) + 1 with pytest.raises(HomeAssistantError) as raised: - await _for(created, tree, EVSE).async_set_native_value(float(over)) + await entity.async_set_native_value(float(over)) assert raised.value.translation_key == "evse_charge_limit_failed" bridge.publish.assert_not_called() @@ -893,7 +909,7 @@ async def test_a_command_the_transport_never_handed_over_is_reported( client, bridge = _live_client() bridge.publish.return_value = None created = await _created(hass, schema_one_snapshot(tree), client) - entity = _for(created, tree, EVSE) + entity = await _added_for(hass, created, tree, EVSE) asked = _published(tree, EVSE, CEILING_TOPIC) - 8 with pytest.raises(HomeAssistantError) as raised: @@ -917,7 +933,7 @@ async def test_a_failure_names_the_charger_the_user_sees(hass: HomeAssistant) -> client, bridge = _live_client() bridge.publish.return_value = None created = await _created(hass, schema_one_snapshot(tree), client) - entity = _for(created, tree, EVSE) + entity = await _added_for(hass, created, tree, EVSE) asked = _published(tree, EVSE, CEILING_TOPIC) - 8 with pytest.raises(HomeAssistantError) as raised: diff --git a/tests/test_evse_lock.py b/tests/test_evse_lock.py index b2d45df8..c3ac61eb 100644 --- a/tests/test_evse_lock.py +++ b/tests/test_evse_lock.py @@ -23,6 +23,7 @@ from custom_components.span_panel.lock import SpanEvseLock, async_setup_entry from .factories import SpanEvseSnapshotFactory, SpanPanelSnapshotFactory +from .helpers import add_through_platform from .test_evse_charge_limit import _coordinator SERIAL: Final = "sp3-lock-001" @@ -113,7 +114,7 @@ async def test_a_command_goes_through_the_librarys_lock_control( ) ) (lock,) = await _created(hass, _snapshot(), client) - lock.hass = hass + await add_through_platform(hass, lock.coordinator.config_entry, "lock", lock) await getattr(lock, method)() diff --git a/tests/test_select.py b/tests/test_select.py index 7878ebb1..777985f4 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -6,7 +6,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError import pytest -from span_panel_api import PublishOutcome, PublishState +from span_panel_api import PublishOutcome, PublishState, SpanPanelSnapshot from span_panel_api.exceptions import SpanPanelServerError from custom_components.span_panel.const import CircuitPriority @@ -18,15 +18,15 @@ ) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory +from .helpers import PANEL_NAME, add_through_platform, coordinator_stand_in -def _make_coordinator_with_circuit( - hass: HomeAssistant, +def _snapshot_with_circuit( circuit_id: str = "id", circuit_name: str = "name", priority: str = "SOC_THRESHOLD", -) -> MagicMock: - """Build a mock coordinator whose .data contains a single circuit.""" +) -> SpanPanelSnapshot: + """Build a snapshot holding a single controllable circuit.""" circuit = SpanCircuitSnapshotFactory.create( circuit_id=circuit_id, name=circuit_name, @@ -38,14 +38,19 @@ def _make_coordinator_with_circuit( priority=priority, is_user_controllable=True, ) + return SpanPanelSnapshotFactory.create(circuits={circuit_id: circuit}) - snapshot = SpanPanelSnapshotFactory.create( - circuits={circuit_id: circuit}, - ) +def _make_coordinator_with_circuit( + hass: HomeAssistant, + circuit_id: str = "id", + circuit_name: str = "name", + priority: str = "SOC_THRESHOLD", +) -> MagicMock: + """Build a mock coordinator whose .data contains a single circuit.""" coordinator = MagicMock() coordinator.hass = hass - coordinator.data = snapshot + coordinator.data = _snapshot_with_circuit(circuit_id, circuit_name, priority) coordinator.config_entry = MagicMock() coordinator.config_entry.title = "SPAN Panel" coordinator.config_entry.data = {} @@ -53,6 +58,20 @@ def _make_coordinator_with_circuit( return coordinator +async def _added_select(hass: HomeAssistant) -> tuple[MagicMock, SpanPanelCircuitsSelect]: + """Return the circuit's priority select, added through a real platform, and its coordinator. + + Added because a priority error names the circuit by its device, which Core + links only as it adds the select. + """ + snapshot = _snapshot_with_circuit() + coordinator, entry = coordinator_stand_in(hass, snapshot) + coordinator.async_request_refresh = AsyncMock() + select = SpanPanelCircuitsSelect(coordinator, CIRCUIT_PRIORITY_DESCRIPTION, snapshot, "id", PANEL_NAME) + await add_through_platform(hass, entry, "select", select) + return coordinator, select + + def test_select_init_missing_circuit() -> None: """Test that initializing with a missing circuit_id raises ValueError.""" # Coordinator with no circuits @@ -117,19 +136,12 @@ async def test_async_select_option_refusal_is_raised_at_the_caller(hass: HomeAss passed through rather than diagnosed here, and the entity contributes the name the user knows the circuit by. """ - coordinator = _make_coordinator_with_circuit(hass) - circuit = coordinator.data.circuits["id"] - - select = SpanPanelCircuitsSelect(coordinator, CIRCUIT_PRIORITY_DESCRIPTION, coordinator.data, "id", "Test Device") - select.coordinator = coordinator - select.hass = MagicMock() - + coordinator, select = await _added_select(hass) coordinator.client = AsyncMock() coordinator.client.set_circuit_priority = AsyncMock( side_effect=SpanPanelServerError("Circuit 'id' declares its shed priority not settable") ) - select._get_circuit = MagicMock(return_value=circuit) with pytest.raises(HomeAssistantError) as raised: await select.async_select_option(CircuitPriority.SOC_THRESHOLD.value) @@ -144,13 +156,7 @@ async def test_async_select_option_refusal_is_raised_at_the_caller(hass: HomeAss @pytest.mark.asyncio async def test_async_select_option_undelivered_is_raised_at_the_caller(hass: HomeAssistant) -> None: """A `FAILED` outcome is the promise this change will not arrive later.""" - coordinator = _make_coordinator_with_circuit(hass) - circuit = coordinator.data.circuits["id"] - - select = SpanPanelCircuitsSelect(coordinator, CIRCUIT_PRIORITY_DESCRIPTION, coordinator.data, "id", "Test Device") - select.coordinator = coordinator - select.hass = MagicMock() - + coordinator, select = await _added_select(hass) coordinator.client = AsyncMock() coordinator.client.set_circuit_priority = AsyncMock( return_value=PublishOutcome( @@ -158,7 +164,6 @@ async def test_async_select_option_undelivered_is_raised_at_the_caller(hass: Hom ) ) - select._get_circuit = MagicMock(return_value=circuit) with pytest.raises(HomeAssistantError) as raised: await select.async_select_option(CircuitPriority.SOC_THRESHOLD.value) @@ -172,22 +177,9 @@ async def test_async_select_option_undelivered_is_raised_at_the_caller(hass: Hom @pytest.mark.asyncio async def test_async_select_option_success_refreshes_coordinator(hass: HomeAssistant) -> None: """Successful priority changes should refresh coordinator data.""" - coordinator = _make_coordinator_with_circuit(hass) - coordinator.async_request_refresh = AsyncMock() - - with patch( - "custom_components.span_panel.select.er.async_get" - ) as mock_async_get: - registry = MagicMock() - registry.async_get_entity_id.return_value = None - mock_async_get.return_value = registry - select = SpanPanelCircuitsSelect( - coordinator, CIRCUIT_PRIORITY_DESCRIPTION, coordinator.data, "id", "SPAN Panel" - ) - + coordinator, select = await _added_select(hass) coordinator.client = MagicMock() coordinator.client.set_circuit_priority = AsyncMock() - select.hass = MagicMock() await select.async_select_option(CircuitPriority.SOC_THRESHOLD.value)