diff --git a/homeassistant/components/websocket_api/messages.py b/homeassistant/components/websocket_api/messages.py index 3d85f984e9a..e5fd5626302 100644 --- a/homeassistant/components/websocket_api/messages.py +++ b/homeassistant/components/websocket_api/messages.py @@ -180,7 +180,10 @@ def _state_diff( if old_attributes.get(key) != value: additions.setdefault(COMPRESSED_STATE_ATTRIBUTES, {})[key] = value if removed := set(old_attributes).difference(new_attributes): - diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: removed} + # 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 + diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: list(removed)} return {ENTITY_EVENT_CHANGE: {new_state.entity_id: diff}} diff --git a/tests/components/websocket_api/test_messages.py b/tests/components/websocket_api/test_messages.py index d2102b651b7..6aafb9f2685 100644 --- a/tests/components/websocket_api/test_messages.py +++ b/tests/components/websocket_api/test_messages.py @@ -222,6 +222,21 @@ async def test_state_diff_event(hass: HomeAssistant) -> None: } } + hass.states.async_set("light.window", "green", {}, 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": { + "+": {"lc": new_state.last_changed.timestamp(), "s": "green"}, + "-": {"a": ["new"]}, + } + } + } + async def test_message_to_json(caplog: pytest.LogCaptureFixture) -> None: """Test we can serialize websocket messages."""