From 919f3243de8fe4c8ec7085c56f6a06f2f811e8d3 Mon Sep 17 00:00:00 2001 From: Andre Lengwenus Date: Sat, 23 May 2020 09:46:03 +0200 Subject: [PATCH] Fix device_registry cleanup behavior (#35977) * Fix: Only decives which are not referenced by an entity or a config_entry are removed * Adapted test for async_cleanup * Changed variable names --- homeassistant/helpers/device_registry.py | 18 +++++++++++++----- tests/helpers/test_device_registry.py | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/homeassistant/helpers/device_registry.py b/homeassistant/helpers/device_registry.py index 8fbb81962ff..2e91d0d6622 100644 --- a/homeassistant/helpers/device_registry.py +++ b/homeassistant/helpers/device_registry.py @@ -399,17 +399,25 @@ def async_cleanup( ent_reg: "entity_registry.EntityRegistry", ) -> None: """Clean up device registry.""" - # Find all devices that are no longer referenced in the entity registry. - referenced = {entry.device_id for entry in ent_reg.entities.values()} - orphan = set(dev_reg.devices) - referenced + # Find all devices that are referenced by a config_entry. + config_entry_ids = {entry.entry_id for entry in hass.config_entries.async_entries()} + references_config_entries = { + device.id + for device in dev_reg.devices.values() + for config_entry_id in device.config_entries + if config_entry_id in config_entry_ids + } + + # Find all devices that are referenced in the entity registry. + references_entities = {entry.device_id for entry in ent_reg.entities.values()} + + orphan = set(dev_reg.devices) - references_entities - references_config_entries for dev_id in orphan: dev_reg.async_remove_device(dev_id) # Find all referenced config entries that no longer exist # This shouldn't happen but have not been able to track down the bug :( - config_entry_ids = {entry.entry_id for entry in hass.config_entries.async_entries()} - for device in list(dev_reg.devices.values()): for config_entry_id in device.config_entries: if config_entry_id not in config_entry_ids: diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index ef5f92de79c..3fbb73a2aa8 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -539,7 +539,7 @@ async def test_cleanup_device_registry(hass, registry): device_registry.async_cleanup(hass, registry, ent_reg) assert registry.async_get_device({("hue", "d1")}, set()) is not None - assert registry.async_get_device({("hue", "d2")}, set()) is None + assert registry.async_get_device({("hue", "d2")}, set()) is not None assert registry.async_get_device({("hue", "d3")}, set()) is not None assert registry.async_get_device({("something", "d4")}, set()) is None