From 1bd982668449815fee2105478569f8e4b5670add Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 1 May 2021 20:30:28 -0700 Subject: [PATCH] Handle different entity_id formats (#49969) --- homeassistant/components/recorder/__init__.py | 18 ++++++++-- tests/components/recorder/test_init.py | 35 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index b4be8852f55..a783dabdbed 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -358,13 +358,27 @@ class Recorder(threading.Thread): self._event_listener = None @callback - def _async_event_filter(self, event): + def _async_event_filter(self, event) -> bool: """Filter events.""" if event.event_type in self.exclude_t: return False entity_id = event.data.get(ATTR_ENTITY_ID) - return bool(entity_id is None or self.entity_filter(entity_id)) + + if entity_id is None: + return True + + if isinstance(entity_id, str): + return self.entity_filter(entity_id) + + if isinstance(entity_id, list): + for eid in entity_id: + if self.entity_filter(eid): + return True + return False + + # Unknown what it is. + return True def do_adhoc_purge(self, **kwargs): """Trigger an adhoc purge retaining keep_days worth of data.""" diff --git a/tests/components/recorder/test_init.py b/tests/components/recorder/test_init.py index 70271634ff5..a34df0a4ac2 100644 --- a/tests/components/recorder/test_init.py +++ b/tests/components/recorder/test_init.py @@ -931,3 +931,38 @@ async def test_database_corruption_while_running(hass, tmpdir, caplog): hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() hass.stop() + + +def test_entity_id_filter(hass_recorder): + """Test that entity ID filtering filters string and list.""" + hass = hass_recorder( + {"include": {"domains": "hello"}, "exclude": {"domains": "hidden_domain"}} + ) + + for idx, data in enumerate( + ( + {}, + {"entity_id": "hello.world"}, + {"entity_id": ["hello.world"]}, + {"entity_id": ["hello.world", "hidden_domain.person"]}, + {"entity_id": {"unexpected": "data"}}, + ) + ): + hass.bus.fire("hello", data) + wait_recording_done(hass) + + with session_scope(hass=hass) as session: + db_events = list(session.query(Events).filter_by(event_type="hello")) + assert len(db_events) == idx + 1, data + + for data in ( + {"entity_id": "hidden_domain.person"}, + {"entity_id": ["hidden_domain.person"]}, + ): + hass.bus.fire("hello", data) + wait_recording_done(hass) + + with session_scope(hass=hass) as session: + db_events = list(session.query(Events).filter_by(event_type="hello")) + # Keep referring idx + 1, as no new events are being added + assert len(db_events) == idx + 1, data