Only call utcnow once during a state changed event (#42941)

This commit is contained in:
J. Nick Koston 2020-11-07 15:51:06 -10:00 committed by GitHub
parent eebf0ef336
commit 1626c236dc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View file

@ -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,
)

View file

@ -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