From 927c9d34801cac49464ee3ef583617ed832140bf Mon Sep 17 00:00:00 2001 From: Jan-Philipp Benecke Date: Tue, 10 Jun 2025 14:10:49 +0200 Subject: [PATCH] Improve error logging in trend binary sensor (#146358) --- .../components/trend/binary_sensor.py | 9 +++- tests/components/trend/test_binary_sensor.py | 47 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/trend/binary_sensor.py b/homeassistant/components/trend/binary_sensor.py index 4261f96bbe6..2bc5949b970 100644 --- a/homeassistant/components/trend/binary_sensor.py +++ b/homeassistant/components/trend/binary_sensor.py @@ -239,7 +239,14 @@ class SensorTrend(BinarySensorEntity, RestoreEntity): self.async_schedule_update_ha_state(True) except (ValueError, TypeError) as ex: - _LOGGER.error(ex) + _LOGGER.error( + "Error processing sensor state change for " + "entity_id=%s, attribute=%s, state=%s: %s", + self._entity_id, + self._attribute, + new_state.state, + ex, + ) self.async_on_remove( async_track_state_change_event( diff --git a/tests/components/trend/test_binary_sensor.py b/tests/components/trend/test_binary_sensor.py index 4a829bb86d2..4f19c7e3427 100644 --- a/tests/components/trend/test_binary_sensor.py +++ b/tests/components/trend/test_binary_sensor.py @@ -437,3 +437,50 @@ async def test_unavailable_source( await hass.async_block_till_done() assert hass.states.get("binary_sensor.test_trend_sensor").state == "on" + + +async def test_invalid_state_handling( + hass: HomeAssistant, + config_entry: MockConfigEntry, + setup_component: ComponentSetup, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test handling of invalid states in trend sensor.""" + await setup_component( + { + "sample_duration": 10000, + "min_gradient": 1, + "max_samples": 25, + "min_samples": 5, + }, + ) + + for val in (10, 20, 30, 40, 50, 60): + freezer.tick(timedelta(seconds=2)) + hass.states.async_set("sensor.test_state", val) + await hass.async_block_till_done() + + assert hass.states.get("binary_sensor.test_trend_sensor").state == STATE_ON + + # Set an invalid state + hass.states.async_set("sensor.test_state", "invalid") + await hass.async_block_till_done() + + # The trend sensor should handle the invalid state gracefully + assert (sensor_state := hass.states.get("binary_sensor.test_trend_sensor")) + assert sensor_state.state == STATE_ON + + # Check if a warning is logged + assert ( + "Error processing sensor state change for entity_id=sensor.test_state, " + "attribute=None, state=invalid: could not convert string to float: 'invalid'" + ) in caplog.text + + # Set a valid state again + hass.states.async_set("sensor.test_state", 50) + await hass.async_block_till_done() + + # The trend sensor should return to a valid state + assert (sensor_state := hass.states.get("binary_sensor.test_trend_sensor")) + assert sensor_state.state == "on"