diff --git a/homeassistant/components/filter/__init__.py b/homeassistant/components/filter/__init__.py index 39743cb1944d..8416abb20ffd 100644 --- a/homeassistant/components/filter/__init__.py +++ b/homeassistant/components/filter/__init__.py @@ -1,7 +1,10 @@ """The filter component.""" from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_ENTITY_ID from homeassistant.core import HomeAssistant +from homeassistant.helpers.device import async_entity_id_to_device_id +from homeassistant.helpers.helper_integration import async_handle_source_entity_changes from .const import DOMAIN, PLATFORMS @@ -13,6 +16,24 @@ __all__ = [ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Set up Filter from a config entry.""" + def set_source_entity_id_or_uuid(source_entity_id: str) -> None: + hass.config_entries.async_update_entry( + entry, + options={**entry.options, CONF_ENTITY_ID: source_entity_id}, + ) + hass.config_entries.async_schedule_reload(entry.entry_id) + + entry.async_on_unload( + async_handle_source_entity_changes( + hass, + 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], + ) + ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) diff --git a/homeassistant/components/filter/sensor.py b/homeassistant/components/filter/sensor.py index 36ee364b010b..a1f815f9e7f4 100644 --- a/homeassistant/components/filter/sensor.py +++ b/homeassistant/components/filter/sensor.py @@ -39,6 +39,8 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.device import async_entity_id_to_device +from homeassistant.helpers.device_registry import AnyDeviceEntry from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -225,7 +227,17 @@ async def async_setup_entry( FILTERS[filter_config.pop(CONF_FILTER_NAME)](entity=entity_id, **filter_config) ] - async_add_entities([SensorFilter(name, entry.entry_id, entity_id, filters)]) + async_add_entities( + [ + SensorFilter( + name, + entry.entry_id, + entity_id, + filters, + device=async_entity_id_to_device(hass, entity_id), + ) + ] + ) class SensorFilter(SensorEntity): @@ -239,10 +251,12 @@ class SensorFilter(SensorEntity): unique_id: str | None, entity_id: str, filters: list[Filter], + device: AnyDeviceEntry | None = None, ) -> None: """Initialize the sensor.""" self._attr_name = name self._attr_unique_id = unique_id + self.device_entry = device self._entity = entity_id self._attr_native_unit_of_measurement = None self._state: StateType = None diff --git a/tests/components/filter/conftest.py b/tests/components/filter/conftest.py index 1a6c57d7a300..da73ac25b5e1 100644 --- a/tests/components/filter/conftest.py +++ b/tests/components/filter/conftest.py @@ -20,9 +20,10 @@ from homeassistant.components.filter.const import ( DOMAIN, FILTER_NAME_OUTLIER, ) -from homeassistant.config_entries import SOURCE_USER +from homeassistant.config_entries import SOURCE_USER, ConfigEntry from homeassistant.const import CONF_ENTITY_ID, CONF_NAME from homeassistant.core import HomeAssistant, State +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.util import dt as dt_util @@ -88,3 +89,60 @@ async def load_integration( await hass.async_block_till_done() return config_entry + + +@pytest.fixture +def sensor_config_entry(hass: HomeAssistant) -> MockConfigEntry: + """Fixture to create a sensor config entry.""" + sensor_config_entry = MockConfigEntry() + sensor_config_entry.add_to_hass(hass) + return sensor_config_entry + + +@pytest.fixture +def sensor_device( + device_registry: dr.DeviceRegistry, sensor_config_entry: ConfigEntry +) -> dr.DeviceEntry: + """Fixture to create a sensor device.""" + return device_registry.async_get_or_create( + config_entry_id=sensor_config_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, + ) + + +@pytest.fixture +def sensor_entity_entry( + entity_registry: er.EntityRegistry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, +) -> er.RegistryEntry: + """Fixture to create a sensor entity entry.""" + return entity_registry.async_get_or_create( + "sensor", + "test", + "unique", + config_entry=sensor_config_entry, + device_id=sensor_device.id, + original_name="ABC", + ) + + +@pytest.fixture +def filter_config_entry( + hass: HomeAssistant, sensor_entity_entry: er.RegistryEntry +) -> MockConfigEntry: + """Fixture to create a filter config entry for the source entity.""" + config_entry = MockConfigEntry( + domain=DOMAIN, + options={ + CONF_NAME: "My filter", + CONF_ENTITY_ID: sensor_entity_entry.entity_id, + CONF_FILTER_NAME: FILTER_NAME_OUTLIER, + CONF_FILTER_WINDOW_SIZE: DEFAULT_WINDOW_SIZE, + CONF_FILTER_RADIUS: DEFAULT_FILTER_RADIUS, + CONF_FILTER_PRECISION: DEFAULT_PRECISION, + }, + title="My filter", + ) + config_entry.add_to_hass(hass) + return config_entry diff --git a/tests/components/filter/test_init.py b/tests/components/filter/test_init.py index f6abcb532637..173ca044e778 100644 --- a/tests/components/filter/test_init.py +++ b/tests/components/filter/test_init.py @@ -1,10 +1,34 @@ """Test Filter component setup process.""" +from unittest.mock import patch + +import pytest from pytest_homeassistant.common import MockConfigEntry +from homeassistant.components import filter as filter_integration +from homeassistant.components.filter.const import FilterEntityStateAttribute from homeassistant.components.recorder import Recorder -from homeassistant.config_entries import ConfigEntryState -from homeassistant.core import HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.const import CONF_ENTITY_ID +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 + +FILTER_ENTITY_ID = "sensor.mock_title_my_filter" + + +def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[str]: + """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"]) + + async_track_entity_registry_updated_event(hass, entity_id, add_event) + + return events async def test_unload_entry( @@ -16,3 +40,187 @@ async def test_unload_entry( assert await hass.config_entries.async_unload(loaded_entry.entry_id) await hass.async_block_till_done() assert loaded_entry.state is ConfigEntryState.NOT_LOADED + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_changes_source_entity_removed( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the filter entity is detached when the source device is removed.""" + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity_entry = entity_registry.async_get(FILTER_ENTITY_ID) + assert filter_entity_entry.device_id == sensor_entity_entry.device_id + + events = track_entity_registry_actions(hass, FILTER_ENTITY_ID) + + # Remove the source device, this removes the source sensor + with patch( + "homeassistant.components.filter.async_unload_entry", + wraps=filter_integration.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_remove_device(sensor_device.id) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + assert entity_registry.async_get(FILTER_ENTITY_ID).device_id is None + assert not device_registry.async_get(sensor_device.id) + assert filter_config_entry.entry_id in hass.config_entries.async_entry_ids() + assert events == ["update"] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the source device is kept when only the source entity is removed.""" + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity_entry = entity_registry.async_get(FILTER_ENTITY_ID) + assert filter_entity_entry.device_id == sensor_entity_entry.device_id + + events = track_entity_registry_actions(hass, FILTER_ENTITY_ID) + + with patch( + "homeassistant.components.filter.async_unload_entry", + wraps=filter_integration.async_unload_entry, + ) as mock_unload_entry: + entity_registry.async_remove(sensor_entity_entry.entity_id) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + assert entity_registry.async_get(FILTER_ENTITY_ID).device_id is None + sensor_device = device_registry.async_get(sensor_device.id) + assert sensor_device is not None + assert sensor_device.config_entry_id != filter_config_entry.entry_id + assert filter_config_entry.entry_id in hass.config_entries.async_entry_ids() + assert events == ["update"] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_changes_source_entity_removed_from_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the source entity removed from the source device.""" + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity_entry = entity_registry.async_get(FILTER_ENTITY_ID) + assert filter_entity_entry.device_id == sensor_entity_entry.device_id + + events = track_entity_registry_actions(hass, FILTER_ENTITY_ID) + + with patch( + "homeassistant.components.filter.async_unload_entry", + wraps=filter_integration.async_unload_entry, + ) as mock_unload_entry: + entity_registry.async_update_entity( + sensor_entity_entry.entity_id, device_id=None + ) + await hass.async_block_till_done() + mock_unload_entry.assert_called_once() + + assert entity_registry.async_get(FILTER_ENTITY_ID).device_id is None + sensor_device = device_registry.async_get(sensor_device.id) + assert sensor_device.config_entry_id != filter_config_entry.entry_id + assert filter_config_entry.entry_id in hass.config_entries.async_entry_ids() + assert events == ["update"] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_changes_source_entity_moved_other_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the filter entity follows the source entity to another device.""" + sensor_device_2 = device_registry.async_get_or_create( + config_entry_id=sensor_config_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:FF")}, + ) + + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity_entry = entity_registry.async_get(FILTER_ENTITY_ID) + assert filter_entity_entry.device_id == sensor_entity_entry.device_id + + events = track_entity_registry_actions(hass, FILTER_ENTITY_ID) + + with patch( + "homeassistant.components.filter.async_unload_entry", + wraps=filter_integration.async_unload_entry, + ) as mock_unload_entry: + entity_registry.async_update_entity( + sensor_entity_entry.entity_id, device_id=sensor_device_2.id + ) + await hass.async_block_till_done() + mock_unload_entry.assert_called_once() + + assert entity_registry.async_get(FILTER_ENTITY_ID).device_id == sensor_device_2.id + sensor_device = device_registry.async_get(sensor_device.id) + assert sensor_device.config_entry_id != filter_config_entry.entry_id + sensor_device_2 = device_registry.async_get(sensor_device_2.id) + assert sensor_device_2.config_entry_id != filter_config_entry.entry_id + assert filter_config_entry.entry_id in hass.config_entries.async_entry_ids() + assert events == ["update"] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_new_entity_id( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the source entity's entity ID is changed.""" + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity_entry = entity_registry.async_get(FILTER_ENTITY_ID) + assert filter_entity_entry.device_id == sensor_entity_entry.device_id + + events = track_entity_registry_actions(hass, FILTER_ENTITY_ID) + + with patch( + "homeassistant.components.filter.async_unload_entry", + wraps=filter_integration.async_unload_entry, + ) as mock_unload_entry: + entity_registry.async_update_entity( + sensor_entity_entry.entity_id, new_entity_id="sensor.new_entity_id" + ) + await hass.async_block_till_done() + mock_unload_entry.assert_called_once() + + assert filter_config_entry.options[CONF_ENTITY_ID] == "sensor.new_entity_id" + assert ( + hass.states.get(FILTER_ENTITY_ID).attributes[ + FilterEntityStateAttribute.ENTITY_ID + ] + == "sensor.new_entity_id" + ) + assert filter_config_entry.entry_id in hass.config_entries.async_entry_ids() + assert events == [] diff --git a/tests/components/filter/test_sensor.py b/tests/components/filter/test_sensor.py index 8cedf8da0d8e..671d9b641b2e 100644 --- a/tests/components/filter/test_sensor.py +++ b/tests/components/filter/test_sensor.py @@ -191,6 +191,51 @@ async def test_from_config_entry_duration( assert state.state == "20.0" +@pytest.mark.usefixtures("recorder_mock") +async def test_device_id( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + filter_config_entry: MockConfigEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the filter sensor is linked to the source entity's device.""" + assert await hass.config_entries.async_setup(filter_config_entry.entry_id) + await hass.async_block_till_done() + + filter_entity = entity_registry.async_get("sensor.mock_title_my_filter") + assert filter_entity is not None + assert filter_entity.device_id == sensor_entity_entry.device_id + + +@pytest.mark.usefixtures("recorder_mock") +async def test_device_id_yaml( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test no device is set for a YAML-configured filter sensor.""" + assert await async_setup_component( + hass, + "sensor", + { + "sensor": { + "platform": "filter", + "name": "test", + "unique_id": "filter_yaml", + "entity_id": sensor_entity_entry.entity_id, + "filters": [{"filter": "outlier", "window_size": 10, "radius": 4.0}], + } + }, + ) + await hass.async_block_till_done() + + filter_entity = entity_registry.async_get("sensor.test") + assert filter_entity is not None + assert filter_entity.device_id is None + assert "attempts to attach a device to an entity" not in caplog.text + + @pytest.mark.parametrize("missing", [True, False]) async def test_chain_history( recorder_mock: Recorder,