Remove orphan devices on startup in SmartThings (#139541)

pull/139859/head
Joost Lekkerkerker 2025-02-28 20:33:25 +01:00 committed by Bram Kragten
parent 6f0c62dc9d
commit f54b3f4de2
2 changed files with 37 additions and 1 deletions

View File

@ -21,13 +21,14 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
async_get_config_entry_implementation,
)
from .const import CONF_INSTALLED_APP_ID, CONF_LOCATION_ID, MAIN, OLD_DATA
from .const import CONF_INSTALLED_APP_ID, CONF_LOCATION_ID, DOMAIN, MAIN, OLD_DATA
_LOGGER = logging.getLogger(__name__)
@ -123,6 +124,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: SmartThingsConfigEntry)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
device_registry = dr.async_get(hass)
device_entries = dr.async_entries_for_config_entry(device_registry, entry.entry_id)
for device_entry in device_entries:
device_id = next(
identifier[1]
for identifier in device_entry.identifiers
if identifier[0] == DOMAIN
)
if device_id in entry.runtime_data.devices:
continue
device_registry.async_update_device(
device_entry.id, remove_config_entry_id=entry.entry_id
)
return True

View File

@ -2,6 +2,7 @@
from unittest.mock import AsyncMock
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.smartthings.const import DOMAIN
@ -29,3 +30,23 @@ async def test_devices(
assert device is not None
assert device == snapshot
@pytest.mark.parametrize("device_fixture", ["da_ac_rac_000001"])
async def test_removing_stale_devices(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test removing stale devices."""
mock_config_entry.add_to_hass(hass)
device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, "aaa-bbb-ccc")},
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not device_registry.async_get_device({(DOMAIN, "aaa-bbb-ccc")})