From 35ad9e6ea20b38bb2b9d922c19aa325381962dee Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Sun, 1 Nov 2026 11:55:47 +0100 Subject: [PATCH] Use the real period length for history stats ratios (#189819) --- .../components/history_stats/helpers.py | 7 ++- .../components/history_stats/test_helpers.py | 59 +++++++++++++++++++ tests/components/history_stats/test_sensor.py | 49 +++++++++++++++ 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 tests/components/history_stats/test_helpers.py diff --git a/homeassistant/components/history_stats/helpers.py b/homeassistant/components/history_stats/helpers.py index db7f217ae3c8..61068c58f5c7 100644 --- a/homeassistant/components/history_stats/helpers.py +++ b/homeassistant/components/history_stats/helpers.py @@ -78,10 +78,13 @@ def async_calculate_period( def pretty_ratio(value: float, period: tuple[dt.datetime, dt.datetime]) -> float: """Format the ratio of value / period duration.""" - if len(period) != 2 or period[0] == period[1]: + # Subtracting datetimes of the same time zone ignores daylight saving changes + duration = dt_util.as_utc(period[1]) - dt_util.as_utc(period[0]) + # Bounds in a skipped hour can be distinct datetimes at the same instant + if not duration: return 0.0 - ratio = 100 * value / (period[1] - period[0]).total_seconds() + ratio = 100 * value / duration.total_seconds() return round(ratio, 1) diff --git a/tests/components/history_stats/test_helpers.py b/tests/components/history_stats/test_helpers.py new file mode 100644 index 000000000000..d4c6af57fdf1 --- /dev/null +++ b/tests/components/history_stats/test_helpers.py @@ -0,0 +1,59 @@ +"""Test the History stats helpers.""" + +from datetime import datetime +from zoneinfo import ZoneInfo + +import pytest + +from homeassistant.components.history_stats.helpers import pretty_ratio +from homeassistant.core import HomeAssistant + +# Falls back on 2026-11-01 and springs forward on 2026-03-08 +TIME_ZONE = "US/Pacific" + + +@pytest.mark.parametrize( + ("value", "start", "end", "expected"), + [ + pytest.param( + 90000, + datetime(2026, 11, 1), + datetime(2026, 11, 2), + 100.0, + id="naive_bounds_over_fall_back", + ), + pytest.param( + 90000, + datetime(2026, 11, 1, tzinfo=ZoneInfo(TIME_ZONE)), + datetime(2026, 11, 2, tzinfo=ZoneInfo(TIME_ZONE)), + 100.0, + id="local_bounds_over_fall_back", + ), + pytest.param( + 82800, + datetime(2026, 3, 8, tzinfo=ZoneInfo(TIME_ZONE)), + datetime(2026, 3, 9, tzinfo=ZoneInfo(TIME_ZONE)), + 100.0, + id="local_bounds_over_spring_forward", + ), + pytest.param( + 0, + datetime(2026, 3, 8, 2, 30, tzinfo=ZoneInfo(TIME_ZONE)), + datetime(2026, 3, 8, 3, 30, tzinfo=ZoneInfo(TIME_ZONE)), + 0.0, + id="skipped_hour_has_no_length", + ), + ], +) +async def test_pretty_ratio( + hass: HomeAssistant, + value: float, + start: datetime, + end: datetime, + expected: float, +) -> None: + """Test the ratio uses the real length of the period.""" + # Naive bounds are in the time zone of Home Assistant, not of the host + await hass.config.async_set_time_zone(TIME_ZONE) + + assert pretty_ratio(value, (start, end)) == expected diff --git a/tests/components/history_stats/test_sensor.py b/tests/components/history_stats/test_sensor.py index e3c0579f250e..b2daad722b83 100644 --- a/tests/components/history_stats/test_sensor.py +++ b/tests/components/history_stats/test_sensor.py @@ -1514,6 +1514,55 @@ async def test_measure_sliding_window( assert hass.states.get("sensor.sensor4").state == "8.3" +async def test_ratio_over_daylight_saving_time_change( + recorder_mock: Recorder, hass: HomeAssistant +) -> None: + """Test the ratio uses the real length of a day with a daylight saving change.""" + # The US/Pacific day of the fall back to standard time lasts 25 hours + now = dt_util.parse_datetime("2026-11-02T12:00:00-08:00") + + def _fake_states(*args, **kwargs): + return { + "binary_sensor.test_id": [ + ha.State( + "binary_sensor.test_id", + "on", + last_changed=dt_util.parse_datetime("2026-10-31T12:00:00-07:00"), + ), + ] + } + + with ( + patch( + "homeassistant.components.recorder.history.state_changes_during_period", + _fake_states, + ), + freeze_time(now), + ): + await async_setup_component( + hass, + "sensor", + { + "sensor": [ + { + "platform": "history_stats", + "entity_id": "binary_sensor.test_id", + "name": "sensor1", + "state": "on", + "start": "{{ as_timestamp(today_at() - timedelta(days=1)) }}", + "end": "{{ as_timestamp(today_at()) }}", + "type": "ratio", + }, + ] + }, + ) + await hass.async_block_till_done() + await async_update_entity(hass, "sensor.sensor1") + await hass.async_block_till_done() + + assert hass.states.get("sensor.sensor1").state == "100.0" + + async def test_measure_from_end_going_backwards( recorder_mock: Recorder, hass: HomeAssistant ) -> None: