Files
EOS/tests/test_adapternodered.py

128 lines
4.8 KiB
Python
Raw Normal View History

feat: add Home Assistant and NodeRED adapters (#764) Adapters for Home Assistant and NodeRED integration are added. Akkudoktor-EOS can now be run as Home Assistant add-on and standalone. As Home Assistant add-on EOS uses ingress to fully integrate the EOSdash dashboard in Home Assistant. The fix includes several bug fixes that are not directly related to the adapter implementation but are necessary to keep EOS running properly and to test and document the changes. * fix: development version scheme The development versioning scheme is adaptet to fit to docker and home assistant expectations. The new scheme is x.y.z and x.y.z.dev<hash>. Hash is only digits as expected by home assistant. Development version is appended by .dev as expected by docker. * fix: use mean value in interval on resampling for array When downsampling data use the mean value of all values within the new sampling interval. * fix: default battery ev soc and appliance wh Make the genetic simulation return default values for the battery SoC, electric vehicle SoC and appliance load if these assets are not used. * fix: import json string Strip outer quotes from JSON strings on import to be compliant to json.loads() expectation. * fix: default interval definition for import data Default interval must be defined in lowercase human definition to be accepted by pendulum. * fix: clearoutside schema change * feat: add adapters for integrations Adapters for Home Assistant and NodeRED integration are added. Akkudoktor-EOS can now be run as Home Assistant add-on and standalone. As Home Assistant add-on EOS uses ingress to fully integrate the EOSdash dashboard in Home Assistant. * feat: allow eos to be started with root permissions and drop priviledges Home assistant starts all add-ons with root permissions. Eos now drops root permissions if an applicable user is defined by paramter --run_as_user. The docker image defines the user eos to be used. * feat: make eos supervise and monitor EOSdash Eos now not only starts EOSdash but also monitors EOSdash during runtime and restarts EOSdash on fault. EOSdash logging is captured by EOS and forwarded to the EOS log to provide better visibility. * feat: add duration to string conversion Make to_duration to also return the duration as string on request. * chore: Use info logging to report missing optimization parameters In parameter preparation for automatic optimization an error was logged for missing paramters. Log is now down using the info level. * chore: make EOSdash use the EOS data directory for file import/ export EOSdash use the EOS data directory for file import/ export by default. This allows to use the configuration import/ export function also within docker images. * chore: improve EOSdash config tab display Improve display of JSON code and add more forms for config value update. * chore: make docker image file system layout similar to home assistant Only use /data directory for persistent data. This is handled as a docker volume. The /data volume is mapped to ~/.local/share/net.akkudoktor.eos if using docker compose. * chore: add home assistant add-on development environment Add VSCode devcontainer and task definition for home assistant add-on development. * chore: improve documentation
2025-12-30 22:08:21 +01:00
from __future__ import annotations
from datetime import datetime
from unittest.mock import MagicMock, patch
import pytest
from pydantic import BaseModel
from akkudoktoreos.adapter.adapter import AdapterCommonSettings
from akkudoktoreos.adapter.nodered import NodeREDAdapter, NodeREDAdapterCommonSettings
from akkudoktoreos.core.emplan import DDBCInstruction, FRBCInstruction
from akkudoktoreos.core.ems import EnergyManagementStage
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
@pytest.fixture
def mock_ems() -> MagicMock:
m = MagicMock()
m.stage.return_value = EnergyManagementStage.DATA_ACQUISITION
m.plan.return_value.get_active_instructions.return_value = []
return m
@pytest.fixture
def adapter(config_eos, mock_ems: MagicMock) -> NodeREDAdapter:
"""Fully Pydantic-safe NodeREDAdapter fixture."""
# Set nested value - also fills None values
config_eos.set_nested_value("adapter/provider", ["NodeRED"])
ad = NodeREDAdapter()
# Mark update datetime invalid
ad.update_datetime = None
# Assign EMS
object.__setattr__(ad, "ems", mock_ems)
return ad
class TestNodeREDAdapter:
def test_provider_id(self, adapter: NodeREDAdapter):
assert adapter.provider_id() == "NodeRED"
def test_enabled_detection_single(self, adapter: NodeREDAdapter):
adapter.config.adapter.provider = ["NodeRED"]
assert adapter.enabled() is True
adapter.config.adapter.provider = ["HomeAssistant"]
assert adapter.enabled() is False
adapter.config.adapter.provider = ["HomeAssistant", "NodeRED"]
assert adapter.enabled() is True
@patch("requests.get")
def test_update_datetime(self, mock_get, adapter: NodeREDAdapter):
adapter.ems.stage.return_value = EnergyManagementStage.DATA_ACQUISITION
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {"foo": "bar"}
now = to_datetime()
adapter.update_data(force_enable=True)
mock_get.assert_called_once()
assert compare_datetimes(adapter.update_datetime, now).approximately_equal
@patch("requests.get")
def test_update_data_data_acquisition_success(self, mock_get , adapter: NodeREDAdapter):
adapter.ems.stage.return_value = EnergyManagementStage.DATA_ACQUISITION
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {"foo": "bar"}
adapter.update_data(force_enable=True)
mock_get.assert_called_once()
url, = mock_get.call_args[0]
assert "/eos/data_aquisition" in url
@patch("requests.get", side_effect=Exception("boom"))
def test_update_data_data_acquisition_failure(self, mock_get, adapter: NodeREDAdapter):
adapter.ems.stage.return_value = EnergyManagementStage.DATA_ACQUISITION
with pytest.raises(RuntimeError):
adapter.update_data(force_enable=True)
@patch("requests.post")
def test_update_data_control_dispatch_instructions(self, mock_post, adapter: NodeREDAdapter):
adapter.ems.stage.return_value = EnergyManagementStage.CONTROL_DISPATCH
instr1 = DDBCInstruction(
id="res1@extra", operation_mode_id="X", operation_mode_factor=0.5,
actuator_id="dummy", execution_time=to_datetime()
)
instr2 = FRBCInstruction(
id="resA", operation_mode_id="Y", operation_mode_factor=0.25,
actuator_id="dummy", execution_time=to_datetime()
)
adapter.ems.plan.return_value.get_active_instructions.return_value = [instr1, instr2]
mock_post.return_value.status_code = 200
mock_post.return_value.json.return_value = {}
adapter.update_data(force_enable=True)
_, kwargs = mock_post.call_args
payload = kwargs["json"]
assert payload["res1_op_mode"] == "X"
assert payload["res1_op_factor"] == 0.5
assert payload["resA_op_mode"] == "Y"
assert payload["resA_op_factor"] == 0.25
url, = mock_post.call_args[0]
assert "/eos/control_dispatch" in url
@patch("requests.post")
def test_update_data_disabled_provider(self, mock_post, adapter: NodeREDAdapter):
adapter.config.adapter.provider = ["HomeAssistant"] # NodeRED disabled
adapter.update_data(force_enable=False)
mock_post.assert_not_called()
@patch("requests.post")
def test_update_data_force_enable_overrides_disabled(self, mock_post, adapter: NodeREDAdapter):
adapter.config.adapter.provider = ["HomeAssistant"]
adapter.ems.stage.return_value = EnergyManagementStage.CONTROL_DISPATCH
mock_post.return_value.status_code = 200
mock_post.return_value.json.return_value = {}
adapter.update_data(force_enable=True)
mock_post.assert_called_once()