cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source
This commit is contained in:
1 parent
343331d234
commit
d5fbcacaa4
176 files changed
+32511
-19
No files matched your search
@@ -0,0 +1,249 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The add-on's manifest (what the Supervisor checks, and what keeps the
|
||||
system "supported") and addon-run's start, with a fake Supervisor."""
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
ADDON = Path(__file__).resolve().parent.parent / "cantabile_edge"
|
||||
RUN = ADDON / "addon-run"
|
||||
|
||||
|
||||
def manifest():
|
||||
return yaml.safe_load((ADDON / "config.yaml").read_text())
|
||||
|
||||
|
||||
def test_manifest_has_what_the_supervisor_needs():
|
||||
m = manifest()
|
||||
for k in ("name", "version", "slug", "description", "arch"):
|
||||
assert m.get(k), k
|
||||
assert m["slug"] == ADDON.name
|
||||
assert set(m["arch"]) <= {"amd64", "aarch64", "armv7", "armhf", "i386"}
|
||||
assert "{arch}" in m["image"]
|
||||
assert isinstance(m["version"], str)
|
||||
|
||||
|
||||
def test_manifest_asks_for_no_more_than_it_needs():
|
||||
m = manifest()
|
||||
for k in ("host_network", "privileged", "full_access", "host_pid", "docker_api", "apparmor"):
|
||||
assert k not in m, k
|
||||
assert m["map"] == [{"type": "homeassistant_config", "read_only": True}, {"type": "share", "read_only": True}]
|
||||
assert m.get("hassio_role", "default") == "default"
|
||||
|
||||
|
||||
def test_options_schema_and_translations_agree():
|
||||
m = manifest()
|
||||
assert set(m["options"]) == set(m["schema"])
|
||||
assert m["schema"]["mode"] == "list(off|shadow)" # advisory and auto only from the console
|
||||
assert m["options"]["mode"] in ("off", "shadow")
|
||||
for lang in ("en", "de"):
|
||||
t = yaml.safe_load((ADDON / "translations" / f"{lang}.yaml").read_text())
|
||||
assert set(t["configuration"]) == set(m["schema"]), lang
|
||||
|
||||
|
||||
def test_icons_exist():
|
||||
for n in ("icon.png", "logo.png"):
|
||||
assert (ADDON / n).read_bytes()[:8] == b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
class Supervisor(http.server.BaseHTTPRequestHandler):
|
||||
mqtt = None
|
||||
seen = []
|
||||
|
||||
def do_GET(self):
|
||||
Supervisor.seen.append((self.path, self.headers.get("Authorization")))
|
||||
if self.path == "/services/mqtt" and Supervisor.mqtt:
|
||||
body = json.dumps({"result": "ok", "data": Supervisor.mqtt}).encode()
|
||||
self.send_response(200)
|
||||
else:
|
||||
body = b'{"result": "error", "message": "Service not enabled"}'
|
||||
self.send_response(400)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def box(tmp_path):
|
||||
srv = http.server.HTTPServer(("127.0.0.1", 0), Supervisor)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
data, ha, etc, share = tmp_path / "data", tmp_path / "ha", tmp_path / "etc", tmp_path / "share"
|
||||
data.mkdir(), (ha / ".storage").mkdir(parents=True), etc.mkdir(), share.mkdir()
|
||||
(ha / ".storage" / "core.uuid").write_text('{"version":1,"key":"core.uuid","data":{"uuid":"8b7c0f9e5a1d4c2b9e3f0a1b2c3d4e5f"}}')
|
||||
(etc / "addon.env").write_text("# the platform\nCANTABILE_DEVICES_URL=https://devices.example.org\n")
|
||||
(etc / "commands.pem").write_text("cert")
|
||||
(data / "options.json").write_text(json.dumps({"consent_data": True, "consent_control": False, "mode": "shadow",
|
||||
"claim_code": " ABCD-EFGH-JKLM ", "dashboards": False}))
|
||||
Supervisor.seen.clear()
|
||||
|
||||
def run():
|
||||
env = {"PATH": os.environ["PATH"], "ADDON_DRY_RUN": "1", "ADDON_DATA": str(data), "ADDON_HA_CONFIG": str(ha),
|
||||
"ADDON_ETC": str(etc), "ADDON_SHARE": str(share), "SUPERVISOR_URL": f"http://127.0.0.1:{srv.server_port}", "SUPERVISOR_TOKEN": "tok"}
|
||||
p = subprocess.run([sys.executable, str(RUN)], env=env, capture_output=True, text=True, check=True)
|
||||
return json.loads(p.stdout.strip().splitlines()[-1])
|
||||
|
||||
yield run, data, etc
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_start_with_the_mosquitto_add_on(box):
|
||||
run, data, etc = box
|
||||
Supervisor.mqtt = {"host": "core-mosquitto", "port": 1883, "ssl": False, "username": "addons", "password": "pw"}
|
||||
out = run()
|
||||
env = out["env"]
|
||||
assert out["cmd"][-1] == "run" and out["cmd"][0] == "cantabile-run"
|
||||
assert env["CANTABILE_DEVICES_URL"] == "https://devices.example.org"
|
||||
assert env["CANTABILE_COMMAND_CERT"] == f"{etc}/commands.pem"
|
||||
assert "CANTABILE_BUNDLE_CERT" not in env # no bundle certificate in this build
|
||||
assert env["CANTABILE_HA_UUID_FILE"] == f"{data}/ha-core.uuid"
|
||||
assert "8b7c0f9e5a1d4c2b9e3f0a1b2c3d4e5f" in (data / "ha-core.uuid").read_text()
|
||||
assert (data / "ha-core.uuid").stat().st_mode & 0o077 == 0
|
||||
assert (data / "claim-code").read_text() == "ABCD-EFGH-JKLM\n"
|
||||
assert env["CANTABILE_MODE"] == "shadow" and env["CANTABILE_DASHBOARDS"] == "0"
|
||||
assert (env["CANTABILE_MQTT_HOST"], env["CANTABILE_MQTT_PORT"], env["CANTABILE_MQTT_USER"]) == ("core-mosquitto", "1883", "addons")
|
||||
assert (data / "mqtt-password").read_text() == "pw"
|
||||
assert Supervisor.seen == [("/services/mqtt", "Bearer tok")]
|
||||
assert "sink: {kind: link" in (data / "config.yaml").read_text()
|
||||
assert "assets: []" in (data / "mapping.yaml").read_text()
|
||||
assert env["CANTABILE_PROPOSE"] == "1" # the agent proposes one, consent off
|
||||
assert not (data / "mapping-import.yaml").exists()
|
||||
|
||||
|
||||
def test_start_without_a_broker_and_keeps_the_installers_files(box):
|
||||
run, data, etc = box
|
||||
Supervisor.mqtt = None
|
||||
(data / "mapping.yaml").write_text("version: 3\nassets: [mine]\n")
|
||||
(data / "config.yaml").write_text("mode: shadow\n# mine\n")
|
||||
(etc / "bundles.pem").write_text("cert")
|
||||
env = run()["env"]
|
||||
assert not any(k.startswith("CANTABILE_MQTT") for k in env)
|
||||
assert env["CANTABILE_BUNDLE_CERT"] == f"{etc}/bundles.pem"
|
||||
assert (data / "mapping.yaml").read_text() == "version: 3\nassets: [mine]\n"
|
||||
assert (data / "config.yaml").read_text() == "mode: shadow\n# mine\n"
|
||||
|
||||
|
||||
def test_no_claim_code_writes_none(box):
|
||||
run, data, etc = box
|
||||
(data / "options.json").write_text(json.dumps({"consent_data": True, "mode": "off", "claim_code": "", "dashboards": True}))
|
||||
env = run()["env"]
|
||||
assert not (data / "claim-code").exists()
|
||||
assert env["CANTABILE_MODE"] == "off" and env["CANTABILE_DASHBOARDS"] == "1"
|
||||
|
||||
|
||||
def test_an_earlier_installs_mapping_is_handed_to_the_agent(box):
|
||||
run, data, etc = box
|
||||
share = data.parent / "share" / "cantabile"
|
||||
share.mkdir()
|
||||
(share / "mapping.yaml").write_text("version: 2\nassets: []\n")
|
||||
run()
|
||||
assert (data / "mapping-import.yaml").read_text() == "version: 2\nassets: []\n"
|
||||
assert (data / "mapping-import.yaml").stat().st_mode & 0o077 == 0
|
||||
|
||||
|
||||
HUB_WEB = ADDON.parent.parent / "hub" / "mkosi" / "mkosi.extra" / "usr" / "lib" / "cantabile" / "web"
|
||||
|
||||
|
||||
def addon_run_constants():
|
||||
import ast
|
||||
tree = ast.parse(RUN.read_text())
|
||||
want = ("CONSENT_TEXT", "CONTROL_TEXT", "CONSENT_VERSION", "CONSENT_SOURCE")
|
||||
return {n.targets[0].id: ast.literal_eval(n.value) for n in tree.body
|
||||
if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name) and n.targets[0].id in want}
|
||||
|
||||
|
||||
def test_consent_is_asked_in_the_configuration():
|
||||
m = manifest()
|
||||
assert m["options"]["consent_data"] is False and m["options"]["consent_control"] is False # off until the owner says yes
|
||||
assert m["schema"]["consent_data"] == "bool" and m["schema"]["consent_control"] == "bool"
|
||||
c = addon_run_constants()
|
||||
en = yaml.safe_load((ADDON / "translations" / "en.yaml").read_text())["configuration"]
|
||||
assert c["CONSENT_TEXT"] in " ".join(en["consent_data"]["description"].split())
|
||||
assert c["CONTROL_TEXT"][len("Allow Cantabile"):] in " ".join(en["consent_control"]["description"].split())
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HUB_WEB.exists(), reason="the Hub's panel is not beside the add-on")
|
||||
def test_consent_texts_and_version_are_the_hubs():
|
||||
import re
|
||||
web = HUB_WEB.read_text()
|
||||
c = addon_run_constants()
|
||||
assert f'CONSENT_VERSION = "{c["CONSENT_VERSION"]}"' in web
|
||||
hub_text = re.search(r'CONSENT_TEXT = M\("([^"]+)"\)', web).group(1)
|
||||
hub_control = "".join(re.findall(r'"([^"]*)"', re.search(r"CONTROL_TEXT = M\((.*?)\)\n", web, re.S).group(1)))
|
||||
assert (c["CONSENT_TEXT"], c["CONTROL_TEXT"]) == (hub_text, hub_control)
|
||||
|
||||
|
||||
def test_no_consent_no_connection(box):
|
||||
run, data, etc = box
|
||||
(data / "options.json").write_text(json.dumps({"consent_data": False, "consent_control": True, "mode": "shadow",
|
||||
"claim_code": "ABCD-EFGH-JKLM", "dashboards": True}))
|
||||
assert run() == {"consent": False} # no link, no agent
|
||||
assert not (data / "claim-code").exists() and Supervisor.seen == []
|
||||
c = json.loads((data / "state" / "consent.json").read_text())
|
||||
assert c["share"] is False and c["control"] is False # control needs sharing too
|
||||
assert c["by"] == "ha-addon-config"
|
||||
|
||||
|
||||
def test_consent_recorded_and_kept(box):
|
||||
run, data, etc = box
|
||||
state = data / "state"
|
||||
state.mkdir()
|
||||
(state / "consent.json").write_text(json.dumps({"recipients": {"building": {"granted": True, "at": 5}}}))
|
||||
assert run()["cmd"][0] == "cantabile-run"
|
||||
c = json.loads((state / "consent.json").read_text())
|
||||
assert (c["share"], c["control"], c["by"]) == (True, False, "ha-addon-config")
|
||||
assert c["source"] == "given at installation in the add-on's configuration"
|
||||
assert c["text_version"] == addon_run_constants()["CONSENT_VERSION"]
|
||||
assert c["texts"]["share"].startswith("Cantabile may receive") and c["recipients"]["building"]["granted"]
|
||||
assert (state / "consent.json").stat().st_mode & 0o077 == 0
|
||||
# unchanged: when it was given stays
|
||||
c["at"] = 1000
|
||||
(state / "consent.json").write_text(json.dumps(c))
|
||||
run()
|
||||
assert json.loads((state / "consent.json").read_text())["at"] == 1000
|
||||
# control given later, then sharing taken back
|
||||
opts = json.loads((data / "options.json").read_text())
|
||||
(data / "options.json").write_text(json.dumps(dict(opts, consent_control=True)))
|
||||
run()
|
||||
c = json.loads((state / "consent.json").read_text())
|
||||
assert c["control"] is True and c["at"] > 1000
|
||||
(data / "options.json").write_text(json.dumps(dict(opts, consent_data=False, consent_control=True)))
|
||||
assert run() == {"consent": False}
|
||||
c = json.loads((state / "consent.json").read_text())
|
||||
assert (c["share"], c["control"]) == (False, False) and c["recipients"]["building"]["granted"]
|
||||
|
||||
|
||||
def test_the_page_says_why_it_is_not_connected():
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
loader = importlib.machinery.SourceFileLoader("addon_run", str(RUN))
|
||||
m = importlib.util.module_from_spec(importlib.util.spec_from_loader("addon_run", loader))
|
||||
loader.exec_module(m)
|
||||
en, de = m.waiting_html("en-US,en;q=0.9"), m.waiting_html("de-DE,de;q=0.9")
|
||||
assert "Cantabile is not connected" in en and "Share energy data with Cantabile" in en and 'lang="en"' in en
|
||||
assert "Cantabile ist nicht verbunden" in de and "Energiedaten mit Cantabile teilen" in de
|
||||
# the names it points to are the configuration's
|
||||
for lang, page in (("en", en), ("de", de)):
|
||||
t = yaml.safe_load((ADDON / "translations" / f"{lang}.yaml").read_text())["configuration"]
|
||||
assert t["consent_data"]["name"] in page and t["consent_control"]["name"] in page
|
||||
|
||||
|
||||
def test_the_page_links_to_the_configuration():
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
loader = importlib.machinery.SourceFileLoader("addon_run", str(RUN))
|
||||
m = importlib.util.module_from_spec(importlib.util.spec_from_loader("addon_run", loader))
|
||||
loader.exec_module(m)
|
||||
page = m.waiting_html("en", "local_cantabile_edge")
|
||||
assert 'href="/hassio/addon/local_cantabile_edge/config"' in page and 'target="_top"' in page
|
||||
assert "prefers-color-scheme:dark" in page
|
||||
assert "href=" not in m.waiting_html("en", "") and "href=" not in m.waiting_html("en", "x/../y")
|
||||
Reference in new issue
Block a user