From 3526fbd9ee5228862a1a24771ee6bb2b249c1db2 Mon Sep 17 00:00:00 2001 From: Ari Date: Fri, 13 May 2022 17:15:13 -0400 Subject: [PATCH] updated api --- api/src/automations/deparser.py | 49 ---- api/src/automations/loader.py | 39 +-- api/src/automations/parsers.py | 88 ------- api/src/automations/types.py | 29 +-- api/src/json_serializer.py | 2 +- api/tests/unittests/api/test_automations.py | 187 ++++++++------- .../unittests/automations/test_loader.py | 27 +-- .../unittests/automations/test_parsers.py | 223 ------------------ 8 files changed, 137 insertions(+), 507 deletions(-) delete mode 100644 api/src/automations/deparser.py delete mode 100644 api/src/automations/parsers.py delete mode 100644 api/tests/unittests/automations/test_parsers.py diff --git a/api/src/automations/deparser.py b/api/src/automations/deparser.py deleted file mode 100644 index c715d97..0000000 --- a/api/src/automations/deparser.py +++ /dev/null @@ -1,49 +0,0 @@ - - - -from typing import Iterable, Union - -from src.automations.types import AutomationActionNode, AutomationConditionNode - - -def _deparse(nodes: Iterable[Union[AutomationActionNode, AutomationConditionNode]]) -> Iterable[dict]: - for node in nodes: - if isinstance(node, AutomationActionNode): - yield from _deparse_action(node) - elif isinstance(node, AutomationConditionNode): - yield from _deparse_condition(node) - else: - raise NotImplementedError(type(node)) - -def _deparse_action(action: AutomationActionNode) -> Iterable[dict]: - if action.action == 'repeat': - raw_data = action.action_data - repeat_data = raw_data.pop("repeat") - yield { - **raw_data, - "repeat": { - **repeat_data, - "sequence": list(_deparse(repeat_data['sequence'])) - } - } - elif action.action == 'choose': - raw_data = action.action_data - choose_data = raw_data.pop("choose") - default_data = raw_data.pop("default", []) - yield { - **raw_data, - "choose": [ - { - "conditions": list(map(_deparse_condition, option.get("conditions", []))), - "sequence": list(_deparse(option.get("sequence", []))), - } - for option in choose_data - ], - "default": list(_deparse(default_data)), - } - else: - yield action.action_data - - -def _deparse_condition(condition: AutomationConditionNode) -> Iterable[dict]: - raise NotImplementedError \ No newline at end of file diff --git a/api/src/automations/loader.py b/api/src/automations/loader.py index 94a1378..8b0ddcc 100644 --- a/api/src/automations/loader.py +++ b/api/src/automations/loader.py @@ -1,10 +1,7 @@ -from itertools import chain -from typing import Iterable, Iterator +from typing import Iterator, Union from pydantic.error_wrappers import ValidationError -from src.automations.tags import TagManager from src.json_serializer import normalize_obj -from .types import AutomationData, AutomationMetdata, ExtenededAutomationData -from .parsers import _parse_actions +from .types import AutomationMetdata, ExtenededAutomationData from .errors import InvalidAutomationFile # Single loader @@ -25,16 +22,30 @@ def load_automation( 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", [])], + condition=load_conditions(auto_raw.get("condition", [])), + sequence=load_conditions(auto_raw.get("action", [])), + trigger=normalize_obj(auto_raw.get("trigger", [])), tags=tags, ) except ValidationError as err: raise InvalidAutomationFile from err + + +def load_conditions(conditions: Union[dict, list, str]): + if isinstance(conditions, list): + return list(map(ensure_condition_dictionary, conditions)) + else: + return [ + ensure_condition_dictionary(conditions) + ] + +def ensure_condition_dictionary(c: Union[str, dict]): + c = normalize_obj(c) + if isinstance(c, str): + return { + "condition": "template", + "value_template": c + } + elif isinstance(c, dict): + return c + raise InvalidAutomationFile(f"Invalid type for condition object {c}") \ No newline at end of file diff --git a/api/src/automations/parsers.py b/api/src/automations/parsers.py deleted file mode 100644 index a875b8a..0000000 --- a/api/src/automations/parsers.py +++ /dev/null @@ -1,88 +0,0 @@ -from typing import Iterable, Union -from src.json_serializer import json_dumps, normalize_obj -from src.yaml_serializer.types import SecretValue, NOT_IMPLEMENTED_SV_MSG -from .types import AutomationActionNode, AutomationConditionNode - - -def _parse_actions( - raw_actions: Iterable[Union[dict, str]] -) -> Iterable[Union[AutomationActionNode, AutomationConditionNode]]: - for raw_c in raw_actions: - action_type = "unknown" - if isinstance(raw_c, str): - yield from _parse_conditions([raw_c]) - continue - elif isinstance(raw_c, dict): - if raw_c.get("condition"): - yield from _parse_conditions([raw_c]) - continue - elif raw_c.get("service"): - action_type = "service" - action_data = normalize_obj(raw_c) - elif raw_c.get("repeat"): - action_type = "repeat" - repeat_data = raw_c.pop("repeat") - action_data = { - **raw_c, - "repeat": { - "count": repeat_data.get("count", 0), - "sequence": list(_parse_actions(repeat_data.get("sequence", []))), - }, - } - elif raw_c.get("wait_template"): - action_type = "wait" - action_data = normalize_obj(raw_c) - elif raw_c.get("event"): - action_type = "event" - action_data = normalize_obj(raw_c) - elif raw_c.get("type") and raw_c.get("device_id"): - action_type = "device" - action_data = normalize_obj(raw_c) - elif raw_c.get("choose"): - action_type = "choose" - choose_data = raw_c.pop("choose") - default_data = raw_c.pop("default", []) - action_data = { - **raw_c, - "choose": [ - { - "conditions": list(_parse_conditions(option.get("conditions", []))), - "sequence": list(_parse_actions(option.get("sequence", []))), - } - for option in choose_data - ], - "default": list(_parse_actions(default_data)), - } - else: - action_data = normalize_obj(raw_c) - yield AutomationActionNode( - action=action_type, - action_data=action_data, - ) - - -def _parse_conditions( - raw_conditions: Iterable[Union[dict, str]] -) -> Iterable[AutomationConditionNode]: - for raw_c in raw_conditions: - if isinstance(raw_c, str): - yield AutomationConditionNode( - condition="template", - condition_data={"value_template": raw_c}, - ) - elif isinstance(raw_c, SecretValue): - yield AutomationConditionNode( - condition="template", - condition_data={"value_template": NOT_IMPLEMENTED_SV_MSG}, - ) - elif isinstance(raw_c, dict): - condition = raw_c.pop("condition") - yield AutomationConditionNode( - condition=condition, - condition_data=normalize_obj(raw_c), - ) - else: - yield AutomationConditionNode( - condition="template", - condition_data=json_dumps(raw_c), - ) diff --git a/api/src/automations/types.py b/api/src/automations/types.py index bb6b2e8..e7d7b9b 100644 --- a/api/src/automations/types.py +++ b/api/src/automations/types.py @@ -2,28 +2,6 @@ from typing import Dict, List, Literal, Optional, Union from pydantic.fields import Field from pydantic import BaseModel - -class AutomationConditionNode(BaseModel): - condition: str - condition_data: dict - node_type: Literal["condition"] = Field(alias="$smType", default="condition") - - def to_primitive(self): - return { - **self.condition_data, - "condition": self.condition, - } - - -class AutomationActionNode(BaseModel): - action: str - action_data: dict - node_type: Literal["action"] = Field(alias="$smType", default="action") - - def to_primitive(self): - return self.action_data - - class AutomationMetdata(BaseModel): id: str alias: Optional[str] = None @@ -35,14 +13,15 @@ class AutomationMetdata(BaseModel): class AutomationData(BaseModel): metadata: AutomationMetdata trigger: List[dict] = [] - sequence: List[Union[AutomationConditionNode, AutomationActionNode]] = [] + condition: List[dict] = [] + sequence: List[dict] = [] def to_primitive(self): return { **self.metadata.dict(exclude_unset=True, exclude_none=True), "trigger": self.trigger, - "condition": [], - "action": [action.to_primitive() for action in self.sequence], + "condition": self.condition, + "action": self.sequence, } class ExtenededAutomationData(AutomationData): diff --git a/api/src/json_serializer.py b/api/src/json_serializer.py index a179f53..e919d03 100644 --- a/api/src/json_serializer.py +++ b/api/src/json_serializer.py @@ -1,5 +1,5 @@ import json -from typing import Any +from typing import Any, List def json_dumps(obj: Any) -> str: diff --git a/api/tests/unittests/api/test_automations.py b/api/tests/unittests/api/test_automations.py index b924dbf..ea3fbd5 100644 --- a/api/tests/unittests/api/test_automations.py +++ b/api/tests/unittests/api/test_automations.py @@ -137,15 +137,15 @@ class automation_update_tests(BaseTestCase): self.assertListEqual(trigger, [ {"platform": "time", "at": "input_datetime.vita_night_pump_time"} ]) - self.assertListEqual(condition, []) - self.assertListEqual(action, [ - { + self.assertListEqual(condition, [{ "conditions": [ {"condition": "time", "after": "input_datetime.vita_night_pump_time", "before": "00:00:00"}, {"condition": "time", "after": "00:00:00", "before": "06:00:00"} ], "condition": "and" - }, + }, ]) + self.assertListEqual(action, [ + { "service": "light.turn_on", "target": { @@ -226,95 +226,100 @@ class automation_update_tests(BaseTestCase): ]) self.assertListEqual(condition, []) self.assertListEqual(action, [ - { - "choose": [ - { - "conditions": [ - { - "condition": "trigger", - "id": "turn_off", + { + "choose": [ + { + "conditions": [ + { + "condition": "trigger", + "id": "turn_off" + } + ], + "sequence": [ + { + "type": "turn_off", + "device_id": "das2qdasdasdasadaasd", + "entity_id": "light.bulb_ari_lamp", + "domain": "light" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "turn_on" + } + ], + "sequence": [ + { + "service": "light.turn_on", + "data": { + "color_temp": 153, + "brightness_pct": 100 + }, + "target": { + "device_id": "das2qdasdasdasadaasd" } - ], - "sequence": [ - { - "action": "device", - "type": "turn_off", - "device_id": "das2qdasdasdasadaasd", - "entity_id": "light.bulb_ari_lamp", - "domain": "light" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "dim_up" + } + ], + "sequence": [ + { + "device_id": "das2qdasdasdasadaasd", + "domain": "light", + "entity_id": "light.bulb_ari_lamp", + "type": "brightness_increase" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "dim_down" + } + ], + "sequence": [ + { + "device_id": "das2qdasdasdasadaasd", + "domain": "light", + "entity_id": "light.bulb_ari_lamp", + "type": "brightness_decrease" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "up_dbclk" + } + ], + "sequence": [ + { + "service": "light.turn_on", + "data": { + "color_temp": 500, + "brightness_pct": 100 + }, + "target": { + "device_id": "das2qdasdasdasadaasd" } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "turn_on", - } - ], - "sequence": [ - { - "action": "service", - "service": "light.turn_on", - "data": {"color_temp": 153, "brightness_pct": 100}, - "target": {"device_id": "das2qdasdasdasadaasd"} - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "dim_up", - } - ], - "sequence": [ - { - "action": "device", - "device_id": "das2qdasdasdasadaasd", - "domain": "light", - "entity_id": "light.bulb_ari_lamp", - "type": "brightness_increase" - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "dim_down", - } - ], - "sequence": [ - { - "action": "device", - "device_id": "das2qdasdasdasadaasd", - "domain": "light", - "entity_id": "light.bulb_ari_lamp", - "type": "brightness_decrease" - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "up_dbclk", - } - ], - "sequence": [ - { - "action": "service", - "service": "light.turn_on", - "data": {"color_temp": 500, "brightness_pct": 100}, - "target": {"device_id": "das2qdasdasdasadaasd"} - } - ] - } - ], - "default": [] - } - ]) + } + ] + } + ], + "default": [] + } + ]) class automation_delete_tests(BaseTestCase): def test_delete_some(self): diff --git a/api/tests/unittests/automations/test_loader.py b/api/tests/unittests/automations/test_loader.py index 37c0371..c6738ce 100644 --- a/api/tests/unittests/automations/test_loader.py +++ b/api/tests/unittests/automations/test_loader.py @@ -1,7 +1,5 @@ from unittest import TestCase from src.automations.types import ( - AutomationActionNode, - AutomationConditionNode, AutomationMetdata, ExtenededAutomationData, ) @@ -46,21 +44,18 @@ class loader_tests(TestCase): mode="single", ), trigger=[{"platform": "homeassistant", "event": "shutdown"}], + condition=[{ + "condition": "template", + "value_template": "states(time.time) >= '10:00:00'", + }], sequence=[ - AutomationConditionNode( - condition="template", - condition_data={"value_template": "states(time.time) >= '10:00:00'"}, - ), - AutomationActionNode( - action="device", - action_data={ - "device_id": NOT_IMPLEMENTED_SV_MSG, - "domain": "mobile_app", - "type": "notify", - "title": "Hassio Status", - "message": "Hassio Is turning off...", - }, - ), + { + "device_id": NOT_IMPLEMENTED_SV_MSG, + "domain": "mobile_app", + "type": "notify", + "title": "Hassio Status", + "message": "Hassio Is turning off...", + } ], tags={} ), diff --git a/api/tests/unittests/automations/test_parsers.py b/api/tests/unittests/automations/test_parsers.py deleted file mode 100644 index 04a9471..0000000 --- a/api/tests/unittests/automations/test_parsers.py +++ /dev/null @@ -1,223 +0,0 @@ -from unittest import TestCase -from src.automations.types import ( - AutomationActionNode, - AutomationConditionNode, -) -from src.automations.parsers import ( - _parse_conditions, - _parse_actions, -) -from src.yaml_serializer.types import ( - SecretValue, - NOT_IMPLEMENTED_SV_MSG, -) - - -class parser_tests(TestCase): - def test_various_condition_types(self): - raw_conditions = [ - {"condition": "template", "value_template": "silly logic here"}, - "silly logic here", - {"condition": "time", "after": "10:00:00", "weekday": ["mon", "tue"]}, - {"condition": "what is this?", "wuba": "dub"}, - SecretValue("supersecretcondition", "rm -rf ./*"), - {"condition": "and", ""} - ] - expected_process = [ - AutomationConditionNode( - condition="template", - condition_data={"value_template": "silly logic here"}, - ), - AutomationConditionNode( - condition="template", - condition_data={"value_template": "silly logic here"}, - ), - AutomationConditionNode( - condition="time", - condition_data={"after": "10:00:00", "weekday": ["mon", "tue"]}, - ), - AutomationConditionNode( - condition="what is this?", - condition_data={"wuba": "dub"}, - ), - AutomationConditionNode( - condition="template", - condition_data={"value_template": NOT_IMPLEMENTED_SV_MSG}, - ), - ] - - for expected, parsed in zip(expected_process, _parse_conditions(raw_conditions)): - self.assertEqual(parsed, expected) - - def test_various_action_types(self): - raw_conditions = [ - {"condition": "template", "value_template": "silly logic here"}, - "silly logic here", - {"condition": "time", "after": "10:00:00", "weekday": ["mon", "tue"]}, - { - "service": "light.turn_on", - "target": ["light.kitchen"], - "data": {"brightness": 10}, - }, - {"something": "is wrong"}, - { - "alias": "Doing amazing things!", - "repeat": { - "count": 1000, - "sequence": [ - "conditionA", - { - "wait_template": "states('light.kitchen') == 'off", - "timeout": 10, - }, - { - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - ], - }, - }, - {"event": "custom-event", "event_data": "wow"}, - { - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - { - "alias": "Doing amazing things!", - "choose": [ - { - "conditions": [ - r"{{ states('switch.plug_out_bug_lamp') == 'unavailable'}}", - ], - "sequence": [ - "conditionA", - { - "wait_template": "states('light.kitchen') == 'off", - "timeout": 10, - }, - { - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - ], - } - ], - "default": [{"event": "nope", "event_data": {}}], - }, - ] - expected_process = [ - AutomationConditionNode( - condition="template", - condition_data={"value_template": "silly logic here"}, - ), - AutomationConditionNode( - condition="template", - condition_data={"value_template": "silly logic here"}, - ), - AutomationConditionNode( - condition="time", - condition_data={"after": "10:00:00", "weekday": ["mon", "tue"]}, - ), - AutomationActionNode( - action="service", - action_data={ - "service": "light.turn_on", - "target": ["light.kitchen"], - "data": {"brightness": 10}, - }, - ), - AutomationActionNode(action="unknown", action_data={"something": "is wrong"}), - AutomationActionNode( - action="repeat", - action_data={ - "alias": "Doing amazing things!", - "repeat": { - "count": 1000, - "sequence": [ - AutomationConditionNode( - condition="template", - condition_data={"value_template": "conditionA"}, - ), - AutomationActionNode( - action="wait", - action_data={ - "wait_template": "states('light.kitchen') == 'off", - "timeout": 10, - }, - ), - AutomationActionNode( - action="device", - action_data={ - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - ), - ], - }, - }, - ), - AutomationActionNode( - action="event", - action_data={"event": "custom-event", "event_data": "wow"}, - ), - AutomationActionNode( - action="device", - action_data={ - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - ), - AutomationActionNode( - action="choose", - action_data={ - "alias": "Doing amazing things!", - "choose": [ - { - "conditions": [ - AutomationConditionNode( - condition="template", - condition_data={ - "value_template": r"{{ states('switch.plug_out_bug_lamp') == 'unavailable'}}" - }, - ) - ], - "sequence": [ - AutomationConditionNode( - condition="template", - condition_data={"value_template": "conditionA"}, - ), - AutomationActionNode( - action="wait", - action_data={ - "wait_template": "states('light.kitchen') == 'off", - "timeout": 10, - }, - ), - AutomationActionNode( - action="device", - action_data={ - "type": "toggle", - "domain": "light", - "device_id": "1231412", - }, - ), - ], - } - ], - "default": [ - AutomationActionNode( - action="event", - action_data={"event": "nope", "event_data": {}}, - ) - ], - }, - ), - ] - - for expected, parsed in zip(expected_process, _parse_actions(raw_conditions)): - self.assertEqual(parsed, expected)