From 55ea1e23a4a70b20d2dd5511c148506cae685260 Mon Sep 17 00:00:00 2001 From: Ari Date: Mon, 15 Aug 2022 21:56:48 -0400 Subject: [PATCH] backend modified --- api/src/api/routes/automations.py | 19 +- api/src/api/types.py | 11 +- api/src/{automations_v2 => automations}/db.py | 0 api/src/automations/errors.py | 16 + api/src/automations/loader.py | 126 +++++- api/src/automations/manager.py | 184 +++++--- api/src/automations/tags.py | 2 + api/src/automations/types.py | 36 +- api/src/automations_v2/__init__.py | 0 api/src/automations_v2/errors.py | 29 -- api/src/automations_v2/loader.py | 140 ------ api/src/automations_v2/manager.py | 132 ------ api/src/automations_v2/tags.py | 16 - api/src/automations_v2/types.py | 35 -- api/src/hass_config/loader.py | 10 - api/tests/unittests/api/test_automations.py | 54 ++- .../test_db.py | 2 +- .../unittests/automations/test_loader.py | 166 ++++++-- .../unittests/automations/test_manager.py | 398 +++++++++++++----- .../{automations_v2 => automations}/utils.py | 2 +- .../unittests/automations_v2/__init__.py | 0 .../unittests/automations_v2/test_loader.py | 139 ------ .../unittests/automations_v2/test_manager.py | 323 -------------- .../unittests/automations_v2/test_tags.py | 17 - .../unittests/hass_config/test_loader.py | 15 +- api/tests/utils.py | 10 +- 26 files changed, 737 insertions(+), 1145 deletions(-) rename api/src/{automations_v2 => automations}/db.py (100%) delete mode 100644 api/src/automations_v2/__init__.py delete mode 100644 api/src/automations_v2/errors.py delete mode 100644 api/src/automations_v2/loader.py delete mode 100644 api/src/automations_v2/manager.py delete mode 100644 api/src/automations_v2/tags.py delete mode 100644 api/src/automations_v2/types.py rename api/tests/unittests/{automations_v2 => automations}/test_db.py (97%) rename api/tests/unittests/{automations_v2 => automations}/utils.py (87%) delete mode 100644 api/tests/unittests/automations_v2/__init__.py delete mode 100644 api/tests/unittests/automations_v2/test_loader.py delete mode 100644 api/tests/unittests/automations_v2/test_manager.py delete mode 100644 api/tests/unittests/automations_v2/test_tags.py diff --git a/api/src/api/routes/automations.py b/api/src/api/routes/automations.py index 7f5e99b..5d4b754 100644 --- a/api/src/api/routes/automations.py +++ b/api/src/api/routes/automations.py @@ -1,43 +1,42 @@ from fastapi import APIRouter, HTTPException from src.api.types import ( - DeleteAutoRequest, ListData, ListParams, - UpdateAutoRequest, UpdateTags, ) from src.automations.errors import FailedDeletion from src.automations.manager import AutomationManager -from src.automations.types import AutomationData +from src.automations.types import ExtenededAutomation def make_automation_router(automations: AutomationManager) -> APIRouter: router = APIRouter() @router.post("/list") - def list_autos(body: ListParams) -> ListData[AutomationData]: + def list_autos(body: ListParams) -> ListData[ExtenededAutomation]: + automations.reload() return ListData( params=body, - totalItems=automations.get_total_items(), - data=automations.find( + totalItems=automations.count(), + data=automations.list( offset=body.offset, limit=body.limit, ), ) @router.post("/item") - def upsert_auto(body: UpdateAutoRequest): - automations.update(body.index, body.data) + def upsert_auto(body: ExtenededAutomation): + automations.upsert(body) @router.post("/item/tags") def update_tags(body: UpdateTags): automations.update_tags(body.automation_id, body.tags) @router.delete("/item") - def delete_auto(body: DeleteAutoRequest): + def delete_auto(body: ExtenededAutomation): try: - automations.delete(body.index) + automations.delete(body) except FailedDeletion as err: return HTTPException( status_code=400, diff --git a/api/src/api/types.py b/api/src/api/types.py index 060e3a9..e4ed78d 100644 --- a/api/src/api/types.py +++ b/api/src/api/types.py @@ -4,7 +4,7 @@ from pydantic import BaseModel from pydantic.fields import Field from pydantic.generics import GenericModel -from src.automations.types import ExtenededAutomationData +from src.automations.types import ExtenededAutomation DataT = TypeVar("DataT") @@ -20,15 +20,6 @@ class ListData(GenericModel, Generic[DataT]): data: List[DataT] -class UpdateAutoRequest(BaseModel): - index: int = Field(description="Index of the automation to update") - data: ExtenededAutomationData - - class UpdateTags(BaseModel): automation_id: str = Field(description="Automation Id to update") tags: Dict[str, str] - - -class DeleteAutoRequest(BaseModel): - index: int = Field(description="Index of the automation to update") diff --git a/api/src/automations_v2/db.py b/api/src/automations/db.py similarity index 100% rename from api/src/automations_v2/db.py rename to api/src/automations/db.py diff --git a/api/src/automations/errors.py b/api/src/automations/errors.py index 439f1cb..b81777e 100644 --- a/api/src/automations/errors.py +++ b/api/src/automations/errors.py @@ -5,9 +5,25 @@ class AutomationLoaderException(Exception): ) +class AttemptingToOverwriteAnIncompatibleFileError(AutomationLoaderException): + pass + + class InvalidAutomationFile(AutomationLoaderException): pass class FailedDeletion(AutomationLoaderException): pass + + +class DBError(Exception): + pass + + +class DBDataError(DBError): + pass + + +class DBNoAutomationFound(DBError): + pass diff --git a/api/src/automations/loader.py b/api/src/automations/loader.py index d9df413..1f1bb4d 100644 --- a/api/src/automations/loader.py +++ b/api/src/automations/loader.py @@ -1,38 +1,118 @@ -from typing import Any, Iterator, Union - -from pydantic.error_wrappers import ValidationError +from pathlib import Path +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.types import IncludedYaml, IncludedYamlDir +from ..hass_config.loader import HassConfig from .errors import InvalidAutomationFile -from .types import AutomationMetdata, ExtenededAutomationData +from .tags import TagManager +from .types import ExtenededAutomation + +logger = get_logger(__file__) -# Single loader -def load_automation( - auto_raw: dict, - tags: dict, -) -> Iterator[ExtenededAutomationData]: - """Converts an automation dictionary loaded directly from the config into - several python typed objects +def extract_automation_paths( + hass_config: HassConfig, +) -> Iterator[Tuple[str, Path]]: + found = False + 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): + 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 + else: + logger.warning(f"found an invalid type in {key}!") + if not found: + yield "", hass_config.root_path / "automations.yaml" + + +def load_automation_path( + automation_path: Path, + configuration_key: str, + tag_manager: TagManager, +) -> Iterator[ExtenededAutomation]: + """ Args: - automations_raw_data (Iterable[dict]) + automation_path (Path) + configuration_key (str) Returns: - Iterator[ExtenededAutomationData] + Iterator[ExtenededAutomation] """ - try: - yield ExtenededAutomationData( - metadata=AutomationMetdata.parse_obj(auto_raw), - condition=ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), - sequence=ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), - trigger=ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), - tags=tags, - ) - except ValidationError as err: - raise InvalidAutomationFile from err + if not automation_path.exists(): + logger.warning(f"the file {automation_path} does not exists") + return + if automation_path.is_dir(): + for f in extract_files(automation_path): + yield from load_automation_path(f, configuration_key, tag_manager) + else: + try: + with automation_path.open("r") as fp: + automations = load_yaml(fp) + except Exception as err: + raise InvalidAutomationFile( + when="loading yaml", + automation_path=automation_path, + error=err, + ) from err + + if isinstance(automations, dict): + try: + yield ExtenededAutomation( + **clean_automation(automations), + tags=tag_manager.get(automations["id"], {}), + configuration_key=configuration_key, + source_file=str(automation_path), + source_file_type="obj", + ) + except Exception as err: + raise InvalidAutomationFile( + when="reading file contents", + automation_path=automation_path, + error=err, + ) from err + else: + if automations is None: + logger.warning(f"the file {automation_path} is empty") + return + for automation in automations: + try: + yield ExtenededAutomation( + **clean_automation(automation), + tags=tag_manager.get(automation["id"], {}), + configuration_key=configuration_key, + source_file=str(automation_path), + source_file_type="list", + ) + except Exception as err: + raise InvalidAutomationFile( + when="reading file contents", + automation_path=automation_path, + error=err, + automation=automation, + ) from err + + +def clean_automation(auto_raw: dict): + return { + **auto_raw, + "condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), + "action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), + "trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), + } def ifempty_or_null_then_list(obj: Any): diff --git a/api/src/automations/manager.py b/api/src/automations/manager.py index 2a77a29..45efd95 100644 --- a/api/src/automations/manager.py +++ b/api/src/automations/manager.py @@ -1,76 +1,132 @@ -from typing import Dict, Iterator, List, Optional +from enum import auto +from pathlib import Path +from tempfile import mktemp +from typing import Dict, Optional, Union -from src.automations.errors import FailedDeletion, InvalidAutomationFile -from src.automations.types import AutomationData, ExtenededAutomationData from src.hass_config.loader import HassConfig +from src.yaml_serializer import dump_yaml, load_yaml -from .loader import load_automation +from ..errors import ErrorSet +from ..logger import get_logger +from .db import AutomationDBConnection +from .errors import ( + AttemptingToOverwriteAnIncompatibleFileError, + DBError, + InvalidAutomationFile, +) +from .loader import extract_automation_paths, load_automation_path +from .tags import TagManager +from .types import ExtenededAutomation + +logger = get_logger(__file__) class AutomationManager: - def __init__(self, hass_config: HassConfig) -> None: - self.hass_config = hass_config - - def find( + def __init__( self, - 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, tags.get(auto.get("id", ""), {})) + hass_config: HassConfig, + db_path: Optional[Path] = None, + ) -> None: + if db_path is None: + db_path = Path(mktemp()) + self.hass_config = hass_config + self.db = AutomationDBConnection(db_path) + self.tag_path = hass_config.get_automation_tags_path() + self.tag_manager = TagManager() + self.reload_tags() - def get(self, index: int) -> Optional[ExtenededAutomationData]: - tags = self.hass_config.automation_tags - if index >= 0: - for i, auto in enumerate(self.hass_config.automations): - if not isinstance(auto, dict): - raise InvalidAutomationFile(automation_index=i) - if i == index: - return next(load_automation(auto, tags.get(auto.get("id", ""), {}))) - return None + def reload_tags(self): + if self.tag_path.exists(): + self.tag_manager = TagManager.load(self.tag_path) - def update(self, index: int, automation: ExtenededAutomationData): - tags = self.hass_config.automation_tags - automations: List[dict] = [] - updated_index: Optional[int] = None - for i, orig_auto in enumerate(self.hass_config.automations): - if i == index: - automations.append(automation.to_primitive()) - updated_index = i - else: - automations.append(orig_auto) - if updated_index is None: - automations.append(automation.to_primitive()) - updated_index = len(automations) - 1 - tags[automation.metadata.id] = automation.tags - self.hass_config.save_automations(automations) - self.hass_config.save_tags(tags) + def reload(self): + self.db.reset() + self.reload_tags() + errors = [] + for config_key, p in extract_automation_paths(self.hass_config): + try: + automations = list(load_automation_path(p, config_key, self.tag_manager)) + self.db.upsert_automations(automations) + except InvalidAutomationFile as e: + logger.warning(e) + errors.append(e) + except DBError as e: + logger.warning(e) + errors.append(e) + if len(errors) > 0: + raise ErrorSet(*errors) - def update_tags(self, auto_id: str, tags: Dict[str, str]): - autos_tags = self.hass_config.automation_tags - autos_tags[auto_id] = tags - self.hass_config.save_tags(autos_tags) + def list(self, offset: int, limit: int): + return self.db.list_automations(offset=offset, limit=limit) - def delete(self, index: int): - automations: List[dict] = [] - deleted = False - for i, orig_auto in enumerate(self.hass_config.automations): - if i == index: - deleted = True - else: - automations.append(orig_auto) - if not deleted: - raise FailedDeletion("No such automation found") - self.hass_config.save_automations(automations) + def count(self): + return self.db.count_automations() - # TODO: improve on this without keeping things in memory - def get_total_items(self) -> int: - count = 0 - for i, _ in enumerate(self.hass_config.automations): - count = i - return count + 1 + 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) + + objs: Optional[Union[list, dict]] = None + if automation.source_file.exists(): + with automation.source_file.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}" + ) + raw_auto = automation.to_primitive(include_tags=False) + automation.source_file.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}" + ) + 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}" + ) + found = False + for i, obj in enumerate(objs): + if obj["id"] == automation.id: + objs[i] = automation.to_primitive(include_tags=False) + found = True + break + if not found: + objs.append(automation.to_primitive(include_tags=False)) + automation.source_file.write_text(dump_yaml(objs)) + self.update_tags(automation.id, automation.tags) + + def update_tags(self, automation_id: str, tags: Dict[str, str]): + self.reload_tags() + self.tag_manager[automation_id] = tags + self.tag_manager.save(self.tag_path) + + def delete_tags(self, automation_id: str): + self.reload_tags() + if automation_id in self.tag_manager: + del self.tag_manager[automation_id] + self.tag_manager.save(self.tag_path) + + def delete(self, automation: ExtenededAutomation): + if automation.source_file_type == "obj": + automation.source_file.unlink(missing_ok=True) + else: + with automation.source_file.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}" + ) + kept = [] + for i, obj in enumerate(objs): + if obj["id"] != automation.id: + kept.append(obj) + automation.source_file.write_text(dump_yaml(kept)) + self.delete_tags(automation.id) diff --git a/api/src/automations/tags.py b/api/src/automations/tags.py index c71d53d..4f0e55d 100644 --- a/api/src/automations/tags.py +++ b/api/src/automations/tags.py @@ -6,6 +6,8 @@ from src.yaml_serializer import dump_yaml, load_yaml class TagManager(Dict[str, Dict[str, str]]): def save(self, path: Path): + if not path.parent.exists(): + path.parent.mkdir(parents=True) path.write_text(dump_yaml(dict(self))) @classmethod diff --git a/api/src/automations/types.py b/api/src/automations/types.py index c027846..45f10d4 100644 --- a/api/src/automations/types.py +++ b/api/src/automations/types.py @@ -1,31 +1,39 @@ -from typing import Dict, List, Optional, Union +import json +from pathlib import Path +from typing import Dict, List, Literal, Optional, Union from pydantic import BaseModel from pydantic.fields import Field -class AutomationMetdata(BaseModel): +class BaseAutomation(BaseModel): id: str alias: Optional[str] = None description: Optional[str] = None trigger_variables: Optional[Dict[str, Union[str, int, bool, float]]] = None mode: str = "single" - - -class AutomationData(BaseModel): - metadata: AutomationMetdata trigger: List[dict] = [] condition: List[dict] = [] - sequence: List[dict] = [] + action: List[dict] = [] def to_primitive(self): - return { - **self.metadata.dict(exclude_unset=True, exclude_none=True), - "trigger": self.trigger, - "condition": self.condition, - "action": self.sequence, - } + return self.dict(exclude_unset=True, exclude_none=True) -class ExtenededAutomationData(AutomationData): +class ExtenededAutomation(BaseAutomation): + source_file: Path + source_file_type: Literal["list", "obj"] + configuration_key: str 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 + + def to_json(self): + return json.loads(self.json()) diff --git a/api/src/automations_v2/__init__.py b/api/src/automations_v2/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/src/automations_v2/errors.py b/api/src/automations_v2/errors.py deleted file mode 100644 index b81777e..0000000 --- a/api/src/automations_v2/errors.py +++ /dev/null @@ -1,29 +0,0 @@ -class AutomationLoaderException(Exception): - def __init__(self, *args: object, **kwargs) -> None: - super().__init__( - "".join(map(str, args)) + ",".join((f"{k}={v}" for k, v in kwargs.items())), - ) - - -class AttemptingToOverwriteAnIncompatibleFileError(AutomationLoaderException): - pass - - -class InvalidAutomationFile(AutomationLoaderException): - pass - - -class FailedDeletion(AutomationLoaderException): - pass - - -class DBError(Exception): - pass - - -class DBDataError(DBError): - pass - - -class DBNoAutomationFound(DBError): - pass diff --git a/api/src/automations_v2/loader.py b/api/src/automations_v2/loader.py deleted file mode 100644 index 1f1bb4d..0000000 --- a/api/src/automations_v2/loader.py +++ /dev/null @@ -1,140 +0,0 @@ -from pathlib import Path -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.types import IncludedYaml, IncludedYamlDir - -from ..hass_config.loader import HassConfig -from .errors import InvalidAutomationFile -from .tags import TagManager -from .types import ExtenededAutomation - -logger = get_logger(__file__) - - -def extract_automation_paths( - hass_config: HassConfig, -) -> Iterator[Tuple[str, Path]]: - found = False - 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): - 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 - else: - logger.warning(f"found an invalid type in {key}!") - if not found: - yield "", hass_config.root_path / "automations.yaml" - - -def load_automation_path( - automation_path: Path, - configuration_key: str, - tag_manager: TagManager, -) -> Iterator[ExtenededAutomation]: - """ - - Args: - automation_path (Path) - configuration_key (str) - - Returns: - Iterator[ExtenededAutomation] - - """ - if not automation_path.exists(): - logger.warning(f"the file {automation_path} does not exists") - return - if automation_path.is_dir(): - for f in extract_files(automation_path): - yield from load_automation_path(f, configuration_key, tag_manager) - else: - try: - with automation_path.open("r") as fp: - automations = load_yaml(fp) - except Exception as err: - raise InvalidAutomationFile( - when="loading yaml", - automation_path=automation_path, - error=err, - ) from err - - if isinstance(automations, dict): - try: - yield ExtenededAutomation( - **clean_automation(automations), - tags=tag_manager.get(automations["id"], {}), - configuration_key=configuration_key, - source_file=str(automation_path), - source_file_type="obj", - ) - except Exception as err: - raise InvalidAutomationFile( - when="reading file contents", - automation_path=automation_path, - error=err, - ) from err - else: - if automations is None: - logger.warning(f"the file {automation_path} is empty") - return - for automation in automations: - try: - yield ExtenededAutomation( - **clean_automation(automation), - tags=tag_manager.get(automation["id"], {}), - configuration_key=configuration_key, - source_file=str(automation_path), - source_file_type="list", - ) - except Exception as err: - raise InvalidAutomationFile( - when="reading file contents", - automation_path=automation_path, - error=err, - automation=automation, - ) from err - - -def clean_automation(auto_raw: dict): - return { - **auto_raw, - "condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), - "action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), - "trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), - } - - -def ifempty_or_null_then_list(obj: Any): - if not isinstance(obj, list): - return [] - else: - return obj - - -def load_conditions(conditions: Union[dict, list, str]): - if isinstance(conditions, list): - return list(map(ensure_condition_dictionary, conditions)) - elif not conditions: - return [] - 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}") diff --git a/api/src/automations_v2/manager.py b/api/src/automations_v2/manager.py deleted file mode 100644 index d786e48..0000000 --- a/api/src/automations_v2/manager.py +++ /dev/null @@ -1,132 +0,0 @@ -from enum import auto -from pathlib import Path -from tempfile import mktemp -from typing import Optional, Union - -from src.hass_config.loader import HassConfig -from src.yaml_serializer import dump_yaml, load_yaml - -from ..errors import ErrorSet -from ..logger import get_logger -from .db import AutomationDBConnection -from .errors import ( - AttemptingToOverwriteAnIncompatibleFileError, - DBError, - InvalidAutomationFile, -) -from .loader import extract_automation_paths, load_automation_path -from .tags import TagManager -from .types import ExtenededAutomation - -logger = get_logger(__file__) - - -class AutomationManager: - def __init__( - self, - hass_config: HassConfig, - db_path: Optional[Path] = None, - ) -> None: - if db_path is None: - db_path = Path(mktemp()) - self.hass_config = hass_config - self.db = AutomationDBConnection(db_path) - self.tag_path = hass_config.get_automation_tags_path() - self.tag_manager = TagManager() - self.reload_tags() - - def reload_tags(self): - if self.tag_path.exists(): - self.tag_manager = TagManager.load(self.tag_path) - - def reload(self): - self.db.reset() - self.reload_tags() - errors = [] - for config_key, p in extract_automation_paths(self.hass_config): - try: - automations = list(load_automation_path(p, config_key, self.tag_manager)) - self.db.upsert_automations(automations) - except InvalidAutomationFile as e: - logger.warning(e) - errors.append(e) - except DBError as e: - logger.warning(e) - errors.append(e) - if len(errors) > 0: - raise ErrorSet(*errors) - - def list(self, offset: int, limit: int): - return self.db.list_automations(offset=offset, limit=limit) - - def count(self): - return self.db.count_automations() - - 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) - - objs: Optional[Union[list, dict]] = None - if automation.source_file.exists(): - with automation.source_file.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}" - ) - raw_auto = automation.to_primitive(include_tags=False) - automation.source_file.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}" - ) - 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}" - ) - found = False - for i, obj in enumerate(objs): - if obj["id"] == automation.id: - objs[i] = automation.to_primitive(include_tags=False) - found = True - break - if not found: - objs.append(automation.to_primitive(include_tags=False)) - automation.source_file.write_text(dump_yaml(objs)) - self.update_tags(automation) - - def update_tags(self, automation: ExtenededAutomation): - self.reload_tags() - self.tag_manager[automation.id] = automation.tags - self.tag_manager.save(self.tag_path) - - def delete_tags(self, automation_id: str): - self.reload_tags() - if automation_id in self.tag_manager: - del self.tag_manager[automation_id] - self.tag_manager.save(self.tag_path) - - def delete(self, automation: ExtenededAutomation): - if automation.source_file_type == "obj": - automation.source_file.unlink(missing_ok=True) - else: - with automation.source_file.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}" - ) - kept = [] - for i, obj in enumerate(objs): - if obj["id"] != automation.id: - kept.append(obj) - automation.source_file.write_text(dump_yaml(kept)) - self.delete_tags(automation.id) diff --git a/api/src/automations_v2/tags.py b/api/src/automations_v2/tags.py deleted file mode 100644 index 4f0e55d..0000000 --- a/api/src/automations_v2/tags.py +++ /dev/null @@ -1,16 +0,0 @@ -from pathlib import Path -from typing import Dict - -from src.yaml_serializer import dump_yaml, load_yaml - - -class TagManager(Dict[str, Dict[str, str]]): - def save(self, path: Path): - if not path.parent.exists(): - path.parent.mkdir(parents=True) - path.write_text(dump_yaml(dict(self))) - - @classmethod - def load(cls, path: Path): - with path.open("r") as fp: - return cls(load_yaml(fp)) diff --git a/api/src/automations_v2/types.py b/api/src/automations_v2/types.py deleted file mode 100644 index 8ce5280..0000000 --- a/api/src/automations_v2/types.py +++ /dev/null @@ -1,35 +0,0 @@ -from pathlib import Path -from typing import Dict, List, Literal, Optional, Union - -from pydantic import BaseModel -from pydantic.fields import Field - - -class BaseAutomation(BaseModel): - id: str - alias: Optional[str] = None - description: Optional[str] = None - trigger_variables: Optional[Dict[str, Union[str, int, bool, float]]] = None - mode: str = "single" - trigger: List[dict] = [] - condition: List[dict] = [] - action: List[dict] = [] - - def to_primitive(self): - return self.dict(exclude_unset=True, exclude_none=True) - - -class ExtenededAutomation(BaseAutomation): - source_file: Path - source_file_type: Literal["list", "obj"] - configuration_key: str - 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 diff --git a/api/src/hass_config/loader.py b/api/src/hass_config/loader.py index 33173ca..1c4c6e5 100644 --- a/api/src/hass_config/loader.py +++ b/api/src/hass_config/loader.py @@ -17,16 +17,6 @@ class HassConfig: with self.get_configuration_path().open("r") as f: return dict(load_yaml(f)) # type: ignore - @property - def automations(self) -> List[dict]: - if automation_path := self.get_automation_path(): - try: - with automation_path.open("r") as f: - return load_yaml(f) # type: ignore - 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() diff --git a/api/tests/unittests/api/test_automations.py b/api/tests/unittests/api/test_automations.py index 66e3641..76f6a39 100644 --- a/api/tests/unittests/api/test_automations.py +++ b/api/tests/unittests/api/test_automations.py @@ -1,14 +1,11 @@ +from pathlib import Path from unittest import TestCase import yaml from fastapi.testclient import TestClient from src.api.app import make_app -from src.automations.types import ( - AutomationData, - AutomationMetdata, - ExtenededAutomationData, -) +from src.automations.types import ExtenededAutomation from tests.utils import HA_CONFIG2_EXAMPLE, get_example_automation_loader @@ -106,48 +103,53 @@ class automation2_lists_tests(automation_list_tests): class automation_update_tests(BaseTestCase): def test_insert_new(self): resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) + autos = resp.json()["data"] self.assertEqual(resp.json()["totalItems"], 32) resp = self.client.post( "/automations/item", - json={ - "index": 33, - "data": AutomationData(metadata=AutomationMetdata(id="testme")).dict(), - }, + json=ExtenededAutomation( + id="i am new", + configuration_key="", + source_file_type="list", + source_file=autos[0]["source_file"], + ).to_json(), ) self.assertEqual(resp.status_code, 200) resp = self.client.post("/automations/list", json={"limit": 1, "offset": 32}) data = resp.json() self.assertEqual(data["totalItems"], 33) - self.assertEqual(data["data"][0]["metadata"]["id"], "testme") + self.assertEqual(data["data"][0]["id"], "i am new") def test_update_some(self): resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20}) original_auto = resp.json()["data"][0] + changed_to = ExtenededAutomation( + id=original_auto["id"], + alias="I have been modified", + configuration_key=original_auto["configuration_key"], + source_file_type=original_auto["source_file_type"], + source_file=original_auto["source_file"], + ) resp = self.client.post( "/automations/item", - json={ - "index": 20, - "data": AutomationData(metadata=AutomationMetdata(id="testme")).dict(), - }, + json=changed_to.to_json(), ) self.assertEqual(resp.status_code, 200) 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( - ExtenededAutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto + changed_to.to_json(), + new_auto, ) 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["metadata"]["alias"] = "I CHANGED!" + original_auto["alias"] = "I CHANGED!" resp = self.client.post( "/automations/item", - json={ - "index": 15, - "data": original_auto, - }, + json=original_auto, ) self.assertEqual(resp.status_code, 200) with (self.config_folder / "automations.yaml").open("r") as fp: @@ -192,13 +194,10 @@ class automation_update_tests(BaseTestCase): 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["metadata"]["alias"] = "I CHANGED!" + original_auto["alias"] = "I CHANGED!" resp = self.client.post( "/automations/item", - json={ - "index": 27, - "data": original_auto, - }, + json=original_auto, ) self.assertEqual(resp.status_code, 200) with (self.config_folder / "automations.yaml").open("r") as fp: @@ -324,12 +323,11 @@ class automation_update_tests(BaseTestCase): class automation_delete_tests(BaseTestCase): def test_delete_some(self): resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) + autos = resp.json()["data"] self.assertEqual(resp.json()["totalItems"], 32) resp = self.client.delete( "/automations/item", - json={ - "index": 20, - }, + json=autos[0], ) self.assertEqual(resp.status_code, 200) resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) diff --git a/api/tests/unittests/automations_v2/test_db.py b/api/tests/unittests/automations/test_db.py similarity index 97% rename from api/tests/unittests/automations_v2/test_db.py rename to api/tests/unittests/automations/test_db.py index 1fbd5e4..f35a0c4 100644 --- a/api/tests/unittests/automations_v2/test_db.py +++ b/api/tests/unittests/automations/test_db.py @@ -1,6 +1,6 @@ from pathlib import Path -from src.automations_v2.types import ExtenededAutomation +from src.automations.types import ExtenededAutomation from .utils import TestWithDB diff --git a/api/tests/unittests/automations/test_loader.py b/api/tests/unittests/automations/test_loader.py index 5dad2fc..4eb7834 100644 --- a/api/tests/unittests/automations/test_loader.py +++ b/api/tests/unittests/automations/test_loader.py @@ -1,59 +1,139 @@ +from pathlib import Path +from tempfile import mktemp from unittest import TestCase -from src.automations.loader import load_automation -from src.automations.types import AutomationMetdata, ExtenededAutomationData -from src.yaml_serializer.types import NOT_IMPLEMENTED_SV_MSG, SecretValue +from src.automations.loader import ( + extract_automation_paths, + load_automation_path, +) +from src.automations.tags import TagManager +from src.automations.types import ExtenededAutomation +from src.hass_config.loader import HassConfig +from tests.utils import ( + HA_CONFIG2_EXAMPLE, + HA_CONFIG3_EXAMPLE, + HA_CONFIG4_EXAMPLE, + HA_CONFIG5_EXAMPLE, + HA_CONFIG6_EXAMPLE, + HA_CONFIG_EXAMPLE, +) 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", - }, - {}, + def test_load_automation_list_file(self): + automations = list( + load_automation_path( + HA_CONFIG2_EXAMPLE / "automations.yaml", + configuration_key="automation", + tag_manager=TagManager({"1652069225859": {"type": "routine"}}), ) ) + self.assertEqual(len(automations), 1) self.assertEqual( - auto[0], - ExtenededAutomationData( - metadata=AutomationMetdata( - id="1616887975473", - alias="Home Assistant Off", - description="", - mode="single", - ), - trigger=[{"platform": "homeassistant", "event": "shutdown"}], - condition=[ + automations[0], + ExtenededAutomation( + id="1652069225859", + source_file=str(HA_CONFIG2_EXAMPLE / "automations.yaml"), + source_file_type="list", + configuration_key="automation", + alias="Climate - Pref temperature ", + description="", + mode="single", + tags={"type": "routine"}, + trigger=[ { - "condition": "template", - "value_template": "states(time.time) >= '10:00:00'", + "platform": "state", + "entity_id": "input_number.preferred_temperature", } ], - sequence=[ + condition=[], + action=[ { - "device_id": NOT_IMPLEMENTED_SV_MSG, - "domain": "mobile_app", - "type": "notify", - "title": "Hassio Status", - "message": "Hassio Is turning off...", + "service": "climate.set_temperature", + "data": { + "temperature": { + "[object Object]": None, + } + }, + "target": { + "entity_id": "climate.main_floor", + }, } ], - tags={}, ), ) + + def test_load_automation_obj_file(self): + automations = list( + load_automation_path( + HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml", + configuration_key="automation base", + tag_manager=TagManager({"1659114647067": {"room": "laundry"}}), + ) + ) + self.assertEqual(len(automations), 1) + self.assertEqual( + automations[0], + ExtenededAutomation( + id="1659114647067", + source_file=str(HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml"), + source_file_type="obj", + configuration_key="automation base", + alias="Notify Washer", + description="Example", + mode="single", + tags={"room": "laundry"}, + trigger=[ + { + "platform": "homeassistant", + "event": "start", + } + ], + condition=[], + action=[ + { + "service": "counter.increment", + "data": {}, + "target": {"entity_id": "counter.up_times"}, + } + ], + ), + ) + + def test_load_automation_empty_file(self): + file_path = Path(mktemp()) + file_path.touch() + automations = list( + load_automation_path( + file_path, + configuration_key="automation ui", + tag_manager=TagManager(), + ) + ) + self.assertEqual(len(automations), 0) + + def test_load_automation_none_existing_file(self): + file_path = Path(mktemp()) + file_path.unlink(missing_ok=True) + automations = list( + load_automation_path( + file_path, + configuration_key="automation manual", + tag_manager=TagManager(), + ) + ) + self.assertEqual(len(automations), 0) + + def test_extract_all_automation_files(self): + for ha_path, expected in [ + (HA_CONFIG_EXAMPLE, 1), + (HA_CONFIG2_EXAMPLE, 1), + (HA_CONFIG3_EXAMPLE, 1), + (HA_CONFIG4_EXAMPLE, 1), + (HA_CONFIG5_EXAMPLE, 3), + (HA_CONFIG6_EXAMPLE, 4), + ]: + with self.subTest(ha_path=ha_path, expected=expected): + hass_config = HassConfig(ha_path) + paths = list(extract_automation_paths(hass_config)) + self.assertEqual(len(paths), expected) diff --git a/api/tests/unittests/automations/test_manager.py b/api/tests/unittests/automations/test_manager.py index d45e3a7..473c8f8 100644 --- a/api/tests/unittests/automations/test_manager.py +++ b/api/tests/unittests/automations/test_manager.py @@ -1,115 +1,323 @@ -from unittest import TestCase +from pathlib import Path -from src.automations.errors import FailedDeletion, InvalidAutomationFile -from src.automations.types import AutomationMetdata, ExtenededAutomationData +from src import yaml_serializer +from src.automations.errors import ( + AttemptingToOverwriteAnIncompatibleFileError, + DBNoAutomationFound, + InvalidAutomationFile, +) +from src.automations.manager import AutomationManager +from src.automations.types import ExtenededAutomation +from src.errors import ErrorSet +from src.hass_config.loader import HassConfig from tests.utils import ( - get_dummy_automation_loader, - get_example_automation_loader, + HA_CONFIG6_EXAMPLE, + HA_CONFIG_EXAMPLE, + create_copy_of_example_config, ) +from .utils import TestWithDB -class manager_tests(TestCase): - def test_find_limit_and_get(self): - _, _, loader = get_example_automation_loader() - first_auto_with_find = list(loader.find(limit=1)) - first_auto_with_get = loader.get(0) - self.assertEqual(first_auto_with_find[0], first_auto_with_get) - def test_find_at_most_with_offset(self): - _, _, loader = get_example_automation_loader() - autos = list(loader.find(limit=10, offset=10)) - self.assertTrue(len(autos), 10) +class manager_tests(TestWithDB): + def get_manager(self, ha_config_example: Path): + self.config_path = create_copy_of_example_config(ha_config_example) + self.automation_manager = AutomationManager( + HassConfig(self.config_path), + self.db_file, + ) + return self.config_path, self.automation_manager + + def test_load_complex_read_modify_delete(self): + _, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + self.assertEqual(automation_manager.count(), 0) + automation_manager.reload() + self.assertEqual(automation_manager.count(), 12) + automation = automation_manager.get("sublist3-mlist2") + self.assertEqual(automation.description, "That was correct!") + self.assertEqual( + automation.action, + [ + { + "service": "switch.turn_off", + "target": {"entity_id": "switch.bathroom"}, + "data": None, + } + ], + ) + self.assertEqual(automation.configuration_key, "automation cools") + automation.trigger.append( + {"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"} + ) + automation_manager.upsert(automation) + self.assertEqual( + automation_manager.get("sublist3-mlist2").trigger, + [], + ) + automation_manager.reload() + self.assertEqual( + automation_manager.get("sublist3-mlist2").trigger, + [ + { + "platform": "zone", + "entity_id": "person.thor", + "zone": "zone.azguard", + } + ], + ) def test_find_invalid(self): - _, _, loader = get_example_automation_loader() - self.assertIsNone(loader.get(-1)) - self.assertIsNone(loader.get(1_000)) - self.assertIsNone(loader.get(33)) - - def test_length(self): - _, _, loader = get_example_automation_loader() - self.assertEqual(loader.get_total_items(), 32) + _, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("invalid") def test_bad_automations_file(self): - folder, _, manager = get_dummy_automation_loader( - [], - automation_in_conifguration_mode="none", - ) - (folder / "automations.yaml").write_text("bob is an uncle") - with self.assertRaises(InvalidAutomationFile): - manager.get(0) + config_path, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) + (config_path / "automations.yaml").write_text("bob is an uncle") + with self.assertRaises(ErrorSet) as err: + automation_manager.reload() + self.assertEqual(len(err.exception.errors), 1) + self.assertIsInstance(err.exception.errors[0], InvalidAutomationFile) + self.assertEqual(automation_manager.count(), 0) - def test_create_automation(self): - _, _, manager = get_dummy_automation_loader( - [], - automation_in_conifguration_mode="none", - ) - manager.update(1, ExtenededAutomationData(metadata=AutomationMetdata(id="test1"))) - auto = manager.get(0) - self.assertIsNotNone(auto) - self.assertEqual(auto.metadata.id, "test1") # type: ignore + def test_one_bad_automations_file(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + (config_path / "automations" / "ui.yaml").write_text("bob is an uncle") + with self.assertRaises(ErrorSet) as err: + automation_manager.reload() + self.assertEqual(len(err.exception.errors), 1) + self.assertIsInstance(err.exception.errors[0], InvalidAutomationFile) + self.assertEqual(automation_manager.count(), 10) - def test_create_automation_with_example_folder(self): - _, _, manager = get_example_automation_loader() - self.assertEqual(manager.get_total_items(), 32) - manager.update(40, ExtenededAutomationData(metadata=AutomationMetdata(id="test1"))) - auto = manager.get(32) - self.assertIsNotNone(auto) - self.assertEqual(manager.get_total_items(), 33) - self.assertEqual(auto.metadata.id, "test1") # type: ignore + def test_delete_automation_in_single_file(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + self.assertTrue((config_path / "automations/include_dir_list/home/down.yaml").exists()) + automation_manager.reload() + automation = automation_manager.get("1659114822642") + self.assertEqual(automation.configuration_key, "automation manual") + automation_manager.delete(automation) + automation_manager.reload() + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("1659114822642") + self.assertFalse((config_path / "automations/include_dir_list/home/down.yaml").exists()) - def test_update_automation(self): - _, _, manager = get_dummy_automation_loader( - [ - ExtenededAutomationData(metadata=AutomationMetdata(id="test1")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test2")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test3")), - ], - automation_in_conifguration_mode="none", + def test_delete_automation_in_list(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() + ) + automation_manager.reload() + automation = automation_manager.get("mlist2") + self.assertEqual(automation.configuration_key, "automation cools") + automation_manager.delete(automation) + automation_manager.reload() + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("mlist2") + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() ) - auto = manager.get(0) - self.assertEqual(auto.metadata.id, "test1") # type: ignore - 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( - [ - ExtenededAutomationData(metadata=AutomationMetdata(id="test1")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test2")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test3")), - ], - automation_in_conifguration_mode="none", + def test_create_new_in_single_file(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + self.assertFalse((config_path / "automations/include_dir_list/home/left.yaml").exists()) + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + automation_manager.upsert( + ExtenededAutomation( + id="newlymade", + configuration_key="automation manual", + source_file=config_path / "automations/include_dir_list/home/left.yaml", + source_file_type="obj", + ) + ) + self.assertTrue((config_path / "automations/include_dir_list/home/left.yaml").exists()) + automation_manager.reload() + self.assertEqual( + automation_manager.get("newlymade"), + ExtenededAutomation( + id="newlymade", + configuration_key="automation manual", + source_file=config_path / "automations/include_dir_list/home/left.yaml", + source_file_type="obj", + ), ) - self.assertEqual(manager.get_total_items(), 3) - manager.delete(1) - self.assertEqual(manager.get_total_items(), 2) - for auto in manager.find(0, 1000): - self.assertNotEqual(auto.metadata.id, "test2") - def test_failed_deletion_automation(self): - _, _, manager = get_dummy_automation_loader( - [ - ExtenededAutomationData(metadata=AutomationMetdata(id="test1")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test2")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test3")), - ], - automation_in_conifguration_mode="none", + def test_create_new_in_existing_list_file(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() + ) + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + automation_manager.upsert( + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", + source_file_type="list", + ) + ) + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() + ) + automation_manager.reload() + self.assertEqual( + automation_manager.get("newlymade"), + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", + source_file_type="list", + ), ) - self.assertEqual(manager.get_total_items(), 3) - with self.assertRaises(FailedDeletion): - manager.delete(10) - def test_save_tags(self): - _, _, manager = get_dummy_automation_loader( - [ - ExtenededAutomationData(metadata=AutomationMetdata(id="test1")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test2")), - ExtenededAutomationData(metadata=AutomationMetdata(id="test3")), - ], - automation_in_conifguration_mode="none", + def test_create_new_in_new_list_file(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + self.assertFalse( + (config_path / "automations/include_dir_merge_list/sub/list4.yaml").exists() + ) + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + automation_manager.upsert( + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml", + source_file_type="list", + ) + ) + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list4.yaml").exists() + ) + automation_manager.reload() + self.assertEqual( + automation_manager.get("newlymade"), + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml", + source_file_type="list", + ), + ) + + def test_save_improper_types_list_to_obj(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + self.assertTrue( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() + ) + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError): + automation_manager.upsert( + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", + source_file_type="obj", + ) + ) + automation_manager.reload() + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + + data = yaml_serializer.load_yaml( + (config_path / "automations/include_dir_merge_list/sub/list2.yaml").open("r") + ) + self.assertIsInstance(data, list) + + def test_save_improper_types_obj_to_list(self): + config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) + automation_manager.reload() + self.assertTrue((config_path / "automations/include_dir_list/home/down.yaml").exists()) + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError): + automation_manager.upsert( + ExtenededAutomation( + id="newlymade", + configuration_key="automation cools", + source_file=config_path / "automations/include_dir_list/home/down.yaml", + source_file_type="list", + ) + ) + automation_manager.reload() + with self.assertRaises(DBNoAutomationFound): + automation_manager.get("newlymade") + + data = yaml_serializer.load_yaml( + (config_path / "automations/include_dir_list/home/down.yaml").open("r") + ) + self.assertIsInstance(data, dict) + + def test_update_tags_through_automation_update(self): + _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + { + "Room": "Living", + "Type": "Button", + }, + ) + auto.tags["Room"] = "Bathroom" + automation_manager.upsert(auto) + del auto + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + { + "Room": "Bathroom", + "Type": "Button", + }, + ) + + def test_update_tags_through_tags(self): + _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + { + "Room": "Living", + "Type": "Button", + }, + ) + auto.tags["Room"] = "Bathroom" + automation_manager.update_tags(auto.id, auto.tags) + del auto + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + { + "Room": "Bathroom", + "Type": "Button", + }, + ) + + def test_delete_tags(self): + _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + { + "Room": "Living", + "Type": "Button", + }, + ) + automation_manager.delete_tags(auto.id) + del auto + automation_manager.reload() + auto = automation_manager.get("1619371298367") + self.assertDictEqual( + auto.tags, + {}, ) - manager.update_tags("test1", {"room": "bathroom"}) - auto = manager.get(0) - assert auto.tags == {"room": "bathroom"} diff --git a/api/tests/unittests/automations_v2/utils.py b/api/tests/unittests/automations/utils.py similarity index 87% rename from api/tests/unittests/automations_v2/utils.py rename to api/tests/unittests/automations/utils.py index 83e2c97..82f7c55 100644 --- a/api/tests/unittests/automations_v2/utils.py +++ b/api/tests/unittests/automations/utils.py @@ -2,7 +2,7 @@ from pathlib import Path from tempfile import mktemp from unittest import TestCase -from src.automations_v2.db import AutomationDBConnection +from src.automations.db import AutomationDBConnection def make_temp_db(): diff --git a/api/tests/unittests/automations_v2/__init__.py b/api/tests/unittests/automations_v2/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/tests/unittests/automations_v2/test_loader.py b/api/tests/unittests/automations_v2/test_loader.py deleted file mode 100644 index 53bf6b9..0000000 --- a/api/tests/unittests/automations_v2/test_loader.py +++ /dev/null @@ -1,139 +0,0 @@ -from pathlib import Path -from tempfile import mktemp -from unittest import TestCase - -from src.automations_v2.loader import ( - extract_automation_paths, - load_automation_path, -) -from src.automations_v2.tags import TagManager -from src.automations_v2.types import ExtenededAutomation -from src.hass_config.loader import HassConfig -from tests.utils import ( - HA_CONFIG2_EXAMPLE, - HA_CONFIG3_EXAMPLE, - HA_CONFIG4_EXAMPLE, - HA_CONFIG5_EXAMPLE, - HA_CONFIG6_EXAMPLE, - HA_CONFIG_EXAMPLE, -) - - -class loader_tests(TestCase): - def test_load_automation_list_file(self): - automations = list( - load_automation_path( - HA_CONFIG2_EXAMPLE / "automations.yaml", - configuration_key="automation", - tag_manager=TagManager({"1652069225859": {"type": "routine"}}), - ) - ) - self.assertEqual(len(automations), 1) - self.assertEqual( - automations[0], - ExtenededAutomation( - id="1652069225859", - source_file=str(HA_CONFIG2_EXAMPLE / "automations.yaml"), - source_file_type="list", - configuration_key="automation", - alias="Climate - Pref temperature ", - description="", - mode="single", - tags={"type": "routine"}, - trigger=[ - { - "platform": "state", - "entity_id": "input_number.preferred_temperature", - } - ], - condition=[], - action=[ - { - "service": "climate.set_temperature", - "data": { - "temperature": { - "[object Object]": None, - } - }, - "target": { - "entity_id": "climate.main_floor", - }, - } - ], - ), - ) - - def test_load_automation_obj_file(self): - automations = list( - load_automation_path( - HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml", - configuration_key="automation base", - tag_manager=TagManager({"1659114647067": {"room": "laundry"}}), - ) - ) - self.assertEqual(len(automations), 1) - self.assertEqual( - automations[0], - ExtenededAutomation( - id="1659114647067", - source_file=str(HA_CONFIG4_EXAMPLE / "automations" / "notify_washer.yaml"), - source_file_type="obj", - configuration_key="automation base", - alias="Notify Washer", - description="Example", - mode="single", - tags={"room": "laundry"}, - trigger=[ - { - "platform": "homeassistant", - "event": "start", - } - ], - condition=[], - action=[ - { - "service": "counter.increment", - "data": {}, - "target": {"entity_id": "counter.up_times"}, - } - ], - ), - ) - - def test_load_automation_empty_file(self): - file_path = Path(mktemp()) - file_path.touch() - automations = list( - load_automation_path( - file_path, - configuration_key="automation ui", - tag_manager=TagManager(), - ) - ) - self.assertEqual(len(automations), 0) - - def test_load_automation_none_existing_file(self): - file_path = Path(mktemp()) - file_path.unlink(missing_ok=True) - automations = list( - load_automation_path( - file_path, - configuration_key="automation manual", - tag_manager=TagManager(), - ) - ) - self.assertEqual(len(automations), 0) - - def test_extract_all_automation_files(self): - for ha_path, expected in [ - (HA_CONFIG_EXAMPLE, 1), - (HA_CONFIG2_EXAMPLE, 1), - (HA_CONFIG3_EXAMPLE, 1), - (HA_CONFIG4_EXAMPLE, 1), - (HA_CONFIG5_EXAMPLE, 3), - (HA_CONFIG6_EXAMPLE, 4), - ]: - with self.subTest(ha_path=ha_path, expected=expected): - hass_config = HassConfig(ha_path) - paths = list(extract_automation_paths(hass_config)) - self.assertEqual(len(paths), expected) diff --git a/api/tests/unittests/automations_v2/test_manager.py b/api/tests/unittests/automations_v2/test_manager.py deleted file mode 100644 index e4cd19d..0000000 --- a/api/tests/unittests/automations_v2/test_manager.py +++ /dev/null @@ -1,323 +0,0 @@ -from pathlib import Path - -from src import yaml_serializer -from src.automations_v2.errors import ( - AttemptingToOverwriteAnIncompatibleFileError, - DBNoAutomationFound, - InvalidAutomationFile, -) -from src.automations_v2.manager import AutomationManager -from src.automations_v2.types import ExtenededAutomation -from src.errors import ErrorSet -from src.hass_config.loader import HassConfig -from tests.utils import ( - HA_CONFIG6_EXAMPLE, - HA_CONFIG_EXAMPLE, - create_copy_of_example_config, -) - -from .utils import TestWithDB - - -class manager_tests(TestWithDB): - def get_manager(self, ha_config_example: Path): - self.config_path = create_copy_of_example_config(ha_config_example) - self.automation_manager = AutomationManager( - HassConfig(self.config_path), - self.db_file, - ) - return self.config_path, self.automation_manager - - def test_load_complex_read_modify_delete(self): - _, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - self.assertEqual(automation_manager.count(), 0) - automation_manager.reload() - self.assertEqual(automation_manager.count(), 12) - automation = automation_manager.get("sublist3-mlist2") - self.assertEqual(automation.description, "That was correct!") - self.assertEqual( - automation.action, - [ - { - "service": "switch.turn_off", - "target": {"entity_id": "switch.bathroom"}, - "data": None, - } - ], - ) - self.assertEqual(automation.configuration_key, "automation cools") - automation.trigger.append( - {"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"} - ) - automation_manager.upsert(automation) - self.assertEqual( - automation_manager.get("sublist3-mlist2").trigger, - [], - ) - automation_manager.reload() - self.assertEqual( - automation_manager.get("sublist3-mlist2").trigger, - [ - { - "platform": "zone", - "entity_id": "person.thor", - "zone": "zone.azguard", - } - ], - ) - - def test_find_invalid(self): - _, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("invalid") - - def test_bad_automations_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) - (config_path / "automations.yaml").write_text("bob is an uncle") - with self.assertRaises(ErrorSet) as err: - automation_manager.reload() - self.assertEqual(len(err.exception.errors), 1) - self.assertIsInstance(err.exception.errors[0], InvalidAutomationFile) - self.assertEqual(automation_manager.count(), 0) - - def test_one_bad_automations_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - (config_path / "automations" / "ui.yaml").write_text("bob is an uncle") - with self.assertRaises(ErrorSet) as err: - automation_manager.reload() - self.assertEqual(len(err.exception.errors), 1) - self.assertIsInstance(err.exception.errors[0], InvalidAutomationFile) - self.assertEqual(automation_manager.count(), 10) - - def test_delete_automation_in_single_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - self.assertTrue((config_path / "automations/include_dir_list/home/down.yaml").exists()) - automation_manager.reload() - automation = automation_manager.get("1659114822642") - self.assertEqual(automation.configuration_key, "automation manual") - automation_manager.delete(automation) - automation_manager.reload() - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("1659114822642") - self.assertFalse((config_path / "automations/include_dir_list/home/down.yaml").exists()) - - def test_delete_automation_in_list(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() - ) - automation_manager.reload() - automation = automation_manager.get("mlist2") - self.assertEqual(automation.configuration_key, "automation cools") - automation_manager.delete(automation) - automation_manager.reload() - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("mlist2") - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() - ) - - def test_create_new_in_single_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - self.assertFalse((config_path / "automations/include_dir_list/home/left.yaml").exists()) - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - automation_manager.upsert( - ExtenededAutomation( - id="newlymade", - configuration_key="automation manual", - source_file=config_path / "automations/include_dir_list/home/left.yaml", - source_file_type="obj", - ) - ) - self.assertTrue((config_path / "automations/include_dir_list/home/left.yaml").exists()) - automation_manager.reload() - self.assertEqual( - automation_manager.get("newlymade"), - ExtenededAutomation( - id="newlymade", - configuration_key="automation manual", - source_file=config_path / "automations/include_dir_list/home/left.yaml", - source_file_type="obj", - ), - ) - - def test_create_new_in_existing_list_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() - ) - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - automation_manager.upsert( - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", - source_file_type="list", - ) - ) - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() - ) - automation_manager.reload() - self.assertEqual( - automation_manager.get("newlymade"), - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", - source_file_type="list", - ), - ) - - def test_create_new_in_new_list_file(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - self.assertFalse( - (config_path / "automations/include_dir_merge_list/sub/list4.yaml").exists() - ) - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - automation_manager.upsert( - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml", - source_file_type="list", - ) - ) - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list4.yaml").exists() - ) - automation_manager.reload() - self.assertEqual( - automation_manager.get("newlymade"), - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_merge_list/sub/list4.yaml", - source_file_type="list", - ), - ) - - def test_save_improper_types_list_to_obj(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - self.assertTrue( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").exists() - ) - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError): - automation_manager.upsert( - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_merge_list/sub/list2.yaml", - source_file_type="obj", - ) - ) - automation_manager.reload() - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - - data = yaml_serializer.load_yaml( - (config_path / "automations/include_dir_merge_list/sub/list2.yaml").open("r") - ) - self.assertIsInstance(data, list) - - def test_save_improper_types_obj_to_list(self): - config_path, automation_manager = self.get_manager(HA_CONFIG6_EXAMPLE) - automation_manager.reload() - self.assertTrue((config_path / "automations/include_dir_list/home/down.yaml").exists()) - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - with self.assertRaises(AttemptingToOverwriteAnIncompatibleFileError): - automation_manager.upsert( - ExtenededAutomation( - id="newlymade", - configuration_key="automation cools", - source_file=config_path / "automations/include_dir_list/home/down.yaml", - source_file_type="list", - ) - ) - automation_manager.reload() - with self.assertRaises(DBNoAutomationFound): - automation_manager.get("newlymade") - - data = yaml_serializer.load_yaml( - (config_path / "automations/include_dir_list/home/down.yaml").open("r") - ) - self.assertIsInstance(data, dict) - - def test_update_tags_through_automation_update(self): - _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - { - "Room": "Living", - "Type": "Button", - }, - ) - auto.tags["Room"] = "Bathroom" - automation_manager.upsert(auto) - del auto - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - { - "Room": "Bathroom", - "Type": "Button", - }, - ) - - def test_update_tags_through_tags(self): - _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - { - "Room": "Living", - "Type": "Button", - }, - ) - auto.tags["Room"] = "Bathroom" - automation_manager.update_tags(auto) - del auto - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - { - "Room": "Bathroom", - "Type": "Button", - }, - ) - - def test_delete_tags(self): - _, automation_manager = self.get_manager(HA_CONFIG_EXAMPLE) - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - { - "Room": "Living", - "Type": "Button", - }, - ) - automation_manager.delete_tags(auto.id) - del auto - automation_manager.reload() - auto = automation_manager.get("1619371298367") - self.assertDictEqual( - auto.tags, - {}, - ) diff --git a/api/tests/unittests/automations_v2/test_tags.py b/api/tests/unittests/automations_v2/test_tags.py deleted file mode 100644 index 24e4626..0000000 --- a/api/tests/unittests/automations_v2/test_tags.py +++ /dev/null @@ -1,17 +0,0 @@ -from pathlib import Path -from tempfile import mktemp -from unittest import TestCase - -from src.automations_v2.tags import TagManager - - -class tag_tests(TestCase): - def test_load_and_save(self): - tmp_file = Path(mktemp()).with_suffix(".yml") - tags = TagManager() - tags[0] = {"Room": "Kitchen", "Type": "Lights"} - tags[1] = {} - - tags.save(tmp_file) - loaded_tags = TagManager.load(tmp_file) - assert loaded_tags.keys() == tags.keys() diff --git a/api/tests/unittests/hass_config/test_loader.py b/api/tests/unittests/hass_config/test_loader.py index 3cf12b6..3cd44de 100644 --- a/api/tests/unittests/hass_config/test_loader.py +++ b/api/tests/unittests/hass_config/test_loader.py @@ -1,6 +1,6 @@ from unittest import TestCase -from src.automations.types import AutomationData, AutomationMetdata +from src.automations.types import BaseAutomation from src.hass_config.errors import MissingFile from src.hass_config.loader import HassConfig from tests.utils import create_dummy_config_folder @@ -9,41 +9,36 @@ from tests.utils import create_dummy_config_folder class loader_tests(TestCase): def test_load_automation_from_config_yaml(self): folder = create_dummy_config_folder( - [AutomationData(metadata=AutomationMetdata(id="test"))], + [BaseAutomation(id="test")], automation_in_conifguration_mode="inline", ) hass_config = HassConfig(folder) self.assertIsInstance(hass_config.configurations, dict) self.assertTrue("automation" in hass_config.configurations) - self.assertEqual(hass_config.automations[0]["id"], "test") def test_load_automation_from_config_yaml_include(self): folder = create_dummy_config_folder( - [AutomationData(metadata=AutomationMetdata(id="test"))], + [BaseAutomation(id="test")], automation_in_conifguration_mode="include", ) hass_config = HassConfig(folder) self.assertIsInstance(hass_config.configurations, dict) self.assertTrue("automation" in hass_config.configurations) - self.assertEqual(hass_config.automations[0]["id"], "test") def test_load_automation_from_infer(self): folder = create_dummy_config_folder( - [AutomationData(metadata=AutomationMetdata(id="test"))], + [BaseAutomation(id="test")], automation_in_conifguration_mode="none", ) hass_config = HassConfig(folder) self.assertIsInstance(hass_config.configurations, dict) self.assertFalse("automation" in hass_config.configurations) - self.assertEqual(hass_config.automations[0]["id"], "test") def test_missing_automations(self): folder = create_dummy_config_folder( - [AutomationData(metadata=AutomationMetdata(id="test"))], + [BaseAutomation(id="test")], automation_in_conifguration_mode="none", ) (folder / "automations.yaml").unlink() hass_config = HassConfig(folder) self.assertIsInstance(hass_config.configurations, dict) - with self.assertRaises(MissingFile): - list(hass_config.automations) diff --git a/api/tests/utils.py b/api/tests/utils.py index 2925200..2d59fe4 100644 --- a/api/tests/utils.py +++ b/api/tests/utils.py @@ -4,7 +4,7 @@ from tempfile import mkdtemp from typing import List, Literal, Optional, Tuple from src.automations.manager import AutomationManager -from src.automations.types import AutomationData +from src.automations.types import BaseAutomation from src.hass_config.loader import HassConfig from src.yaml_serializer import dump_yaml from src.yaml_serializer.types import IncludedYaml @@ -46,7 +46,7 @@ def create_copy_of_example_config(config_to_copy: Path = HA_CONFIG_EXAMPLE) -> P def get_dummy_automation_loader( - auto: List[AutomationData], + auto: List[BaseAutomation], secrets: Optional[dict] = None, other_config: Optional[dict] = None, automation_in_conifguration_mode: Literal["include", "inline", "none"] = "include", @@ -54,7 +54,7 @@ def get_dummy_automation_loader( """Creates a dummy /config structure for testing and return the loader and config Args: - auto (List[AutomationData]): automations + auto (List[BaseAutomation]): automations secrets (Optional[dict], optional): dictionary of secrets other_config (Optional[dict], optional): some config stuff to place into configuration.yaml. Defaults to None. automation_in_conifguration_mode (Literal['include', 'inline', 'none'], optional): whether to !include automation as a separete file or in the configuration yaml. Defaults to inline. @@ -74,7 +74,7 @@ def get_dummy_automation_loader( def create_dummy_config_folder( - auto: List[AutomationData], + auto: List[BaseAutomation], secrets: Optional[dict] = None, other_config: Optional[dict] = None, automation_in_conifguration_mode: Literal["include", "inline", "none"] = "include", @@ -82,7 +82,7 @@ def create_dummy_config_folder( """Creates a dummy /config structure for testing Args: - auto (List[AutomationData]): automations + auto (List[BaseAutomation]): automations secrets (Optional[dict], optional): dictionary of secrets other_config (Optional[dict], optional): some config stuff to place into configuration.yaml. Defaults to None. automation_in_conifguration_mode (Literal['include', 'inline', 'none'], optional): whether to !include automation as a separete file or in the configuration yaml. Defaults to inline.