From 1626c236dc63bfac501bccb5589af2ef0937972f Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 7 Nov 2020 15:51:06 -1000 Subject: [PATCH] Only call utcnow once during a state changed event (#42941) --- homeassistant/core.py | 5 ++++- tests/test_core.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/homeassistant/core.py b/homeassistant/core.py index 295e813a642..a5dea7fcc5e 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -1180,12 +1180,14 @@ class StateMachine: if context is None: context = Context() + now = dt_util.utcnow() + state = State( entity_id, new_state, attributes, last_changed, - None, + now, context, old_state is None, ) @@ -1195,6 +1197,7 @@ class StateMachine: {"entity_id": entity_id, "old_state": old_state, "new_state": state}, EventOrigin.local, context, + time_fired=now, ) diff --git a/tests/test_core.py b/tests/test_core.py index 119c0269ba7..a7bd87c650e 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1584,3 +1584,24 @@ async def test_reserving_states(hass): assert hass.states.async_available("light.bedroom") is False hass.states.async_remove("light.bedroom") assert hass.states.async_available("light.bedroom") is True + + +async def test_state_change_events_match_state_time(hass): + """Test last_updated and timed_fired only call utcnow once.""" + + events = [] + + @ha.callback + def _event_listener(event): + events.append(event) + + hass.bus.async_listen(ha.EVENT_STATE_CHANGED, _event_listener) + + hass.states.async_set("light.bedroom", "on") + await hass.async_block_till_done() + state = hass.states.get("light.bedroom") + + import pprint + + pprint.pprint(events) + assert state.last_updated == events[0].time_fired