From af2e95d8919f3ee3979a007353a8b38677f83c81 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 7 Dec 2021 12:44:50 +0100 Subject: [PATCH] Guard against missing states in Alexa state updates (#61152) --- homeassistant/components/alexa/state_report.py | 9 +++++---- tests/components/alexa/test_state_report.py | 12 ++++++++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/alexa/state_report.py b/homeassistant/components/alexa/state_report.py index 1ab12041e32..767bfa18224 100644 --- a/homeassistant/components/alexa/state_report.py +++ b/homeassistant/components/alexa/state_report.py @@ -182,12 +182,13 @@ async def async_send_add_or_update_message(hass, config, entity_ids): endpoints = [] for entity_id in entity_ids: - domain = entity_id.split(".", 1)[0] - - if domain not in ENTITY_ADAPTERS: + if (domain := entity_id.split(".", 1)[0]) not in ENTITY_ADAPTERS: continue - alexa_entity = ENTITY_ADAPTERS[domain](hass, config, hass.states.get(entity_id)) + if (state := hass.states.get(entity_id)) is None: + continue + + alexa_entity = ENTITY_ADAPTERS[domain](hass, config, state) endpoints.append(alexa_entity.serialize_discovery()) payload = {"endpoints": endpoints, "scope": {"type": "BearerToken", "token": token}} diff --git a/tests/components/alexa/test_state_report.py b/tests/components/alexa/test_state_report.py index bd91dc8f846..29624e7d1ff 100644 --- a/tests/components/alexa/test_state_report.py +++ b/tests/components/alexa/test_state_report.py @@ -117,10 +117,18 @@ async def test_send_add_or_update_message(hass, aioclient_mock): {"friendly_name": "Test Contact Sensor", "device_class": "door"}, ) - await state_report.async_send_add_or_update_message( - hass, DEFAULT_CONFIG, ["binary_sensor.test_contact", "zwave.bla"] + hass.states.async_set( + "zwave.bla", + "wow_such_unsupported", ) + entities = [ + "binary_sensor.test_contact", + "binary_sensor.non_existing", # Supported, but does not exist + "zwave.bla", # Unsupported + ] + await state_report.async_send_add_or_update_message(hass, DEFAULT_CONFIG, entities) + assert len(aioclient_mock.mock_calls) == 1 call = aioclient_mock.mock_calls