From 86fe0c96830817d27e3b0180a7cc2ab7e23b73c1 Mon Sep 17 00:00:00 2001 From: Diogo Gomes Date: Mon, 10 Apr 2023 17:37:45 +0100 Subject: [PATCH] Track availability of source sensor in utility meter (#91035) * track availability of source sensor * address review comments --- homeassistant/components/utility_meter/sensor.py | 9 +++++++++ tests/components/utility_meter/test_sensor.py | 9 ++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/utility_meter/sensor.py b/homeassistant/components/utility_meter/sensor.py index b7be0bdcfc0..050e801f056 100644 --- a/homeassistant/components/utility_meter/sensor.py +++ b/homeassistant/components/utility_meter/sensor.py @@ -423,6 +423,15 @@ class UtilityMeterSensor(RestoreSensor): @callback def async_reading(self, event: Event): """Handle the sensor state changes.""" + if ( + source_state := self.hass.states.get(self._sensor_source_id) + ) is None or source_state.state == STATE_UNAVAILABLE: + self._attr_available = False + self.async_write_ha_state() + return + + self._attr_available = True + old_state: State | None = event.data.get("old_state") new_state: State = event.data.get("new_state") # type: ignore[assignment] # a state change event always has a new state diff --git a/tests/components/utility_meter/test_sensor.py b/tests/components/utility_meter/test_sensor.py index 8dcff8438ad..65892ae376a 100644 --- a/tests/components/utility_meter/test_sensor.py +++ b/tests/components/utility_meter/test_sensor.py @@ -217,20 +217,19 @@ async def test_state(hass: HomeAssistant, yaml_config, config_entry_config) -> N entity_id, "*", {ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR} ) await hass.async_block_till_done() - state = hass.states.get("sensor.energy_bill_midpeak") + state = hass.states.get("sensor.energy_bill_offpeak") assert state is not None - assert state.state == "0.123" + assert state.state == "3" # test unavailable source hass.states.async_set( entity_id, STATE_UNAVAILABLE, - {ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR}, ) await hass.async_block_till_done() - state = hass.states.get("sensor.energy_bill_midpeak") + state = hass.states.get("sensor.energy_bill_offpeak") assert state is not None - assert state.state == "0.123" + assert state.state == "unavailable" @pytest.mark.parametrize(