additional api refactor

This commit is contained in:
ari committed 2022-08-18 10:19:17 -04:00
1 parent 8792ed6ed8
commit 7cb1a5d907
11 files changed
+415 -271

No files matched your search

+8 -3
View File
@@ -1,9 +1,10 @@
from ctypes import Union
from fastapi import APIRouter, HTTPException
from src.api.types import ListData, ListParams, UpdateTags
from src.automations.errors import FailedDeletion
from src.automations.manager import AutomationManager
from src.automations.types import ExtenededAutomation
from src.automations.types import Automation, ExtenededAutomation
def make_automation_router(automations: AutomationManager) -> APIRouter:
@@ -22,8 +23,12 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
)
@router.post("/item")
def upsert_auto(body: ExtenededAutomation):
automations.upsert(body)
def insert_auto(body: Automation):
automations.create(body)
@router.put("/item")
def update_auto(body: ExtenededAutomation):
automations.update(body)
@router.post("/item/tags")
def update_tags(body: UpdateTags):
+5 -1
View File
@@ -2,6 +2,7 @@ from fastapi import APIRouter
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig
from src.automations.loader import extract_automation_paths
def make_details_router(hass_config: HassConfig) -> APIRouter:
@@ -15,7 +16,10 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
"hassio_url": HASSIO_WS,
"config": hass_config.get_configuration_path(),
"tags": hass_config.get_automation_tags_path(),
"autos": hass_config.get_automation_path(),
"autos": {
config_key: auto_file
for config_key, auto_file in extract_automation_paths(hass_config)
},
}
return router
+1 -1
View File
@@ -82,7 +82,7 @@ class AutomationDBConnection:
"{automation.alias}",
"{automation.description}",
"{automation.mode}",
"{automation.source_file.absolute()}",
"{automation.source_file}",
"{automation.source_file_type}",
"{automation.configuration_key}",
"{encode_auto(automation)}"
+46 -14
View File
@@ -4,7 +4,7 @@ from typing import Any, Iterator, Tuple, Union
from src.json_serializer import normalize_obj
from src.logger import get_logger
from src.utils import extract_files
from src.yaml_serializer import load_yaml
from src.yaml_serializer import dump_yaml, load_yaml
from src.yaml_serializer.types import IncludedYaml, IncludedYamlDir
from ..hass_config.loader import HassConfig
@@ -14,30 +14,62 @@ from .types import ExtenededAutomation
logger = get_logger(__file__)
AUTOMATION_CONFIGURATION_KEY = "automation shortumation"
def extract_automation_paths(
hass_config: HassConfig,
) -> Iterator[Tuple[str, Path]]:
) -> Iterator[Tuple[str, str]]:
found = False
for key, value in extract_automation_keys(hass_config):
logger.info(f"Loading automations from '{key}'")
found = True
if isinstance(value, IncludedYaml):
yield key, value.path_str
elif isinstance(value, IncludedYamlDir):
yield key, value.name
else:
logger.warning(f"found an invalid type in {key}!")
if not found:
yield "", "automations.yaml"
def get_base_automation_key(hass_config: HassConfig):
found_any = False
for key, value in extract_automation_keys(hass_config):
found_any = True
if isinstance(value, IncludedYaml):
return key, value.path_str
configurations = hass_config.configurations
if found_any:
out_path = hass_config.get_backup_automation_file_path()
else:
out_path = hass_config.get_default_automation_path()
out_file = str(out_path.relative_to(hass_config.root_path))
configurations[AUTOMATION_CONFIGURATION_KEY] = IncludedYaml(out_file)
out_path.touch(exist_ok=True)
with hass_config.get_configuration_path().open("w") as fp:
fp.write(dump_yaml(configurations))
return AUTOMATION_CONFIGURATION_KEY, out_file
def extract_automation_keys(
hass_config: HassConfig,
) -> Iterator[Tuple[str, Union[IncludedYaml, IncludedYamlDir]]]:
for key, value in hass_config.configurations.items():
if str(key).startswith("automation"):
logger.info(f"Loading automations from '{key}'")
found = True
if isinstance(value, dict):
if isinstance(value, dict) or isinstance(value, list):
raise NotImplementedError(
"No support for automations baked into configuration.yaml! Please extract these into a seperate file"
)
elif isinstance(value, IncludedYaml):
yield key, hass_config.root_path / value.path_str
elif isinstance(value, IncludedYamlDir):
yield key, hass_config.root_path / value.name
elif isinstance(value, IncludedYaml) or isinstance(value, IncludedYamlDir):
yield key, value
else:
logger.warning(f"found an invalid type in {key}!")
if not found:
yield "", hass_config.root_path / "automations.yaml"
def load_automation_path(
root_path: Path,
automation_path: Path,
configuration_key: str,
tag_manager: TagManager,
@@ -57,7 +89,7 @@ def load_automation_path(
return
if automation_path.is_dir():
for f in extract_files(automation_path):
yield from load_automation_path(f, configuration_key, tag_manager)
yield from load_automation_path(root_path, f, configuration_key, tag_manager)
else:
try:
with automation_path.open("r") as fp:
@@ -75,7 +107,7 @@ def load_automation_path(
**clean_automation(automations),
tags=tag_manager.get(automations["id"], {}),
configuration_key=configuration_key,
source_file=str(automation_path),
source_file=str(automation_path.relative_to(root_path)),
source_file_type="obj",
)
except Exception as err:
@@ -94,7 +126,7 @@ def load_automation_path(
**clean_automation(automation),
tags=tag_manager.get(automation["id"], {}),
configuration_key=configuration_key,
source_file=str(automation_path),
source_file=str(automation_path.relative_to(root_path)),
source_file_type="list",
)
except Exception as err:
+44 -18
View File
@@ -14,9 +14,9 @@ from .errors import (
DBError,
InvalidAutomationFile,
)
from .loader import extract_automation_paths, load_automation_path
from .loader import extract_automation_paths, get_base_automation_key, load_automation_path
from .tags import TagManager
from .types import ExtenededAutomation
from .types import Automation, ExtenededAutomation
logger = get_logger(__file__)
@@ -45,7 +45,14 @@ class AutomationManager:
errors = []
for config_key, p in extract_automation_paths(self.hass_config):
try:
automations = list(load_automation_path(p, config_key, self.tag_manager))
automations = list(
load_automation_path(
self.hass_config.root_path,
self.hass_config.root_path / p,
config_key,
self.tag_manager,
)
)
self.db.insert_automations(automations)
except InvalidAutomationFile as e:
logger.warning(e)
@@ -65,32 +72,45 @@ class AutomationManager:
def get(self, auto_id: str):
return self.db.get_automation(auto_id)
def upsert(self, automation: ExtenededAutomation):
if not automation.source_file.parent.exists():
automation.source_file.parent.mkdir(parents=True)
def create(self, automation: Automation):
config_key, config_path = get_base_automation_key(self.hass_config)
return self.update(
ExtenededAutomation(
**automation.dict(),
configuration_key=config_key,
source_file=config_path,
source_file_type="list",
),
create_if_not_found=True,
)
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True)
objs: Optional[Union[list, dict]] = None
if automation.source_file.exists():
with automation.source_file.open("r") as fp:
if automation_path.exists():
with automation_path.open("r") as fp:
objs = load_yaml(fp)
if automation.source_file_type == "obj":
if isinstance(objs, list):
raise AttemptingToOverwriteAnIncompatibleFileError(
f"{automation.source_file} is a list, but expected a obj for {automation}"
f"{automation_path} is a list, but expected a obj for {automation}"
)
raw_auto = automation.to_primitive(include_tags=False)
automation.source_file.write_text(dump_yaml(raw_auto))
automation_path.write_text(dump_yaml(raw_auto))
else:
if isinstance(objs, dict):
raise AttemptingToOverwriteAnIncompatibleFileError(
f"{automation.source_file} is a list, but expected a obj for {automation}"
f"{automation_path} is a list, but expected a obj for {automation}"
)
elif objs is None:
objs = []
if not isinstance(objs, list):
raise AssertionError(
f"Attemption to save automation to {automation.source_file} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
f"Attemption to save automation to {automation_path} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
)
found = False
for i, obj in enumerate(objs):
@@ -99,8 +119,13 @@ class AutomationManager:
found = True
break
if not found:
objs.append(automation.to_primitive(include_tags=False))
automation.source_file.write_text(dump_yaml(objs))
if create_if_not_found:
objs.append(automation.to_primitive(include_tags=False))
else:
raise InvalidAutomationFile(
"Could not update automations, not found in source file."
)
automation_path.write_text(dump_yaml(objs))
self.update_tags(automation.id, automation.tags)
def update_tags(self, automation_id: str, tags: Dict[str, str]):
@@ -115,18 +140,19 @@ class AutomationManager:
self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation):
automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj":
automation.source_file.unlink(missing_ok=True)
automation_path.unlink(missing_ok=True)
else:
with automation.source_file.open("r") as fp:
with automation_path.open("r") as fp:
objs = load_yaml(fp)
if not isinstance(objs, list):
raise AssertionError(
f"Attemption to save automation to {automation.source_file} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
f"Attemption to save automation to {automation_path} but encountering an invalid list yaml file. Did you modify this file prior to saving?\n{automation}"
)
kept = []
for i, obj in enumerate(objs):
if obj["id"] != automation.id:
kept.append(obj)
automation.source_file.write_text(dump_yaml(kept))
automation_path.write_text(dump_yaml(kept))
self.delete_tags(automation.id)
+14 -7
View File
@@ -20,20 +20,27 @@ class BaseAutomation(BaseModel):
return self.dict(exclude_unset=True, exclude_none=True)
class ExtenededAutomation(BaseAutomation):
source_file: Path
source_file_type: Literal["list", "obj"]
configuration_key: str
class Automation(BaseAutomation):
tags: Dict[str, str] = Field(default_factory=dict)
def to_primitive(self, include_tags: bool = False):
out = super().to_primitive()
del out["source_file"]
del out["source_file_type"]
del out["configuration_key"]
if not include_tags and out.get("tags", None) is not None:
del out["tags"]
return out
class ExtenededAutomation(Automation):
source_file: str
source_file_type: Literal["list", "obj"]
configuration_key: str
def to_primitive(self, include_tags: bool = False):
out = super().to_primitive(include_tags=include_tags)
del out["source_file"]
del out["source_file_type"]
del out["configuration_key"]
return out
def to_json(self):
return json.loads(self.json())
+14 -14
View File
@@ -19,18 +19,14 @@ class HassConfig:
def automation_tags(self) -> TagManager:
tag_path = self.get_automation_tags_path()
if not tag_path.exists():
tag_path.parent.mkdir(parents=True, exist_ok=True)
return TagManager()
else:
return TagManager.load(tag_path)
def get_automation_tags_path(self) -> Path:
return self.root_path / ".shortumations" / "tags.yaml"
def get_backup_automation_file_path(self) -> Path:
return self.get_shortumations_path() / "automations.yaml"
def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml"
def get_automation_path(self) -> Optional[Path]:
def get_default_automation_path(self) -> Optional[Path]:
"""Get Automation Path (if not included in configuration.yaml, in this case the return value is None)
Returns:
@@ -45,13 +41,17 @@ class HassConfig:
return None
return self.root_path / "automations.yaml"
def save_automations(self, automations: List[dict]):
if automation_path := self.get_automation_path():
automation_path.write_text(dump_yaml(automations))
else:
self.get_configuration_path().write_text(
dump_yaml({**self.configurations, "automation": automations})
)
def get_shortumations_path(self) -> Path:
shortumations_path = self.root_path / ".shortumations"
if not shortumations_path.exists():
shortumations_path.mkdir(parents=True, exist_ok=True)
return shortumations_path
def get_automation_tags_path(self) -> Path:
return self.get_shortumations_path() / "tags.yaml"
def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml"
def save_tags(self, tags: TagManager):
tags.save(self.get_automation_tags_path())
+250 -188
View File
@@ -5,8 +5,8 @@ import yaml
from fastapi.testclient import TestClient
from src.api.app import make_app
from src.automations.types import ExtenededAutomation
from tests.utils import HA_CONFIG2_EXAMPLE, get_example_automation_loader
from src.automations.types import Automation, ExtenededAutomation
from tests.utils import HA_CONFIG2_EXAMPLE, HA_CONFIG6_EXAMPLE, get_example_automation_loader
class BaseTestCase(TestCase):
@@ -19,7 +19,7 @@ class BaseTestCase(TestCase):
self.client = TestClient(make_app(self.automation_loader))
class automation_list_tests(BaseTestCase):
class automation_pagination_tests(BaseTestCase):
test_params = {"total": 32, "subtest2_found_items": 7, "subtest1_found_items": 10}
@@ -84,7 +84,7 @@ class automation_list_tests(BaseTestCase):
self.assertEqual(len(d["data"]), self.test_params["subtest2_found_items"])
class automation2_lists_tests(automation_list_tests):
class automation_pagination_tests_2(automation_pagination_tests):
test_params = {
"total": 1,
"subtest2_found_items": 0,
@@ -101,27 +101,189 @@ class automation2_lists_tests(automation_list_tests):
class automation_update_tests(BaseTestCase):
test_params = {
"total": 32,
"modify_item": 20,
"consitency_tests": {
1: {
"offset": 15,
"file_offset": 15,
"expected_change": {
"metadata": {
"id": "1629422438707",
"alias": "I CHANGED!",
"description": "",
"mode": "single",
},
"trigger": [{"platform": "time", "at": "input_datetime.vita_night_pump_time"}],
"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",
},
],
"action": [
{
"service": "light.turn_on",
"target": {
"entity_id": "light.bulb_staircase",
"area_id": "living_room",
},
"data": {"brightness_pct": 40, "transition": 15},
}
],
},
},
2: {
"offset": 27,
"file_offset": 27,
"expected_change": {
"metadata": {
"id": "1649947692702",
"alias": "I CHANGED!",
"description": "",
"mode": "single",
},
"trigger": [
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "turn_on",
"id": "turn_on",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "turn_off",
"id": "turn_off",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "dim_up",
"id": "dim_up",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "dim_down",
"id": "dim_down",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_double_press",
"subtype": "turn_on",
"id": "up_dbclk",
},
],
"condition": [],
"action": [
{
"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"},
}
],
},
{
"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"},
}
],
},
],
"default": [],
}
],
},
},
},
}
def test_insert_new(self):
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0})
resp = self.client.post(
"/automations/list", json={"limit": self.test_params["total"] + 1, "offset": 0}
)
autos = resp.json()["data"]
self.assertEqual(resp.json()["totalItems"], 32)
self.assertEqual(resp.json()["totalItems"], self.test_params["total"])
self.assertNotIn("i am new", set([a["id"] for a in autos]))
resp = self.client.post(
"/automations/item",
json=ExtenededAutomation(
json=Automation(
id="i am new",
configuration_key="",
source_file_type="list",
source_file=autos[0]["source_file"],
).to_json(),
).dict(),
)
self.assertEqual(resp.status_code, 200)
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 32})
resp = self.client.post(
"/automations/list", json={"limit": self.test_params["total"] + 1, "offset": 0}
)
data = resp.json()
self.assertEqual(data["totalItems"], 33)
self.assertEqual(data["data"][0]["id"], "i am new")
self.assertEqual(data["totalItems"], self.test_params["total"] + 1)
self.assertIn("i am new", set([a["id"] for a in data["data"]]))
def test_update_some(self):
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20})
resp = self.client.post(
"/automations/list", json={"limit": 1, "offset": self.test_params["modify_item"]}
)
original_auto = resp.json()["data"][0]
changed_to = ExtenededAutomation(
id=original_auto["id"],
@@ -130,12 +292,14 @@ class automation_update_tests(BaseTestCase):
source_file_type=original_auto["source_file_type"],
source_file=original_auto["source_file"],
)
resp = self.client.post(
resp = self.client.put(
"/automations/item",
json=changed_to.to_json(),
)
self.assertEqual(resp.status_code, 200)
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20})
resp = self.client.post(
"/automations/list", json={"limit": 1, "offset": self.test_params["modify_item"]}
)
new_auto = resp.json()["data"][0]
self.assertNotEqual(original_auto, new_auto)
self.assertEqual(
@@ -144,180 +308,78 @@ class automation_update_tests(BaseTestCase):
)
def test_consistent_standard_1(self):
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 15})
original_auto = resp.json()["data"][0]
original_auto["alias"] = "I CHANGED!"
resp = self.client.post(
"/automations/item",
json=original_auto,
)
self.assertEqual(resp.status_code, 200)
with (self.config_folder / "automations.yaml").open("r") as fp:
disk_data = dict(yaml.safe_load(fp)[15])
trigger = list(map(dict, disk_data.pop("trigger")))
condition = disk_data.pop("condition")
action = list(map(dict, disk_data.pop("action")))
self.assertDictEqual(
disk_data,
{"id": "1629422438707", "alias": "I CHANGED!", "description": "", "mode": "single"},
)
self.assertListEqual(
trigger, [{"platform": "time", "at": "input_datetime.vita_night_pump_time"}]
)
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": {"entity_id": "light.bulb_staircase", "area_id": "living_room"},
"data": {"brightness_pct": 40, "transition": 15},
}
],
)
for test_id, test_params in self.test_params["consitency_tests"].items():
with self.subTest(test_id=test_id):
resp = self.client.post(
"/automations/list",
json={"limit": 1, "offset": test_params["offset"]},
)
original_auto = resp.json()["data"][0]
original_auto["alias"] = "I CHANGED!"
resp = self.client.post(
"/automations/item",
json=original_auto,
)
self.assertEqual(resp.status_code, 200)
with (self.config_folder / original_auto["source_file"]).open("r") as fp:
disk_data = dict(yaml.safe_load(fp)[test_params["file_offset"]])
trigger = list(map(dict, disk_data.pop("trigger")))
condition = disk_data.pop("condition")
action = list(map(dict, disk_data.pop("action")))
self.assertDictEqual(
disk_data,
test_params["expected_change"]["metadata"],
)
self.assertListEqual(
trigger,
test_params["expected_change"]["trigger"],
)
self.assertListEqual(
condition,
test_params["expected_change"]["condition"],
)
self.assertListEqual(
action,
test_params["expected_change"]["action"],
)
def test_consistent_standard_2(self):
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 27})
original_auto = resp.json()["data"][0]
original_auto["alias"] = "I CHANGED!"
resp = self.client.post(
"/automations/item",
json=original_auto,
)
self.assertEqual(resp.status_code, 200)
with (self.config_folder / "automations.yaml").open("r") as fp:
disk_data = dict(yaml.safe_load(fp)[27])
trigger = list(map(dict, disk_data.pop("trigger")))
condition = disk_data.pop("condition")
action = list(map(dict, disk_data.pop("action")))
self.assertDictEqual(
disk_data,
{"id": "1649947692702", "alias": "I CHANGED!", "description": "", "mode": "single"},
)
self.assertListEqual(
trigger,
[
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "turn_on",
"id": "turn_on",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "turn_off",
"id": "turn_off",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "dim_up",
"id": "dim_up",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_short_press",
"subtype": "dim_down",
"id": "dim_down",
},
{
"device_id": "das2qdasdasdasadaasd",
"domain": "zha",
"platform": "device",
"type": "remote_button_double_press",
"subtype": "turn_on",
"id": "up_dbclk",
},
],
)
self.assertListEqual(condition, [])
self.assertListEqual(
action,
[
{
"choose": [
class automation_update_split_config_tests(automation_update_tests):
test_params = {
"total": 12,
"modify_item": 3,
"consitency_tests": {
1: {
"offset": 3,
"file_offset": 0,
"expected_change": {
"metadata": {
"alias": "I CHANGED!",
"description": "Example",
"id": "ui1",
"mode": "single",
},
"trigger": [{"platform": "homeassistant", "event": "start"}],
"condition": [],
"action": [
{
"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"},
}
],
},
{
"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"},
}
],
},
"service": "counter.increment",
"data": {},
"target": {"entity_id": "counter.up_times"},
}
],
"default": [],
}
],
)
},
},
},
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG6_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_delete_tests(BaseTestCase):
+4 -4
View File
@@ -22,14 +22,14 @@ class db_tests(TestWithDB):
ExtenededAutomation(
id="test",
alias="test",
source_file=Path("automation.yaml").absolute(),
source_file="automation.yaml",
source_file_type="obj",
configuration_key="automation",
),
ExtenededAutomation(
id="test2",
alias="test",
source_file=Path("automation.yaml").absolute(),
source_file="automation.yaml",
source_file_type="obj",
action=[{"event": {"nice": "one"}, "event_type": "custom"}],
configuration_key="automation",
@@ -47,14 +47,14 @@ class db_tests(TestWithDB):
ExtenededAutomation(
id="test",
alias="test",
source_file=Path("automation.yaml").absolute(),
source_file="automation.yaml",
source_file_type="obj",
configuration_key="automation",
),
ExtenededAutomation(
id="test",
alias="test",
source_file=Path("automation.yaml").absolute(),
source_file="automation.yaml",
source_file_type="obj",
action=[{"event": {"nice": "one"}, "event_type": "custom"}],
configuration_key="automation",
@@ -23,6 +23,7 @@ class loader_tests(TestCase):
def test_load_automation_list_file(self):
automations = list(
load_automation_path(
HA_CONFIG2_EXAMPLE,
HA_CONFIG2_EXAMPLE / "automations.yaml",
configuration_key="automation",
tag_manager=TagManager({"1652069225859": {"type": "routine"}}),
@@ -33,7 +34,7 @@ class loader_tests(TestCase):
automations[0],
ExtenededAutomation(
id="1652069225859",
source_file=str(HA_CONFIG2_EXAMPLE / "automations.yaml"),
source_file="automations.yaml",
source_file_type="list",
configuration_key="automation",
alias="Climate - Pref temperature ",
@@ -66,6 +67,7 @@ class loader_tests(TestCase):
def test_load_automation_obj_file(self):
automations = list(
load_automation_path(
HA_CONFIG4_EXAMPLE,
HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml",
configuration_key="automation base",
tag_manager=TagManager({"1659114647067": {"room": "laundry"}}),
@@ -76,7 +78,7 @@ class loader_tests(TestCase):
automations[0],
ExtenededAutomation(
id="1659114647067",
source_file=str(HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml"),
source_file="automations/notify_washer.yaml",
source_file_type="obj",
configuration_key="automation base",
alias="Notify Washer",
@@ -105,6 +107,7 @@ class loader_tests(TestCase):
file_path.touch()
automations = list(
load_automation_path(
file_path.parent,
file_path,
configuration_key="automation ui",
tag_manager=TagManager(),
@@ -117,6 +120,7 @@ class loader_tests(TestCase):
file_path.unlink(missing_ok=True)
automations = list(
load_automation_path(
file_path.parent,
file_path,
configuration_key="automation manual",
tag_manager=TagManager(),
+23 -19
View File
@@ -49,7 +49,7 @@ class manager_tests(TestWithDB):
automation.trigger.append(
{"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"}
)
automation_manager.upsert(automation)
automation_manager.update(automation)
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
[],
@@ -124,11 +124,11 @@ class manager_tests(TestWithDB):
self.assertFalse((config_path / "automations/include_dir_list/home/left.yaml").exists())
with self.assertRaises(DBNoAutomationFound):
automation_manager.get("newlymade")
automation_manager.upsert(
automation_manager.update(
ExtenededAutomation(
id="newlymade",
configuration_key="automation manual",
source_file=config_path / "automations/include_dir_list/home/left.yaml",
source_file="automations/include_dir_list/home/left.yaml",
source_file_type="obj",
)
)
@@ -139,7 +139,7 @@ class manager_tests(TestWithDB):
ExtenededAutomation(
id="newlymade",
configuration_key="automation manual",
source_file=config_path / "automations/include_dir_list/home/left.yaml",
source_file="automations/include_dir_list/home/left.yaml",
source_file_type="obj",
),
)
@@ -152,13 +152,14 @@ class manager_tests(TestWithDB):
)
with self.assertRaises(DBNoAutomationFound):
automation_manager.get("newlymade")
automation_manager.upsert(
automation_manager.update(
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml",
source_file="automations/include_dir_merge_list/sub/list2.yaml",
source_file_type="list",
)
),
create_if_not_found=True,
)
self.assertTrue(
(config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists()
@@ -169,7 +170,7 @@ class manager_tests(TestWithDB):
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml",
source_file="automations/include_dir_merge_list/sub/list2.yaml",
source_file_type="list",
),
)
@@ -182,13 +183,14 @@ class manager_tests(TestWithDB):
)
with self.assertRaises(DBNoAutomationFound):
automation_manager.get("newlymade")
automation_manager.upsert(
automation_manager.update(
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml",
source_file="automations/include_dir_merge_list/sub/list4.yaml",
source_file_type="list",
)
),
create_if_not_found=True,
)
self.assertTrue(
(config_path / "automations/include_dir_merge_list/sub/list4.yaml").exists()
@@ -199,7 +201,7 @@ class manager_tests(TestWithDB):
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml",
source_file="automations/include_dir_merge_list/sub/list4.yaml",
source_file_type="list",
),
)
@@ -213,13 +215,14 @@ class manager_tests(TestWithDB):
with self.assertRaises(DBNoAutomationFound):
automation_manager.get("newlymade")
with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError):
automation_manager.upsert(
automation_manager.update(
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml",
source_file="automations/include_dir_merge_list/sub/list2.yaml",
source_file_type="obj",
)
),
create_if_not_found=True,
)
automation_manager.reload()
with self.assertRaises(DBNoAutomationFound):
@@ -237,13 +240,14 @@ class manager_tests(TestWithDB):
with self.assertRaises(DBNoAutomationFound):
automation_manager.get("newlymade")
with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError):
automation_manager.upsert(
automation_manager.update(
ExtenededAutomation(
id="newlymade",
configuration_key="automation cools",
source_file=config_path / "automations/include_dir_list/home/down.yaml",
source_file="automations/include_dir_list/home/down.yaml",
source_file_type="list",
)
),
create_if_not_found=True,
)
automation_manager.reload()
with self.assertRaises(DBNoAutomationFound):
@@ -266,7 +270,7 @@ class manager_tests(TestWithDB):
},
)
auto.tags["Room"] = "Bathroom"
automation_manager.upsert(auto)
automation_manager.update(auto)
del auto
automation_manager.reload()
auto = automation_manager.get("1619371298367")