Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a history stats bug when window and tracked state change simultaneously #133770

Merged
merged 5 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions homeassistant/components/history_stats/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,18 @@ async def async_update(
await self._async_history_from_db(
current_period_start_timestamp, current_period_end_timestamp
)
if event and (new_state := event.data["new_state"]) is not None:
if (
current_period_start_timestamp
<= floored_timestamp(new_state.last_changed)
<= current_period_end_timestamp
):
self._history_current_period.append(
HistoryState(
new_state.state, new_state.last_changed.timestamp()
frenck marked this conversation as resolved.
Show resolved Hide resolved
)
)

self._previous_run_before_start = False

seconds_matched, match_count = self._async_compute_seconds_and_changes(
Expand Down
90 changes: 90 additions & 0 deletions tests/components/history_stats/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1465,6 +1465,96 @@ def _fake_states(*args, **kwargs):
assert hass.states.get("sensor.sensor4").state == "50.0"


async def test_state_change_during_window_rollover(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test we startup from history and switch to watching state changes."""
await hass.config.async_set_time_zone("UTC")
utcnow = dt_util.utcnow()
start_time = utcnow.replace(hour=23, minute=0, second=0, microsecond=0)

def _fake_states(*args, **kwargs):
return {
"binary_sensor.state": [
ha.State(
"binary_sensor.state",
"on",
last_changed=start_time - timedelta(hours=11),
last_updated=start_time - timedelta(hours=11),
),
]
}

with (
patch(
"homeassistant.components.recorder.history.state_changes_during_period",
_fake_states,
),
freeze_time(start_time),
):
await async_setup_component(
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ today_at() }}",
"end": "{{ now() }}",
"type": "time",
}
]
},
)
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 == "11.0"

t1 = start_time + timedelta(minutes=30)
with freeze_time(t1):
async_fire_time_changed(hass, t1)
await hass.async_block_till_done()

assert hass.states.get("sensor.sensor1").state == "11.5"

t2 = t1 + timedelta(minutes=29, microseconds=300)
with freeze_time(t2):
async_fire_time_changed(hass, t2)
await hass.async_block_till_done()

assert hass.states.get("sensor.sensor1").state == "11.98"

t3 = t2 + timedelta(minutes=1)
with freeze_time(t3):
hass.states.async_set("binary_sensor.state", "off")
await hass.async_block_till_done()
async_fire_time_changed(hass, t3)
await hass.async_block_till_done()

assert hass.states.get("sensor.sensor1").state == "0.0"

t4 = t3 + timedelta(minutes=10)
with freeze_time(t4):
async_fire_time_changed(hass, t4)
await hass.async_block_till_done()

assert hass.states.get("sensor.sensor1").state == "0.0"
Copy link
Contributor Author

@karwosts karwosts Dec 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the fix the test fails here:

./tests/components/history_stats/test_sensor.py::test_state_change_during_window_rollover Failed: [undefined]AssertionError: assert '0.17' == '0.0'


t5 = t4 + timedelta(hours=1)
with freeze_time(t5):
async_fire_time_changed(hass, t5)
await hass.async_block_till_done()

assert hass.states.get("sensor.sensor1").state == "0.0"


@pytest.mark.parametrize("time_zone", ["Europe/Berlin", "America/Chicago", "US/Hawaii"])
async def test_end_time_with_microseconds_zeroed(
time_zone: str,
Expand Down