From e7fd24eadee037e8d2bb2199251dc03341ceadc3 Mon Sep 17 00:00:00 2001 From: Diogo Gomes Date: Tue, 7 Sep 2021 07:12:54 +0100 Subject: [PATCH] Integration Sensor Initial State (#55875) * initial state is UNAVAILABLE * update tests --- homeassistant/components/integration/sensor.py | 11 ++++++++--- tests/components/integration/test_sensor.py | 7 +++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index cd3e376b792..d36e2da54c1 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -106,7 +106,7 @@ class IntegrationSensor(RestoreEntity, SensorEntity): """Initialize the integration sensor.""" self._sensor_source_id = source_entity self._round_digits = round_digits - self._state = 0 + self._state = STATE_UNAVAILABLE self._method = integration_method self._name = name if name is not None else f"{source_entity} integral" @@ -187,7 +187,10 @@ class IntegrationSensor(RestoreEntity, SensorEntity): except AssertionError as err: _LOGGER.error("Could not calculate integral: %s", err) else: - self._state += integral + if isinstance(self._state, Decimal): + self._state += integral + else: + self._state = integral self.async_write_ha_state() async_track_state_change_event( @@ -202,7 +205,9 @@ class IntegrationSensor(RestoreEntity, SensorEntity): @property def native_value(self): """Return the state of the sensor.""" - return round(self._state, self._round_digits) + if isinstance(self._state, Decimal): + return round(self._state, self._round_digits) + return self._state @property def native_unit_of_measurement(self): diff --git a/tests/components/integration/test_sensor.py b/tests/components/integration/test_sensor.py index e8aaf906936..58df0a53a00 100644 --- a/tests/components/integration/test_sensor.py +++ b/tests/components/integration/test_sensor.py @@ -81,7 +81,6 @@ async def test_restore_state(hass: HomeAssistant) -> None: "platform": "integration", "name": "integration", "source": "sensor.power", - "unit": ENERGY_KILO_WATT_HOUR, "round": 2, } } @@ -114,7 +113,6 @@ async def test_restore_state_failed(hass: HomeAssistant) -> None: "platform": "integration", "name": "integration", "source": "sensor.power", - "unit": ENERGY_KILO_WATT_HOUR, } } @@ -123,9 +121,10 @@ async def test_restore_state_failed(hass: HomeAssistant) -> None: state = hass.states.get("sensor.integration") assert state - assert state.state == "0" - assert state.attributes.get("unit_of_measurement") == ENERGY_KILO_WATT_HOUR + assert state.state == "unavailable" + assert state.attributes.get("unit_of_measurement") is None assert state.attributes.get("state_class") == STATE_CLASS_TOTAL_INCREASING + assert "device_class" not in state.attributes