Prevent entity creation errors from causing all entities for a platform from loading in ZHA (#121631)

This commit is contained in:
David F. Mulcahey 2024-07-10 02:31:24 -04:00 committed by GitHub
parent 4245357403
commit 0aa6a17da8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 49 additions and 1 deletions

View File

@ -1116,7 +1116,17 @@ async def async_add_entities(
if not entities:
return
entities_to_add = [entity_class(entity_data) for entity_data in entities]
entities_to_add = []
for entity_data in entities:
try:
entities_to_add.append(entity_class(entity_data))
# broad exception to prevent a single entity from preventing an entire platform from loading
# this can potentially be caused by a misbehaving device or a bad quirk. Not ideal but the
# alternative is adding try/catch to each entity class __init__ method with a specific exception
except Exception: # noqa: BLE001
_LOGGER.exception(
"Error while adding entity from entity data: %s", entity_data
)
_async_add_entities(entities_to_add, update_before_add=False)
entities.clear()

View File

@ -556,3 +556,41 @@ async def async_test_flash_from_hass(
manufacturer=None,
tsn=None,
)
@patch(
"zigpy.zcl.clusters.lighting.Color.request",
new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]),
)
@patch(
"zigpy.zcl.clusters.general.Identify.request",
new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]),
)
@patch(
"zigpy.zcl.clusters.general.LevelControl.request",
new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]),
)
@patch(
"zigpy.zcl.clusters.general.OnOff.request",
new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]),
)
async def test_light_exception_on_creation(
hass: HomeAssistant,
setup_zha,
zigpy_device_mock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ZHA light entity creation exception."""
await setup_zha()
gateway = get_zha_gateway(hass)
zigpy_device = zigpy_device_mock(LIGHT_COLOR)
gateway.get_or_create_device(zigpy_device)
with patch(
"homeassistant.components.zha.light.Light.__init__", side_effect=Exception
):
await gateway.async_device_initialized(zigpy_device)
await hass.async_block_till_done(wait_background_tasks=True)
assert "Error while adding entity from entity data" in caplog.text