updated api for tag support
This commit is contained in:
1 parent
4f78e42699
commit
baada590c5
10 files changed
+95
-69
No files matched your search
@@ -2,7 +2,7 @@ from typing import Generic, List, TypeVar
|
||||
from pydantic import BaseModel
|
||||
from pydantic.fields import Field
|
||||
from pydantic.generics import GenericModel
|
||||
from src.automations.types import AutomationData
|
||||
from src.automations.types import ExtenededAutomationData
|
||||
|
||||
DataT = TypeVar("DataT")
|
||||
|
||||
@@ -20,7 +20,7 @@ class ListData(GenericModel, Generic[DataT]):
|
||||
|
||||
class UpdateAutoRequest(BaseModel):
|
||||
index: int = Field(description="Index of the automation to update")
|
||||
data: AutomationData
|
||||
data: ExtenededAutomationData
|
||||
|
||||
|
||||
class DeleteAutoRequest(BaseModel):
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
from itertools import chain
|
||||
from typing import Iterable, Iterator
|
||||
from pydantic.error_wrappers import ValidationError
|
||||
from src.automations.tags import TagManager
|
||||
from src.json_serializer import normalize_obj
|
||||
from .types import AutomationData, AutomationMetdata
|
||||
from .types import AutomationData, AutomationMetdata, ExtenededAutomationData
|
||||
from .parsers import _parse_actions
|
||||
from .errors import InvalidAutomationFile
|
||||
|
||||
# Single loader
|
||||
def load_automation(
|
||||
automations_raw_data: Iterable[dict],
|
||||
) -> Iterator[AutomationData]:
|
||||
auto_raw: dict,
|
||||
tags: dict,
|
||||
) -> Iterator[ExtenededAutomationData]:
|
||||
"""Converts an automation dictionary loaded directly from the config into
|
||||
several python typed objects
|
||||
|
||||
@@ -17,22 +19,22 @@ def load_automation(
|
||||
automations_raw_data (Iterable[dict])
|
||||
|
||||
Returns:
|
||||
Iterator[AutomationData]
|
||||
Iterator[ExtenededAutomationData]
|
||||
|
||||
"""
|
||||
for auto_raw in automations_raw_data:
|
||||
try:
|
||||
yield AutomationData(
|
||||
metadata=AutomationMetdata.parse_obj(auto_raw),
|
||||
sequence=list(
|
||||
_parse_actions(
|
||||
chain(
|
||||
auto_raw.get("condition", []),
|
||||
auto_raw.get("action", []),
|
||||
)
|
||||
try:
|
||||
yield ExtenededAutomationData(
|
||||
metadata=AutomationMetdata.parse_obj(auto_raw),
|
||||
sequence=list(
|
||||
_parse_actions(
|
||||
chain(
|
||||
auto_raw.get("condition", []),
|
||||
auto_raw.get("action", []),
|
||||
)
|
||||
),
|
||||
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
|
||||
)
|
||||
except ValidationError as err:
|
||||
raise InvalidAutomationFile from err
|
||||
)
|
||||
),
|
||||
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
|
||||
tags=tags,
|
||||
)
|
||||
except ValidationError as err:
|
||||
raise InvalidAutomationFile from err
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import Iterator, List, Optional
|
||||
from src.automations.errors import FailedDeletion
|
||||
from src.automations.types import AutomationData
|
||||
from src.automations.types import AutomationData, ExtenededAutomationData
|
||||
from src.hass_config.loader import HassConfig
|
||||
from .loader import load_automation
|
||||
|
||||
@@ -14,21 +14,24 @@ class AutomationManager:
|
||||
offset: int = 0,
|
||||
limit: int = 10,
|
||||
) -> Iterator[AutomationData]:
|
||||
tags = self.hass_config.automation_tags
|
||||
for i, auto in enumerate(self.hass_config.automations):
|
||||
if i < offset:
|
||||
continue
|
||||
if i >= offset + limit:
|
||||
break
|
||||
yield from load_automation([auto])
|
||||
yield from load_automation(auto, tags.get(i, {}))
|
||||
|
||||
def get(self, index: int) -> Optional[AutomationData]:
|
||||
tags = self.hass_config.automation_tags
|
||||
if index >= 0:
|
||||
for i, auto in enumerate(self.hass_config.automations):
|
||||
if i == index:
|
||||
return next(load_automation(([auto])))
|
||||
return next(load_automation(auto, tags.get(i, {})))
|
||||
return None
|
||||
|
||||
def update(self, index: int, automation: AutomationData):
|
||||
def update(self, index: int, automation: ExtenededAutomationData):
|
||||
tags = self.hass_config.automation_tags
|
||||
automations: List[dict] = []
|
||||
updated = False
|
||||
for i, orig_auto in enumerate(self.hass_config.automations):
|
||||
@@ -39,8 +42,10 @@ class AutomationManager:
|
||||
automations.append(orig_auto)
|
||||
if not updated:
|
||||
automations.append(automation.to_primitive())
|
||||
tags[index] = automation.tags
|
||||
self.hass_config.save_automations(automations)
|
||||
|
||||
self.hass_config.save_tags(tags)
|
||||
|
||||
def delete(self, index: int):
|
||||
automations: List[dict] = []
|
||||
deleted = False
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
from typing import Dict
|
||||
from src.yaml_serializer import dump_yaml, load_yaml
|
||||
|
||||
class TagManager(Dict[str, List[str]]):
|
||||
class TagManager(Dict[int, Dict[str, str]]):
|
||||
def save(self, path: Path):
|
||||
path.write_text(dump_yaml(self))
|
||||
path.write_text(dump_yaml(dict(self)))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: Path):
|
||||
|
||||
@@ -44,3 +44,6 @@ class AutomationData(BaseModel):
|
||||
"condition": [],
|
||||
"action": [action.to_primitive() for action in self.sequence],
|
||||
}
|
||||
|
||||
class ExtenededAutomationData(AutomationData):
|
||||
tags: Dict[str, str] = Field(default_factory=dict)
|
||||
@@ -1,5 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from src.automations.tags import TagManager
|
||||
|
||||
from src.yaml_serializer import load_yaml, dump_yaml
|
||||
from src.yaml_serializer.types import IncludedYaml
|
||||
@@ -24,6 +25,18 @@ class HassConfig:
|
||||
except FileNotFoundError as err:
|
||||
raise MissingFile("automations.yaml") from err
|
||||
return self.configurations["automation"]
|
||||
|
||||
@property
|
||||
def automation_tags(self) -> TagManager:
|
||||
tag_path = self.get_automation_tags_path()
|
||||
if not tag_path.exists():
|
||||
return TagManager()
|
||||
else:
|
||||
return TagManager.load(tag_path)
|
||||
|
||||
|
||||
def get_automation_tags_path(self) -> Path:
|
||||
return self.root_path / "_shortu_automation_tags.yaml"
|
||||
|
||||
def get_configuration_path(self) -> Path:
|
||||
return self.root_path / "configuration.yaml"
|
||||
@@ -50,3 +63,6 @@ class HassConfig:
|
||||
self.get_configuration_path().write_text(
|
||||
dump_yaml({**self.configurations, "automation": automations})
|
||||
)
|
||||
|
||||
def save_tags(self, tags: TagManager):
|
||||
tags.save(self.get_automation_tags_path())
|
||||
@@ -1,7 +1,7 @@
|
||||
from unittest import TestCase
|
||||
from fastapi.testclient import TestClient
|
||||
from src.api.app import make_app
|
||||
from src.automations.types import AutomationData, AutomationMetdata
|
||||
from src.automations.types import AutomationData, AutomationMetdata, ExtenededAutomationData
|
||||
from tests.utils import get_example_automation_loader
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ class automation_update_tests(BaseTestCase):
|
||||
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20})
|
||||
new_auto = resp.json()["data"][0]
|
||||
self.assertNotEqual(original_auto, new_auto)
|
||||
self.assertEqual(AutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto)
|
||||
self.assertEqual(ExtenededAutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto)
|
||||
|
||||
|
||||
class automation_delete_tests(BaseTestCase):
|
||||
|
||||
@@ -2,8 +2,8 @@ from unittest import TestCase
|
||||
from src.automations.types import (
|
||||
AutomationActionNode,
|
||||
AutomationConditionNode,
|
||||
AutomationData,
|
||||
AutomationMetdata,
|
||||
ExtenededAutomationData,
|
||||
)
|
||||
from src.automations.loader import load_automation
|
||||
from src.yaml_serializer.types import (
|
||||
@@ -16,30 +16,29 @@ class loader_tests(TestCase):
|
||||
def test_load_automation_runs(self):
|
||||
auto = list(
|
||||
load_automation(
|
||||
[
|
||||
{
|
||||
"id": "1616887975473",
|
||||
"alias": "Home Assistant Off",
|
||||
"description": "",
|
||||
"trigger": [{"platform": "homeassistant", "event": "shutdown"}],
|
||||
"condition": ["states(time.time) >= '10:00:00'"],
|
||||
"action": [
|
||||
{
|
||||
"device_id": SecretValue("my_mobile_phone", "..."),
|
||||
"domain": "mobile_app",
|
||||
"type": "notify",
|
||||
"title": "Hassio Status",
|
||||
"message": "Hassio Is turning off...",
|
||||
}
|
||||
],
|
||||
"mode": "single",
|
||||
}
|
||||
]
|
||||
{
|
||||
"id": "1616887975473",
|
||||
"alias": "Home Assistant Off",
|
||||
"description": "",
|
||||
"trigger": [{"platform": "homeassistant", "event": "shutdown"}],
|
||||
"condition": ["states(time.time) >= '10:00:00'"],
|
||||
"action": [
|
||||
{
|
||||
"device_id": SecretValue("my_mobile_phone", "..."),
|
||||
"domain": "mobile_app",
|
||||
"type": "notify",
|
||||
"title": "Hassio Status",
|
||||
"message": "Hassio Is turning off...",
|
||||
}
|
||||
],
|
||||
"mode": "single",
|
||||
},
|
||||
{}
|
||||
)
|
||||
)
|
||||
self.assertEqual(
|
||||
auto[0],
|
||||
AutomationData(
|
||||
ExtenededAutomationData(
|
||||
metadata=AutomationMetdata(
|
||||
id="1616887975473",
|
||||
alias="Home Assistant Off",
|
||||
@@ -63,5 +62,6 @@ class loader_tests(TestCase):
|
||||
},
|
||||
),
|
||||
],
|
||||
tags={}
|
||||
),
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
from unittest import TestCase
|
||||
from src.automations.errors import FailedDeletion, InvalidAutomationFile
|
||||
from src.automations.types import AutomationData, AutomationMetdata
|
||||
from src.automations.types import AutomationMetdata, ExtenededAutomationData
|
||||
from tests.utils import (
|
||||
get_dummy_automation_loader,
|
||||
get_example_automation_loader,
|
||||
@@ -43,7 +43,7 @@ class manager_tests(TestCase):
|
||||
[],
|
||||
automation_in_conifguration_mode="none",
|
||||
)
|
||||
manager.update(1, AutomationData(metadata=AutomationMetdata(id="test1")))
|
||||
manager.update(1, ExtenededAutomationData(metadata=AutomationMetdata(id="test1")))
|
||||
auto = manager.get(0)
|
||||
self.assertIsNotNone(auto)
|
||||
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
||||
@@ -51,7 +51,7 @@ class manager_tests(TestCase):
|
||||
def test_create_automation_with_example_folder(self):
|
||||
_, _, manager = get_example_automation_loader()
|
||||
self.assertEqual(manager.get_total_items(), 28)
|
||||
manager.update(32, AutomationData(metadata=AutomationMetdata(id="test1")))
|
||||
manager.update(32, ExtenededAutomationData(metadata=AutomationMetdata(id="test1")))
|
||||
auto = manager.get(28)
|
||||
self.assertIsNotNone(auto)
|
||||
self.assertEqual(manager.get_total_items(), 29)
|
||||
@@ -60,24 +60,24 @@ class manager_tests(TestCase):
|
||||
def test_update_automation(self):
|
||||
_, _, manager = get_dummy_automation_loader(
|
||||
[
|
||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
],
|
||||
automation_in_conifguration_mode="none",
|
||||
)
|
||||
auto = manager.get(0)
|
||||
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
||||
manager.update(0, AutomationData(metadata=AutomationMetdata(id="toaster-7")))
|
||||
manager.update(0, ExtenededAutomationData(metadata=AutomationMetdata(id="toaster-7")))
|
||||
auto = manager.get(0)
|
||||
self.assertEqual(auto.metadata.id, "toaster-7") # type: ignore
|
||||
|
||||
def test_delete_automation(self):
|
||||
_, _, manager = get_dummy_automation_loader(
|
||||
[
|
||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
],
|
||||
automation_in_conifguration_mode="none",
|
||||
)
|
||||
@@ -90,9 +90,9 @@ class manager_tests(TestCase):
|
||||
def test_failed_deletion_automation(self):
|
||||
_, _, manager = get_dummy_automation_loader(
|
||||
[
|
||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||
],
|
||||
automation_in_conifguration_mode="none",
|
||||
)
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from tempfile import mktemp
|
||||
from unittest import TestCase
|
||||
from src.automations.tags import TagManager
|
||||
|
||||
class tag_tests(TestCase):
|
||||
|
||||
def test_load_and_save(self):
|
||||
tmp_file = Path(mkdtemp())
|
||||
tmp_file = Path(mktemp()).with_suffix('.yml')
|
||||
tags = TagManager()
|
||||
tags['id#1'] = ['home things', 'barns', 'kitchen']
|
||||
tags['id#2'] = ['kitchen']
|
||||
tags[0] = {'Room': "Kitchen", "Type": 'Lights'}
|
||||
tags[1] = {}
|
||||
|
||||
tags.save(tmp_file)
|
||||
loaded_tags = TagManager.load(tmp_file)
|
||||
|
||||
Reference in new issue
Block a user