Use the real period length for history stats ratios (#189819)

This commit is contained in:
Josef Zweck
2026-11-01 11:55:47 +01:00
committed by GitHub
parent 0d98008033
commit 35ad9e6ea2
3 changed files with 113 additions and 2 deletions
@@ -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)
@@ -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
@@ -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: