Small speed up to compressed state diff (#106624)

This commit is contained in:
J. Nick Koston 2023-12-28 21:36:20 -10:00 committed by GitHub
parent 7051f28547
commit 03fcb81a59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 1 deletions

View File

@ -204,7 +204,7 @@ def _state_diff(
for key, value in new_attributes.items():
if old_attributes.get(key) != value:
additions.setdefault(COMPRESSED_STATE_ATTRIBUTES, {})[key] = value
if removed := set(old_attributes).difference(new_attributes):
if removed := old_attributes.keys() - new_attributes:
# sets are not JSON serializable by default so we convert to list
# here if there are any values to avoid jumping into the json_encoder_default
# for every state diff with a removed attribute

View File

@ -237,6 +237,50 @@ async def test_state_diff_event(hass: HomeAssistant) -> None:
}
}
hass.states.async_set(
"light.window",
"green",
{"list_attr": ["a", "b", "c", "d"], "list_attr_2": ["a", "b"]},
context=new_context,
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"a": {"list_attr": ["a", "b", "c", "d"], "list_attr_2": ["a", "b"]},
"lu": new_state.last_updated.timestamp(),
}
}
}
}
hass.states.async_set(
"light.window",
"green",
{"list_attr": ["a", "b", "c", "e"]},
context=new_context,
)
await hass.async_block_till_done()
last_state_event: Event = state_change_events[-1]
new_state: State = last_state_event.data["new_state"]
message = _state_diff_event(last_state_event)
assert message == {
"c": {
"light.window": {
"+": {
"a": {"list_attr": ["a", "b", "c", "e"]},
"lu": new_state.last_updated.timestamp(),
},
"-": {"a": ["list_attr_2"]},
}
}
}
async def test_message_to_json(caplog: pytest.LogCaptureFixture) -> None:
"""Test we can serialize websocket messages."""