From 7df0016fab91cd81e850856e25a4ce8a2b423bfb Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Mon, 14 Jul 2025 20:05:20 +0200 Subject: [PATCH] Do not add threshold config entry to source device (#148732) --- .../components/threshold/__init__.py | 50 ++++- .../components/threshold/binary_sensor.py | 42 +++-- .../components/threshold/config_flow.py | 17 +- tests/components/threshold/test_init.py | 177 ++++++++++++++++-- 4 files changed, 237 insertions(+), 49 deletions(-) diff --git a/homeassistant/components/threshold/__init__.py b/homeassistant/components/threshold/__init__.py index 9460a50db80..56d51f4f1e0 100644 --- a/homeassistant/components/threshold/__init__.py +++ b/homeassistant/components/threshold/__init__.py @@ -1,5 +1,7 @@ """The threshold component.""" +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ENTITY_ID, Platform from homeassistant.core import HomeAssistant @@ -7,12 +9,18 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) + +_LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Min/Max from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -25,20 +33,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_ENTITY_ID: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_ENTITY_ID] ), source_entity_id_or_uuid=entry.options[CONF_ENTITY_ID], - source_entity_removed=source_entity_removed, ) ) @@ -51,6 +55,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the threshold config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_ENTITY_ID] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener, called when the config entry options are changed.""" diff --git a/homeassistant/components/threshold/binary_sensor.py b/homeassistant/components/threshold/binary_sensor.py index 3227f030812..88fd2784f96 100644 --- a/homeassistant/components/threshold/binary_sensor.py +++ b/homeassistant/components/threshold/binary_sensor.py @@ -31,8 +31,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import config_validation as cv, entity_registry as er -from homeassistant.helpers.device import async_device_info_to_link_from_entity -from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -102,11 +101,6 @@ async def async_setup_entry( registry, config_entry.options[CONF_ENTITY_ID] ) - device_info = async_device_info_to_link_from_entity( - hass, - entity_id, - ) - hysteresis = config_entry.options[CONF_HYSTERESIS] lower = config_entry.options[CONF_LOWER] name = config_entry.title @@ -116,14 +110,14 @@ async def async_setup_entry( async_add_entities( [ ThresholdSensor( - entity_id, - name, - lower, - upper, - hysteresis, - device_class, - unique_id, - device_info=device_info, + hass, + entity_id=entity_id, + name=name, + lower=lower, + upper=upper, + hysteresis=hysteresis, + device_class=device_class, + unique_id=unique_id, ) ] ) @@ -146,7 +140,14 @@ async def async_setup_platform( async_add_entities( [ ThresholdSensor( - entity_id, name, lower, upper, hysteresis, device_class, None + hass, + entity_id=entity_id, + name=name, + lower=lower, + upper=upper, + hysteresis=hysteresis, + device_class=device_class, + unique_id=None, ) ], ) @@ -171,6 +172,8 @@ class ThresholdSensor(BinarySensorEntity): def __init__( self, + hass: HomeAssistant, + *, entity_id: str, name: str, lower: float | None, @@ -178,12 +181,15 @@ class ThresholdSensor(BinarySensorEntity): hysteresis: float, device_class: BinarySensorDeviceClass | None, unique_id: str | None, - device_info: DeviceInfo | None = None, ) -> None: """Initialize the Threshold sensor.""" self._preview_callback: Callable[[str, Mapping[str, Any]], None] | None = None self._attr_unique_id = unique_id - self._attr_device_info = device_info + if entity_id: # Guard against empty entity_id in preview mode + self.device_entry = async_entity_id_to_device( + hass, + entity_id, + ) self._entity_id = entity_id self._attr_name = name if lower is not None: diff --git a/homeassistant/components/threshold/config_flow.py b/homeassistant/components/threshold/config_flow.py index 24f58333782..29f4a0986c1 100644 --- a/homeassistant/components/threshold/config_flow.py +++ b/homeassistant/components/threshold/config_flow.py @@ -80,6 +80,8 @@ OPTIONS_FLOW = { class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow for Threshold.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW @@ -131,13 +133,14 @@ def ws_start_preview( ) preview_entity = ThresholdSensor( - entity_id, - name, - msg["user_input"].get(CONF_LOWER), - msg["user_input"].get(CONF_UPPER), - msg["user_input"].get(CONF_HYSTERESIS), - None, - None, + hass, + entity_id=entity_id, + name=name, + lower=msg["user_input"].get(CONF_LOWER), + upper=msg["user_input"].get(CONF_UPPER), + hysteresis=msg["user_input"].get(CONF_HYSTERESIS), + device_class=None, + unique_id=None, ) preview_entity.hass = hass diff --git a/tests/components/threshold/test_init.py b/tests/components/threshold/test_init.py index 599612ce0b7..fed35bc6502 100644 --- a/tests/components/threshold/test_init.py +++ b/tests/components/threshold/test_init.py @@ -7,8 +7,8 @@ import pytest from homeassistant.components import threshold from homeassistant.components.threshold.config_flow import ConfigFlowHandler from homeassistant.components.threshold.const import DOMAIN -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -81,6 +81,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -174,6 +175,7 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: # Set up entities, with backing devices and config entries run1_entry = _create_mock_entity("sensor", "initial") run2_entry = _create_mock_entity("sensor", "changed") + assert run1_entry.device_id != run2_entry.device_id # Setup the config entry config_entry = MockConfigEntry( @@ -186,23 +188,27 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: "name": "My threshold", "upper": None, }, - title="My integration", + title="My threshold", ) config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() - assert config_entry.entry_id in _get_device_config_entries(run1_entry) + assert config_entry.entry_id not in _get_device_config_entries(run1_entry) assert config_entry.entry_id not in _get_device_config_entries(run2_entry) + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == run1_entry.device_id hass.config_entries.async_update_entry( config_entry, options={**config_entry.options, "entity_id": "sensor.changed"} ) await hass.async_block_till_done() - # Check that the config entry association has updated + # Check that the device association has updated assert config_entry.entry_id not in _get_device_config_entries(run1_entry) - assert config_entry.entry_id in _get_device_config_entries(run2_entry) + assert config_entry.entry_id not in _get_device_config_entries(run2_entry) + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == run2_entry.device_id async def test_device_cleaning( @@ -273,7 +279,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( threshold_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(threshold_config_entry.entry_id) @@ -288,7 +294,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( threshold_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 async def test_async_handle_source_entity_changes_source_entity_removed( @@ -299,6 +305,54 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the threshold config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(threshold_config_entry.entry_id) + await hass.async_block_till_done() + + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.threshold.async_unload_entry", + wraps=threshold.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the threshold config entry is not removed + assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["update"] + + +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + threshold_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the threshold config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -315,7 +369,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -332,7 +386,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() - # Check that the threshold config entry is removed from the device + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the threshold config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries @@ -359,7 +417,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -374,7 +432,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the threshold config entry is removed from the device + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the threshold config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries @@ -407,7 +469,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert threshold_config_entry.entry_id not in sensor_device_2.config_entries @@ -424,11 +486,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the threshold config entry is moved to the other device + # Check that the entity is linked to the other device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_device_2.id + + # Check that the derivative config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert threshold_config_entry.entry_id in sensor_device_2.config_entries + assert threshold_config_entry.entry_id not in sensor_device_2.config_entries # Check that the threshold config entry is not removed assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -453,7 +519,7 @@ async def test_async_handle_source_entity_new_entity_id( assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -471,12 +537,87 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the threshold config entry is updated with the new entity ID assert threshold_config_entry.options["entity_id"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries # Check that the threshold config entry is not removed assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, +) -> None: + """Test migration from v1.1 removes threshold config entry from device.""" + + threshold_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "entity_id": sensor_entity_entry.entity_id, + "hysteresis": 0.0, + "lower": -2.0, + "name": "My threshold", + "upper": None, + }, + title="My threshold", + version=1, + minor_version=1, + ) + threshold_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=threshold_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(threshold_config_entry.entry_id) + await hass.async_block_till_done() + + assert threshold_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id not in sensor_device.config_entries + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_entity_entry.device_id + + assert threshold_config_entry.version == 1 + assert threshold_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "entity_id": "sensor.test", + "hysteresis": 0.0, + "lower": -2.0, + "name": "My threshold", + "upper": None, + }, + title="My threshold", + version=2, + minor_version=1, + ) + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.MIGRATION_ERROR