From 48546c77b5e9c8e770c789ac13b1ad98bbcfce17 Mon Sep 17 00:00:00 2001 From: Diogo Gomes Date: Tue, 25 Apr 2023 08:49:58 +0100 Subject: [PATCH] Follow the unavailability of the source sensor (#91975) --- homeassistant/components/integration/sensor.py | 9 +++++++++ tests/components/integration/test_sensor.py | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index 54e50b7b1de..d199b8808d3 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -197,6 +197,15 @@ class IntegrationSensor(RestoreEntity, SensorEntity): old_state: State | None = event.data.get("old_state") new_state: State | None = event.data.get("new_state") + 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 + if new_state is None or new_state.state in ( STATE_UNKNOWN, STATE_UNAVAILABLE, diff --git a/tests/components/integration/test_sensor.py b/tests/components/integration/test_sensor.py index dd867b58166..93da55c51a4 100644 --- a/tests/components/integration/test_sensor.py +++ b/tests/components/integration/test_sensor.py @@ -401,13 +401,20 @@ async def test_units(hass: HomeAssistant) -> None: # When source state goes to None / Unknown, expect an early exit without # changes to the state or unit_of_measurement - hass.states.async_set(entity_id, STATE_UNAVAILABLE, None) + hass.states.async_set(entity_id, None, None) await hass.async_block_till_done() new_state = hass.states.get("sensor.integration") assert state == new_state assert state.attributes.get("unit_of_measurement") == UnitOfEnergy.WATT_HOUR + # When source state goes to unavailable, expect sensor to also become unavailable + hass.states.async_set(entity_id, STATE_UNAVAILABLE, None) + await hass.async_block_till_done() + + new_state = hass.states.get("sensor.integration") + assert new_state.state == STATE_UNAVAILABLE + async def test_device_class(hass: HomeAssistant) -> None: """Test integration sensor units using a power source."""