Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use index to query available entities #79

Merged
merged 1 commit into from
Dec 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions detective/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,28 @@ def perform_query(self, query):
raise

def fetch_entities(self):
"""Fetch unique entities which have data (COUNT>0)."""
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id, COUNT(*)
SELECT entity_id
FROM states
GROUP BY entity_id
ORDER by 2 DESC
"""
)
response = self.perform_query(query)
entities = [e[0] for e in list(response)]
print("There are {} entities with data".format(len(entities)))

# Parse the domains from the entities.
self._domains = list(set([e.split(".")[0] for e in entities]))
self._entities = {}
entities = {}
domains = set()

for [entity] in response:
domain = entity.split('.')[0]
domains.add(domain)
entities.setdefault(domain, []).append(entity)

# Parse entities into a dict indexed by domain.
for d in self._domains:
self._entities[d] = [e for e in entities if e.split(".")[0] == d]
self._domains = list(domains)
self._entities = entities
print("There are {} entities with data".format(len(entities)))

def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
Expand Down
11 changes: 11 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from unittest.mock import patch

import pytest

from detective.core import HassDatabase


@pytest.fixture
def mock_db():
with patch('detective.core.create_engine'):
return HassDatabase('mock://db')
16 changes: 16 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from unittest.mock import patch

from detective.core import get_db_type, stripped_db_url


Expand All @@ -12,3 +14,17 @@ def test_stripped_db_url():
'mysql://paulus@localhost'
assert stripped_db_url('mysql://paulus:password@localhost') == \
'mysql://paulus:***@localhost'


def test_fetch_entities(mock_db):
with patch.object(mock_db, 'perform_query', return_value=[
['light.kitchen'],
['light.living_room'],
['switch.ac'],
]):
mock_db.fetch_entities()

assert mock_db.entities == {
'light': ['light.kitchen', 'light.living_room'],
'switch': ['switch.ac'],
}