feat: Home Assistant OS driver over the WebSocket API (0.1.0) #1

Merged
christianmanivong merged 2 commits from feature/driver into main 2026-12-03 01:05:27 +00:00
29 changed files with 2441 additions and 1 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
jobs:
driver:
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
with:
standard-ref: main
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+18
View File
@@ -0,0 +1,18 @@
# Changelog
All notable changes to this driver. The format follows
[Keep a Changelog](https://keepachangelog.com/), versions follow
[Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
- `homeassistant` driver for Home Assistant OS and Supervised installs, through Home
Assistant's WebSocket API with an administrator's long-lived access token:
facts, interfaces and their addresses, host status (pending reboot, data disk),
pending updates of Core, the OS, the Supervisor and every add-on, add-ons as
services, backups running now.
- Actions: apply updates (add-ons first, the OS last), start, stop and restart an
add-on or switch its start at boot, refresh the update information, reboot and
shut down the host.
- Discovery: Home Assistant's web page on port 8123.
+73 -1
View File
@@ -1,4 +1,76 @@
# napalm-homeassistant
NAPALM driver for Home Assistant OS, built on
[napalm-device-types](https://git.netork.io/NAPALM/napalm-device-types).
[napalm-device-types](https://git.netork.io/NAPALM/napalm-device-types) (`OSDriver`).
It talks to Home Assistant's WebSocket API and, through it, to the Supervisor: the
same way Home Assistant's own settings pages do. Nothing is installed on the device,
no add-on and no SSH.
## Tested against
| Install | Versions |
|---|---|
| Home Assistant OS (VM, board `ova`) | OS 18.4, Core 2026.11.3, Supervisor 2026.11.0 — answer shapes from the Supervisor's source; not yet against a device |
The fixtures are built from the Supervisor 2026.11.0 API source and are replaced by
recordings from the first onboarded device (see `tests/fixtures/README.md`).
## Connection
`ws://<host>:8123/api/websocket`, or `wss://` with `use_ssl` (the default on port 443).
The credential is a **long-lived access token of a Home Assistant administrator**
(Profile → Security → Long-lived access tokens): the Supervisor calls are open to
administrators only. It goes in as the password or as `optional_args["token_value"]`;
the username is not used.
```python
from napalm import get_network_driver
driver = get_network_driver("homeassistant")
with driver("192.0.2.21", "", "<long-lived access token>") as device:
print(device.get_facts())
```
| Optional arg | |
|---|---|
| `port` | Home Assistant's port, default 8123 |
| `use_ssl` | `wss://` instead of `ws://`; default on port 443 |
| `ssl_verify` / `verify_ssl` | verify the certificate against the system's CAs (default true) |
| `tls_fingerprints`, `tls_certificate_observer` | certificate pinning as in device-types' `tls_certificates`; a changed certificate is refused before the token is sent |
| `token_value` | the access token, instead of the password |
## Supported
| Getter / action | |
|---|---|
| `get_facts` | vendor, board as model, hostname, OS, uptime, interfaces; without a Supervisor only Core's version |
| `get_interfaces`, `get_interfaces_ip` | the interfaces NetworkManager manages (no speed, no MTU) |
| `get_host_status` | pending reboot (an installed OS waiting for it, or the Supervisor's `reboot_required` issue), data disk usage |
| `get_available_updates` | `core`, `os`, `supervisor` and each add-on by its slug |
| `apply_updates` | add-ons first, then Supervisor, Core (waits until Home Assistant is back) and the OS last (the host restarts); no backup is taken first |
| `refresh_available_updates` | the Supervisor's `/reload_updates` |
| `get_services`, `manage_service` | add-ons by slug: start, stop, restart; enable/disable sets their start at boot |
| `get_running_backups` | the Supervisor's backup jobs in progress |
| `reboot_host`, `shutdown_host` | the host, through the Supervisor |
| Discovery | Home Assistant's web page on port 8123 |
## Not supported
Anything inside Home Assistant itself (entities, automations, integrations), the
Supervisor's health and unsupported reasons, listing or making backups, configuration
changes, Home Assistant Container or Core installs beyond their version (they have
no Supervisor).
## Development
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
```bash
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/pytest --cov
```
## License
Apache-2.0
+5
View File
@@ -0,0 +1,5 @@
"""NAPALM driver for Home Assistant OS."""
from napalm_homeassistant.driver import HomeAssistantDriver
__all__ = ["HomeAssistantDriver"]
+365
View File
@@ -0,0 +1,365 @@
"""NAPALM driver for Home Assistant OS over the Home Assistant WebSocket API.
It reads and acts through the Supervisor, which Home Assistant reaches for an
administrator's access token: no add-on and no SSH on the device.
Credentials
-----------
A long-lived access token of a Home Assistant administrator, as ``password`` or as
``optional_args["token_value"]`` (which wins). The username is not used.
Optional args
-------------
port : int
Home Assistant's port (default 8123).
use_ssl : bool
``wss://`` instead of ``ws://``; the default on port 443.
ssl_verify / verify_ssl : bool
Verify the certificate against the system's CAs (default True). Pinned
fingerprints (``tls_fingerprints``) are checked either way.
"""
from __future__ import annotations
import logging
import re
import ssl
import time
from collections.abc import Callable
from typing import Any, Protocol
from napalm.base.exceptions import ConnectionException
from napalm.base.models import FactsDict, InterfaceDict, InterfacesIPDict
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import (
ApplyUpdatesResultDict,
HostStatusDict,
ServiceDict,
UpdateDict,
)
from napalm_device_types.running_backups import RunningBackupDict, RunningBackupsMixin
from napalm_device_types.tls_certificates import CertificateCheck
from napalm_homeassistant.parsers import (
parse_facts,
parse_host_status,
parse_interfaces,
parse_interfaces_ip,
parse_running_backups,
parse_services,
parse_updates,
)
from napalm_homeassistant.parsers.system import VENDOR
from napalm_homeassistant.parsers.updates import CORE, OS, SUPERVISOR
from napalm_homeassistant.transport import (
UNKNOWN_COMMAND,
ConnectionLost,
HomeAssistantError,
connect,
start_session,
)
LOG = logging.getLogger(__name__)
DEFAULT_PORT = 8123
TLS_PORT = 443
WEBSOCKET_PATH = "/api/websocket"
#: How long one update may run: an image download on a slow line.
UPDATE_WAIT = 3600.0
#: How long Home Assistant may take to come back after an update of Core.
RESTART_WAIT = 900.0
RECONNECT_INTERVAL = 10.0
#: What apply_updates accepts as a name, as the contract has it.
PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9_\-\+\.]+$")
ADDON_SLUG = re.compile(r"^[a-z0-9_]+$")
ADDON_ACTIONS = frozenset({"start", "stop", "restart"})
BOOT_BY_ACTION = {"enable": "auto", "disable": "manual"}
#: The order updates run in: add-ons, then what restarts more and more of the host.
UPDATE_ORDER = {SUPERVISOR: 1, CORE: 2, OS: 3}
CORE_ONLY_MODEL = "Home Assistant (without Supervisor)"
class SupervisorApi(Protocol):
"""A logged-in connection to Home Assistant (``transport.Session``)."""
ha_version: str | None
def supervisor(
self,
endpoint: str,
method: str = "get",
data: dict[str, Any] | None = None,
*,
wait: float | None = None,
) -> Any: ...
def close(self) -> None: ...
class HomeAssistantDriver(RunningBackupsMixin, OSDriver):
"""Home Assistant OS (or a Supervised install) through Home Assistant's WebSocket."""
VENDOR = VENDOR
DRIVER_NAME = "homeassistant"
USES_SSH = False
#: Home Assistant OS boots and starts Core before the API answers again.
REBOOT_SETTLE_SECONDS = 180
default_port = DEFAULT_PORT
PORT_SPECS = [PortSpec("http", DEFAULT_PORT, ("/",), weight=6.0)]
HTTP_FINGERPRINT = [FingerprintRule("home assistant", weight=8.0, mandatory=True)]
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: dict[str, Any] | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.timeout = timeout
self.optional_args = dict(optional_args or {})
self.token = str(self.optional_args.get("token_value") or password or "")
self.port = int(self.optional_args.get("port") or DEFAULT_PORT)
self.use_ssl = bool(self.optional_args.get("use_ssl", self.port == TLS_PORT))
verify = self.optional_args.get("ssl_verify", self.optional_args.get("verify_ssl", True))
self.ssl_verify = bool(verify)
self.transport: SupervisorApi | None = None
@property
def url(self) -> str:
host = f"[{self.hostname}]" if ":" in self.hostname else self.hostname
scheme = "wss" if self.use_ssl else "ws"
return f"{scheme}://{host}:{self.port}{WEBSOCKET_PATH}"
# --- connection -------------------------------------------------------------------
def open(self) -> None:
if not self.token:
raise ConnectionException(
f"{self.hostname}: no access token; give a long-lived access token "
"as the password or as token_value"
)
self.transport = self._open_transport()
def _open_transport(self) -> SupervisorApi: # pragma: no cover - live I/O
tls: ssl.SSLContext | None = None
check: CertificateCheck | None = None
if self.use_ssl:
tls = ssl.create_default_context()
if not self.ssl_verify:
# The pinned fingerprint (CertificateCheck) stands in for the CA.
tls.check_hostname = False
tls.verify_mode = ssl.CERT_NONE
check = CertificateCheck(self.optional_args, self.hostname, self.port)
socket, certificate = connect(self.url, timeout=float(self.timeout), tls=tls)
return start_session(
socket, self.token, timeout=float(self.timeout), check=check, certificate=certificate
)
def close(self) -> None:
transport, self.transport = self.transport, None
if transport is not None:
try:
transport.close()
except Exception: # a connection Home Assistant dropped closes badly
LOG.debug("%s: closing a dropped connection failed", self.hostname)
def is_alive(self) -> dict[str, bool]:
return {"is_alive": self.transport is not None}
def _session(self) -> SupervisorApi:
if self.transport is None:
raise ConnectionException(f"{self.hostname}: not connected; call open() first")
return self.transport
def _get(self, endpoint: str) -> Any:
return self._session().supervisor(endpoint)
def _post(self, endpoint: str, data: dict[str, Any] | None = None, **kwargs: Any) -> Any:
return self._session().supervisor(endpoint, "post", data, **kwargs)
# --- getters ----------------------------------------------------------------------
def get_facts(self) -> FactsDict:
try:
host = self._get("/host/info")
except HomeAssistantError as exc:
if exc.code != UNKNOWN_COMMAND:
raise
return self._core_facts()
return parse_facts(host, self._get("/os/info"), self._get("/network/info"))
def _core_facts(self) -> FactsDict:
"""Home Assistant without a Supervisor: only Core's version is known."""
return {
"vendor": VENDOR,
"model": CORE_ONLY_MODEL,
"hostname": self.hostname,
"fqdn": self.hostname,
"os_version": f"Home Assistant Core {self._session().ha_version or ''}".strip(),
"serial_number": "",
"uptime": -1.0,
"interface_list": [],
}
def get_interfaces(self) -> dict[str, InterfaceDict]:
return parse_interfaces(self._get("/network/info"))
def get_interfaces_ip(self) -> dict[str, InterfacesIPDict]:
return parse_interfaces_ip(self._get("/network/info"))
def get_available_updates(self) -> list[UpdateDict]:
"""Core, the OS, the Supervisor and every add-on with a newer version."""
return parse_updates(
self._get("/core/info"),
self._get("/os/info"),
self._get("/supervisor/info"),
self._get("/addons"),
)
def get_host_status(self) -> HostStatusDict:
return parse_host_status(
self._get("/host/info"), self._get("/os/info"), self._get("/resolution/info")
)
def get_services(self) -> list[ServiceDict]:
"""Every installed add-on, by its slug."""
addons = self._get("/addons")
boots = {
str(addon["slug"]): str(self._get(f"/addons/{addon['slug']}/info").get("boot"))
for addon in addons.get("addons", [])
}
return parse_services(addons, boots)
def get_running_backups(self) -> list[RunningBackupDict]:
return parse_running_backups(self._get("/jobs/info"))
# --- add-ons ----------------------------------------------------------------------
def manage_service(self, name: str, action: str) -> dict[str, Any]:
"""Start, stop or restart an add-on; enable or disable its start at boot."""
if action not in ADDON_ACTIONS and action not in BOOT_BY_ACTION:
raise ValueError(f"unknown action {action!r}")
installed = {str(a["slug"]) for a in self._get("/addons").get("addons", [])}
if not ADDON_SLUG.fullmatch(name) or name not in installed:
raise ValueError(f"no installed add-on {name!r}")
try:
if action in BOOT_BY_ACTION:
self._post(f"/addons/{name}/options", {"boot": BOOT_BY_ACTION[action]})
else:
self._post(f"/addons/{name}/{action}")
except HomeAssistantError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": f"{action} {name}: done"}
# --- updates ----------------------------------------------------------------------
def refresh_available_updates(self) -> dict[str, Any]:
"""Has the Supervisor look up the newest versions again."""
try:
self._post("/reload_updates")
except HomeAssistantError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": "update information reloaded"}
def apply_updates(
self, packages: list[str], *, log: Callable[[str], None] | None = None
) -> ApplyUpdatesResultDict:
"""Updates the named parts (``core``, ``os``, ``supervisor``, add-on slugs).
An empty list updates everything pending. Add-ons go first, then the
Supervisor, Core and the OS, which restarts the host last. The run stops at
the first refused update.
"""
updates, missing = self._pending_updates(packages)
if missing:
return {
"success": False,
"output": "",
"error": f"no pending update for: {', '.join(missing)}",
}
lines: list[str] = []
def say(line: str) -> None:
lines.append(line)
if log is not None:
log(line)
for update in updates:
try:
self._apply_one(update, say)
except (HomeAssistantError, ConnectionException) as exc:
error = f"{update.get('title') or update['name']}: {exc}"
say(error)
return {"success": False, "output": "\n".join(lines), "error": error}
return {"success": True, "output": "\n".join(lines)}
def _pending_updates(self, packages: list[str]) -> tuple[list[UpdateDict], list[str]]:
"""The pending updates *packages* name (all for none), in the order they run,
and the names that have none pending."""
for name in packages:
if not PACKAGE_NAME.fullmatch(name):
raise ValueError(f"not an update name: {name!r}")
pending = {update["name"]: update for update in self.get_available_updates()}
wanted = list(packages) or list(pending)
missing = [name for name in wanted if name not in pending]
ordered = sorted((n for n in wanted if n in pending), key=lambda n: UPDATE_ORDER.get(n, 0))
return [pending[name] for name in ordered], missing
def _apply_one(self, update: UpdateDict, say: Callable[[str], None]) -> None:
name = update["name"]
title = update.get("title") or name
say(f"Updating {title} {update['current_version']} -> {update['new_version']}")
if name == OS:
self._post_expecting_restart("/os/update", {})
say("Home Assistant OS installed; the host restarts")
elif name == CORE:
if self._post_expecting_restart("/core/update", {"backup": False}):
say("Home Assistant Core is restarting")
self._wait_until_back()
say("Home Assistant Core is back")
elif name == SUPERVISOR:
self._post("/supervisor/update", {}, wait=UPDATE_WAIT)
else:
self._post(f"/store/addons/{name}/update", {"backup": False}, wait=UPDATE_WAIT)
say(f"{title} updated")
def _post_expecting_restart(self, endpoint: str, data: dict[str, Any]) -> bool:
"""Whether the connection dropped: Home Assistant restarting is the update going on."""
try:
self._post(endpoint, data, wait=UPDATE_WAIT)
except ConnectionLost:
return True
return False
def _wait_until_back(self) -> None:
deadline = time.monotonic() + RESTART_WAIT
self.close()
while True:
try:
self.transport = self._open_transport()
return
except ConnectionException as exc:
if time.monotonic() >= deadline:
raise ConnectionException(
f"Home Assistant did not come back within {RESTART_WAIT:g}s"
) from exc
time.sleep(RECONNECT_INTERVAL)
# --- power ------------------------------------------------------------------------
def reboot_host(self) -> None:
self._power("/host/reboot")
def shutdown_host(self) -> None:
self._power("/host/shutdown")
def _power(self, endpoint: str) -> None:
try:
self._post(endpoint, {})
except ConnectionLost:
return # the host is on its way down
except HomeAssistantError as exc:
raise RuntimeError(f"{self.hostname}: the Supervisor refused: {exc}") from exc
+24
View File
@@ -0,0 +1,24 @@
"""Pure functions: Supervisor answers in, the contract's dicts out."""
from napalm_homeassistant.parsers.jobs import parse_running_backups
from napalm_homeassistant.parsers.network import parse_interfaces, parse_interfaces_ip
from napalm_homeassistant.parsers.services import parse_services
from napalm_homeassistant.parsers.system import (
board_model,
parse_facts,
parse_host_status,
uptime_seconds,
)
from napalm_homeassistant.parsers.updates import parse_updates
__all__ = [
"board_model",
"parse_facts",
"parse_host_status",
"parse_interfaces",
"parse_interfaces_ip",
"parse_running_backups",
"parse_services",
"parse_updates",
"uptime_seconds",
]
+38
View File
@@ -0,0 +1,38 @@
"""Backups running now: the Supervisor's jobs (``/jobs/info``)."""
from __future__ import annotations
from collections.abc import Iterator
from datetime import datetime
from typing import Any
from napalm_device_types.running_backups import RunningBackupDict
#: The Supervisor's jobs that take a backup, full or partial.
BACKUP_JOBS = frozenset({"backup_manager_full_backup", "backup_manager_partial_backup"})
def _walk(jobs: list[dict[str, Any]]) -> Iterator[dict[str, Any]]:
for job in jobs:
yield job
yield from _walk(job.get("child_jobs") or [])
def _since(created: str | None) -> int | None:
return int(datetime.fromisoformat(created).timestamp()) if created else None
def parse_running_backups(info: dict[str, Any]) -> list[RunningBackupDict]:
"""Backup jobs started and not done (``done`` is None before a job starts)."""
return [
{
"kind": "backup",
# Home Assistant's own schedule and a backup started by hand look the same.
"job": None,
"task": str(job["uuid"]),
"guests": [],
"since": _since(job.get("created")),
}
for job in _walk(info.get("jobs", []))
if job.get("name") in BACKUP_JOBS and job.get("done") is False
]
+48
View File
@@ -0,0 +1,48 @@
"""The host's network: ``/network/info``, the interfaces NetworkManager manages."""
from __future__ import annotations
import ipaddress
from typing import Any
from napalm.base.models import InterfaceDict, InterfacesIPDict, InterfacesIPDictEntry
UNKNOWN = -1
def parse_interfaces(network: dict[str, Any]) -> dict[str, InterfaceDict]:
"""NAPALM's interfaces; the Supervisor names neither speed nor MTU."""
return {
str(entry["interface"]): {
"is_up": bool(entry.get("connected")),
"is_enabled": bool(entry.get("enabled")),
"description": "",
"last_flapped": float(UNKNOWN),
"speed": float(UNKNOWN),
"mtu": UNKNOWN,
"mac_address": str(entry.get("mac") or ""),
}
for entry in network.get("interfaces", [])
}
def _addresses(config: dict[str, Any] | None) -> dict[str, InterfacesIPDictEntry]:
found: dict[str, InterfacesIPDictEntry] = {}
for text in (config or {}).get("address", []):
interface = ipaddress.ip_interface(text)
found[str(interface.ip)] = {"prefix_length": interface.network.prefixlen}
return found
def parse_interfaces_ip(network: dict[str, Any]) -> dict[str, InterfacesIPDict]:
"""Each interface's addresses; an interface without any is left out."""
result: dict[str, InterfacesIPDict] = {}
for entry in network.get("interfaces", []):
families: InterfacesIPDict = {}
for family in ("ipv4", "ipv6"):
addresses = _addresses(entry.get(family))
if addresses:
families[family] = addresses
if families:
result[str(entry["interface"])] = families
return result
+35
View File
@@ -0,0 +1,35 @@
"""Add-ons as services: ``/addons`` and each add-on's ``boot`` setting."""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import (
SERVICE_RESULT_EXIT_CODE,
SERVICE_RESULT_SUCCESS,
ServiceDict,
)
STARTED = "started"
#: How the Supervisor's add-on states end a run. ``error``: the container failed or
#: exited with an error; an add-on it stopped on request is ``stopped``.
RESULTS = {
STARTED: SERVICE_RESULT_SUCCESS,
"stopped": SERVICE_RESULT_SUCCESS,
"error": SERVICE_RESULT_EXIT_CODE,
}
BOOT_AUTO = "auto"
def parse_services(addons: dict[str, Any], boots: dict[str, str]) -> list[ServiceDict]:
"""Each installed add-on; *boots* maps its slug to its ``boot`` setting."""
return [
{
"name": str(addon["slug"]),
"running": addon.get("state") == STARTED,
"enabled": boots.get(str(addon["slug"])) == BOOT_AUTO,
"pid": 0, # the Supervisor names no process
"result": RESULTS.get(str(addon.get("state"))),
}
for addon in addons.get("addons", [])
]
+112
View File
@@ -0,0 +1,112 @@
"""The host itself: ``/host/info``, ``/os/info`` and ``/resolution/info``."""
from __future__ import annotations
from datetime import datetime
from typing import Any
from napalm.base.models import FactsDict
from napalm_device_types.models import FilesystemUsageDict, HostStatusDict
VENDOR = "Home Assistant"
#: What a host without Home Assistant OS -- a Supervised install -- is called.
SUPERVISED_MODEL = "Home Assistant Supervised"
#: The Supervisor names the data partition's size in GiB, rounded to a tenth.
GIB = 1024**3
#: Where Home Assistant OS mounts the data partition the disk figures describe.
DATA_MOUNTPOINT = "/mnt/data"
#: The Supervisor's issue for a host that waits for a reboot.
REBOOT_ISSUE = "reboot_required"
MICROSECONDS = 1_000_000
#: Home Assistant OS boards by the name the Supervisor gives them.
BOARD_MODELS = {
"ova": "Virtual Machine",
"generic-x86-64": "Generic x86-64",
"generic-aarch64": "Generic AArch64",
"green": "Home Assistant Green",
"yellow": "Home Assistant Yellow",
"rpi3": "Raspberry Pi 3",
"rpi3-64": "Raspberry Pi 3",
"rpi4": "Raspberry Pi 4",
"rpi4-64": "Raspberry Pi 4",
"rpi5-64": "Raspberry Pi 5",
"odroid-n2": "ODROID-N2",
"khadas-vim3": "Khadas VIM3",
}
def board_model(board: str | None) -> str:
"""The product name of a Home Assistant OS *board*; a Supervised host has none."""
if not board:
return SUPERVISED_MODEL
return BOARD_MODELS.get(board, board)
def uptime_seconds(host: dict[str, Any]) -> float:
"""Seconds since the host booted, by its own clock; -1.0 when it does not say."""
booted = host.get("boot_timestamp")
now = host.get("dt_utc")
if not booted or not now:
return -1.0
return float(datetime.fromisoformat(str(now)).timestamp() - booted / MICROSECONDS)
def parse_facts(
host: dict[str, Any], os_info: dict[str, Any], network: dict[str, Any]
) -> FactsDict:
"""NAPALM's facts of a host with a Supervisor."""
hostname = str(host.get("hostname") or "")
return {
"vendor": VENDOR,
"model": board_model(os_info.get("board")),
"hostname": hostname,
"fqdn": hostname,
"os_version": str(host.get("operating_system") or ""),
"serial_number": "",
"uptime": uptime_seconds(host),
"interface_list": [str(i["interface"]) for i in network.get("interfaces", [])],
}
def _filesystems(host: dict[str, Any]) -> list[FilesystemUsageDict] | None:
total, used, free = (host.get(key) for key in ("disk_total", "disk_used", "disk_free"))
if total is None or used is None or free is None:
return None
return [
{
"mountpoint": DATA_MOUNTPOINT,
"total": _bytes(total),
"used": _bytes(used),
"available": _bytes(free),
}
]
def _bytes(gib: float) -> int:
return int(float(gib) * GIB)
def _reboot(os_info: dict[str, Any], resolution: dict[str, Any]) -> tuple[bool, str | None]:
pending = os_info.get("version_pending")
running = os_info.get("version")
if pending and pending != running:
return True, f"Home Assistant OS {pending} installed, {running} running"
if any(issue.get("type") == REBOOT_ISSUE for issue in resolution.get("issues", [])):
return True, "the Supervisor reports a reboot required"
return False, None
def parse_host_status(
host: dict[str, Any], os_info: dict[str, Any], resolution: dict[str, Any]
) -> HostStatusDict:
"""What the host says about its own state: a pending reboot, the data disk."""
required, reason = _reboot(os_info, resolution)
return {
"reboot_required": required,
"reboot_reason": reason,
# Core, the OS and add-ons each update on their own terms; no one answer.
"auto_updates": None,
"package_manager": None,
"filesystems": _filesystems(host),
}
+62
View File
@@ -0,0 +1,62 @@
"""Pending updates: Core, the OS, the Supervisor and every add-on."""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import UpdateDict
#: The names ``apply_updates`` takes for the parts that are no add-on. An add-on's
#: slug always carries its repository's prefix (``core_``, ``local_``, a hash), so
#: none of these can be an add-on's.
CORE = "core"
OS = "os"
SUPERVISOR = "supervisor"
TITLES = {
CORE: "Home Assistant Core",
OS: "Home Assistant OS",
SUPERVISOR: "Home Assistant Supervisor",
}
def _system_update(name: str, info: dict[str, Any], channel: str | None) -> UpdateDict | None:
if not info.get("update_available") or not info.get("version"):
return None
return {
"name": name,
"current_version": str(info["version"]),
"new_version": str(info.get("version_latest") or ""),
"origin": channel,
"title": TITLES[name],
}
def parse_updates(
core: dict[str, Any],
os_info: dict[str, Any],
supervisor: dict[str, Any],
addons: dict[str, Any],
) -> list[UpdateDict]:
"""What has a newer version; ``origin`` is the update channel or the add-on's repository."""
channel = supervisor.get("channel")
updates = [
update
for update in (
_system_update(CORE, core, channel),
_system_update(OS, os_info, channel),
_system_update(SUPERVISOR, supervisor, channel),
)
if update is not None
]
for addon in addons.get("addons", []):
if addon.get("update_available"):
updates.append(
{
"name": str(addon["slug"]),
"current_version": str(addon.get("version") or ""),
"new_version": str(addon.get("version_latest") or ""),
"origin": addon.get("repository"),
"title": str(addon.get("name") or addon["slug"]),
}
)
return updates
View File
Whitespace-only changes.
+194
View File
@@ -0,0 +1,194 @@
"""Home Assistant's WebSocket API: one logged-in connection, and Supervisor calls over it.
Home Assistant hands an administrator's ``supervisor/api`` messages on to its
Supervisor and answers with the Supervisor's ``data``. That is the whole way in:
no add-on, no SSH.
"""
from __future__ import annotations
import json
import logging
import ssl
from typing import Any, Protocol
from napalm.base.exceptions import (
ConnectAuthError,
ConnectionClosedException,
ConnectionException,
)
from napalm_device_types.tls_certificates import CertificateCheck
LOG = logging.getLogger(__name__)
SUPERVISOR_API = "supervisor/api"
#: Home Assistant's answer to a message type it does not know: no Supervisor.
UNKNOWN_COMMAND = "unknown_command"
#: The largest message accepted; the add-on list of a busy install stays far below.
MAX_MESSAGE_BYTES = 16 * 1024 * 1024
class HomeAssistantError(RuntimeError):
"""Home Assistant or its Supervisor refused a call."""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"{code}: {message}")
self.code = code
self.message = message
class ConnectionLost(ConnectionClosedException):
"""The connection closed before the answer came: Home Assistant went away."""
class Socket(Protocol):
"""A WebSocket that sends and receives text frames."""
def send(self, text: str) -> None: ...
def recv(self, timeout: float | None) -> str: ...
def close(self) -> None: ...
class Session:
"""A connection: numbered requests, each answer matched to its request by id."""
def __init__(self, socket: Socket, timeout: float) -> None:
self.socket = socket
self.timeout = timeout
self.ha_version: str | None = None
self._last_id = 0
def authenticate(self, token: str) -> None:
"""Log in with *token*; only after Home Assistant has asked for it."""
hello = self._receive(self.timeout)
if hello.get("type") != "auth_required":
raise ConnectionException(
f"not Home Assistant's WebSocket API: it opened with {hello.get('type')!r}"
)
self.socket.send(json.dumps({"type": "auth", "access_token": token}))
answer = self._receive(self.timeout)
if answer.get("type") == "auth_invalid":
raise ConnectAuthError(
f"Home Assistant refused the access token: {answer.get('message', '')}"
)
if answer.get("type") != "auth_ok":
raise ConnectionException(f"unexpected answer to the login: {answer.get('type')!r}")
self.ha_version = answer.get("ha_version")
def supervisor(
self,
endpoint: str,
method: str = "get",
data: dict[str, Any] | None = None,
*,
wait: float | None = None,
) -> Any:
"""Call the Supervisor's *endpoint*.
:param wait: For a call that runs long (an update): lifts Home Assistant's
own limit of 10 seconds and waits this many seconds for the answer.
"""
message: dict[str, Any] = {"type": SUPERVISOR_API, "endpoint": endpoint, "method": method}
if data is not None:
message["data"] = data
if wait is not None:
message["timeout"] = None
return self.call(message, wait=wait)
def call(self, message: dict[str, Any], *, wait: float | None = None) -> Any:
"""Send *message* and return the result of the answer to it."""
self._last_id += 1
request_id = self._last_id
LOG.debug("%s %s", message.get("type"), message.get("endpoint", ""))
self.socket.send(json.dumps({"id": request_id, **message}))
while True:
answer = self._receive(wait if wait is not None else self.timeout)
if answer.get("id") == request_id and answer.get("type") == "result":
break
if answer.get("success"):
return answer.get("result")
error = answer.get("error") or {}
raise HomeAssistantError(
str(error.get("code") or "unknown_error"), str(error.get("message") or "")
)
def close(self) -> None:
self.socket.close()
def _receive(self, timeout: float) -> dict[str, Any]:
try:
text = self.socket.recv(timeout)
except TimeoutError as exc:
raise ConnectionException(f"Home Assistant did not answer within {timeout:g}s") from exc
try:
answer = json.loads(text)
except ValueError as exc:
raise ConnectionException("Home Assistant answered with something not JSON") from exc
if not isinstance(answer, dict):
raise ConnectionException("Home Assistant answered with something not an object")
return answer
def start_session(
socket: Socket,
token: str,
*,
timeout: float,
check: CertificateCheck | None = None,
certificate: bytes | None = None,
) -> Session:
"""Log in over *socket*; a TLS *certificate* is judged by *check* before the token leaves.
The socket is closed when anything on the way fails.
"""
try:
if check is not None and certificate is not None:
check.verify(certificate)
session = Session(socket, timeout)
session.authenticate(token)
if check is not None and certificate is not None:
check.observe()
return session
except BaseException:
socket.close()
raise
class _WebSocket: # pragma: no cover - live I/O
"""The ``websockets`` sync client as a :class:`Socket`."""
def __init__(self, connection: Any) -> None:
self.connection = connection
def send(self, text: str) -> None:
self.connection.send(text)
def recv(self, timeout: float | None) -> str:
from websockets.exceptions import ConnectionClosed
try:
return str(self.connection.recv(timeout=timeout))
except ConnectionClosed as exc:
raise ConnectionLost(f"Home Assistant closed the connection: {exc}") from exc
def close(self) -> None:
self.connection.close()
def connect( # pragma: no cover - live I/O
url: str, *, timeout: float, tls: ssl.SSLContext | None
) -> tuple[Socket, bytes | None]:
"""Open *url*; the server's certificate in DER, for a TLS connection."""
from websockets.exceptions import InvalidHandshake, InvalidURI
from websockets.sync.client import connect as open_websocket
try:
connection = open_websocket(url, ssl=tls, open_timeout=timeout, max_size=MAX_MESSAGE_BYTES)
except (OSError, TimeoutError, InvalidHandshake, InvalidURI) as exc:
raise ConnectionException(f"cannot open {url}: {exc}") from exc
certificate = None
if isinstance(connection.socket, ssl.SSLSocket):
certificate = connection.socket.getpeercert(binary_form=True)
return _WebSocket(connection), certificate
+70
View File
@@ -0,0 +1,70 @@
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "napalm-homeassistant"
version = "0.1.0"
description = "NAPALM driver for Home Assistant OS over the Home Assistant WebSocket API"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.12"
authors = [{ name = "Christian Manivong", email = "christian@manivong.de" }]
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Topic :: System :: Networking",
"Topic :: Home Automation",
]
dependencies = [
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.56", # ServiceDict.result and its SERVICE_RESULT_* words
"websockets>=13.0", # the sync client with recv(timeout=)
]
[project.optional-dependencies]
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
[project.urls]
Repository = "https://git.netork.io/NAPALM/napalm-homeassistant"
Issues = "https://git.netork.io/NAPALM/napalm-homeassistant/issues"
[project.entry-points."napalm.drivers"]
homeassistant = "napalm_homeassistant:HomeAssistantDriver"
[tool.setuptools.packages.find]
include = ["napalm_homeassistant*"]
[tool.setuptools.package-data]
napalm_homeassistant = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.ruff.lint.per-file-ignores]
# Recorded device output keeps its lines.
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
[[tool.mypy.overrides]]
module = ["napalm.*"]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.coverage.run]
source = ["napalm_homeassistant"]
[tool.coverage.report]
fail_under = 90
exclude_also = ["pragma: no cover - live I/O"]
View File
Whitespace-only changes.
+94
View File
@@ -0,0 +1,94 @@
"""Fixtures and a stand-in for the Supervisor behind Home Assistant's WebSocket."""
from __future__ import annotations
import copy
import json
import pathlib
from typing import Any
import pytest
from napalm_homeassistant import HomeAssistantDriver
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
PREFIX = "haos-18.4-supervisor-2026.11.0-"
def load(name: str) -> Any:
"""The fixture *name* (without prefix and extension), a fresh copy each time."""
return json.loads((FIXTURES / f"{PREFIX}{name}.json").read_text())
def addon_info(slug: str) -> dict[str, Any]:
"""The part of ``/addons/<slug>/info`` the driver reads."""
return {"slug": slug, "boot": load("addon-boot")[slug]}
def device_answers() -> dict[tuple[str, str], Any]:
"""What the recorded Home Assistant OS answers, by (method, endpoint)."""
answers: dict[tuple[str, str], Any] = {
("get", "/host/info"): load("host-info"),
("get", "/os/info"): load("os-info"),
("get", "/core/info"): load("core-info"),
("get", "/supervisor/info"): load("supervisor-info"),
("get", "/network/info"): load("network-info"),
("get", "/addons"): load("addons"),
("get", "/resolution/info"): load("resolution-info"),
("get", "/jobs/info"): load("jobs-info"),
}
for slug in load("addon-boot"):
answers[("get", f"/addons/{slug}/info")] = addon_info(slug)
return answers
class FakeSupervisor:
"""Answers Supervisor calls from a table; an Exception in the table is raised.
A value that is a list is a sequence of answers, one per call, the last repeated.
"""
def __init__(self, answers: dict[tuple[str, str], Any] | None = None) -> None:
self.answers = answers if answers is not None else device_answers()
self.calls: list[dict[str, Any]] = []
self.closed = False
self.ha_version = "2026.11.3"
def supervisor(
self,
endpoint: str,
method: str = "get",
data: dict[str, Any] | None = None,
*,
wait: float | None = None,
) -> Any:
self.calls.append({"endpoint": endpoint, "method": method, "data": data, "wait": wait})
key = (method, endpoint)
if key not in self.answers:
if method == "post":
return {}
raise AssertionError(f"unexpected call {method.upper()} {endpoint}")
answer = self.answers[key]
if isinstance(answer, list):
answer = answer.pop(0) if len(answer) > 1 else answer[0]
if isinstance(answer, BaseException):
raise answer
return copy.deepcopy(answer)
def posted(self) -> list[tuple[str, dict[str, Any] | None]]:
return [(c["endpoint"], c["data"]) for c in self.calls if c["method"] == "post"]
def close(self) -> None:
self.closed = True
@pytest.fixture
def fake() -> FakeSupervisor:
return FakeSupervisor()
@pytest.fixture
def driver(fake: FakeSupervisor) -> HomeAssistantDriver:
device = HomeAssistantDriver("192.0.2.21", "", "token-123")
device.transport = fake
return device
+13
View File
@@ -0,0 +1,13 @@
# Fixtures
Each file is the `data` of one Supervisor API answer, as Home Assistant hands it
back over its WebSocket (`{"type": "supervisor/api", ...}` → `result`).
**These are not recordings yet.** They are built from the answer shapes in the
Supervisor 2026.11.0 source (`supervisor/api/*.py`) with values of a Home
Assistant OS 18.4 VM, anonymised (documentation addresses, a made-up hostname,
locally administered MACs). They are replaced by recorded output once the first
Home Assistant has been onboarded.
`haos-18.4-supervisor-2026.11.0-addon-boot.json` is not an answer: it maps each
add-on's slug to the `boot` of its `/addons/<slug>/info`.
@@ -0,0 +1,6 @@
{
"core_mosquitto": "auto",
"core_samba": "auto",
"a0d7b954_vscode": "manual",
"a0d7b954_ssh": "auto"
}
@@ -0,0 +1,84 @@
{
"addons": [
{
"name": "Mosquitto broker",
"slug": "core_mosquitto",
"description": "",
"stage": "stable",
"version": "7.1.3",
"version_latest": "7.1.3",
"update_available": false,
"available": true,
"detached": false,
"homeassistant": null,
"state": "started",
"repository": "core",
"build": false,
"url": null,
"icon": true,
"logo": true,
"system_managed": false,
"advanced": false
},
{
"name": "Samba share",
"slug": "core_samba",
"description": "",
"stage": "stable",
"version": "12.11.0",
"version_latest": "12.11.0",
"update_available": false,
"available": true,
"detached": false,
"homeassistant": null,
"state": "started",
"repository": "core",
"build": false,
"url": null,
"icon": true,
"logo": true,
"system_managed": false,
"advanced": false
},
{
"name": "Studio Code Server",
"slug": "a0d7b954_vscode",
"description": "",
"stage": "stable",
"version": "7.2.0",
"version_latest": "7.3.0",
"update_available": true,
"available": true,
"detached": false,
"homeassistant": null,
"state": "stopped",
"repository": "a0d7b954",
"build": false,
"url": null,
"icon": true,
"logo": true,
"system_managed": false,
"advanced": false
},
{
"name": "Advanced SSH & Web Terminal",
"slug": "a0d7b954_ssh",
"description": "",
"stage": "stable",
"version": "24.2.1",
"version_latest": "24.2.1",
"update_available": false,
"available": true,
"detached": false,
"homeassistant": null,
"state": "error",
"repository": "a0d7b954",
"build": false,
"url": null,
"icon": true,
"logo": true,
"system_managed": false,
"advanced": false
}
]
}
@@ -0,0 +1,17 @@
{
"version": "2026.11.3",
"version_latest": "2026.12.0",
"update_available": true,
"machine": "qemux86-64",
"ip_address": "172.30.32.1",
"arch": "amd64",
"image": "ghcr.io/home-assistant/qemux86-64-homeassistant",
"boot": true,
"port": 8123,
"ssl": false,
"watchdog": true,
"audio_input": null,
"audio_output": null,
"backups_exclude_database": false,
"duplicate_log_file": false
}
@@ -0,0 +1,38 @@
{
"agent_version": "1.14.0",
"apparmor_version": "3.1.2",
"chassis": "vm",
"virtualization": "kvm",
"cpe": "cpe:2.3:o:home-assistant:haos:18.4:*:production:*:*:*:ova:*",
"deployment": "production",
"disk_free": 17.1,
"disk_total": 30.8,
"disk_used": 12.3,
"disk_life_time": null,
"features": [
"reboot",
"shutdown",
"services",
"network",
"hostname",
"timedate",
"os_agent",
"haos",
"resolved",
"journal",
"disk",
"mount"
],
"hostname": "ha-lab-01",
"llmnr_hostname": "ha-lab-01",
"kernel": "6.18.58-haos",
"operating_system": "Home Assistant OS 18.4",
"timezone": "Europe/Berlin",
"dt_utc": "2026-12-03T08:00:00.000000+00:00",
"dt_synchronized": true,
"use_ntp": true,
"startup_time": 5.21,
"boot_timestamp": 1794556800000000,
"broadcast_llmnr": true,
"broadcast_mdns": true
}
@@ -0,0 +1,41 @@
{
"ignore_conditions": [],
"jobs": [
{
"name": "backup_manager_full_backup",
"reference": "8f3a2b1c",
"uuid": "0a1b2c3d4e5f60718293a4b5c6d7e8f9",
"progress": 42.0,
"stage": "addons",
"done": false,
"errors": [],
"created": "2026-12-03T07:55:00.000000+00:00",
"extra": null,
"child_jobs": []
},
{
"name": "backup_manager_partial_backup",
"reference": "1c2b3a4d",
"uuid": "1a1b2c3d4e5f60718293a4b5c6d7e8f9",
"progress": 100.0,
"stage": null,
"done": true,
"errors": [],
"created": "2026-12-03T03:00:00.000000+00:00",
"extra": null,
"child_jobs": []
},
{
"name": "addon_manager_update",
"reference": "core_samba",
"uuid": "2a1b2c3d4e5f60718293a4b5c6d7e8f9",
"progress": 10.0,
"stage": null,
"done": false,
"errors": [],
"created": "2026-12-03T07:59:00.000000+00:00",
"extra": null,
"child_jobs": []
}
]
}
@@ -0,0 +1,63 @@
{
"interfaces": [
{
"interface": "enp6s18",
"type": "ethernet",
"enabled": true,
"connected": true,
"primary": true,
"mac": "02:00:5E:10:00:21",
"ipv4": {
"method": "static",
"address": [
"192.0.2.21/24"
],
"nameservers": [
"192.0.2.4"
],
"gateway": "192.0.2.1",
"route_metric": null,
"ready": true
},
"ipv6": {
"method": "auto",
"addr_gen_mode": "default",
"ip6_privacy": "default",
"address": [
"2001:db8::21/64",
"fe80::5dbe:d5ae:4e3f:77bc/64"
],
"nameservers": [],
"gateway": "fe80::1",
"route_metric": null,
"ready": true
},
"wifi": null,
"vlan": null,
"mdns": "announce",
"llmnr": "announce"
},
{
"interface": "wlan0",
"type": "wireless",
"enabled": false,
"connected": false,
"primary": false,
"mac": "02:00:5E:10:00:22",
"ipv4": null,
"ipv6": null,
"wifi": null,
"vlan": null,
"mdns": "default",
"llmnr": "default"
}
],
"docker": {
"interface": "hassio",
"address": "172.30.32.0/23",
"gateway": "172.30.32.1",
"dns": "172.30.32.3"
},
"host_internet": true,
"supervisor_internet": true
}
@@ -0,0 +1,21 @@
{
"version": "18.4",
"version_latest": "18.5",
"version_pending": null,
"update_available": true,
"board": "ova",
"boot": "A",
"data_disk": "QEMU-QEMU_HARDDISK-0123456789",
"boot_slots": {
"A": {
"state": "booted",
"status": "good",
"version": "18.4"
},
"B": {
"state": "inactive",
"status": "good",
"version": "18.3"
}
}
}
@@ -0,0 +1,14 @@
{
"unsupported": [],
"unhealthy": [],
"suggestions": [],
"checks": [],
"issues": [
{
"uuid": "5c0d6f0e9a2b4c1d8e7f6a5b4c3d2e1f",
"type": "multiple_data_disks",
"context": "system",
"reference": "/dev/sdb1"
}
]
}
@@ -0,0 +1,22 @@
{
"version": "2026.11.0",
"version_latest": "2026.11.0",
"update_available": false,
"channel": "stable",
"arch": "amd64",
"supported": true,
"healthy": true,
"ip_address": "172.30.32.2",
"timezone": "Europe/Berlin",
"logging": "info",
"debug": false,
"debug_block": false,
"diagnostics": false,
"auto_update": true,
"detect_blocking_io": false,
"country": "DE",
"feature_flags": {},
"wait_boot": 5,
"addons": [],
"addons_repositories": []
}
+407
View File
@@ -0,0 +1,407 @@
"""The driver with its transport replaced: what it sends, what it returns."""
from __future__ import annotations
from typing import Any
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_homeassistant import HomeAssistantDriver
from napalm_homeassistant import driver as driver_module
from napalm_homeassistant.transport import ConnectionLost, HomeAssistantError
from tests.conftest import FakeSupervisor, load
REFUSED = HomeAssistantError("unknown_error", "refused by the Supervisor")
# --- registration and metadata -----------------------------------------------------------
def test_the_driver_is_registered_under_its_name() -> None:
from napalm import get_network_driver
assert get_network_driver("homeassistant") is HomeAssistantDriver
def test_metadata() -> None:
assert HomeAssistantDriver.DRIVER_NAME == "homeassistant"
assert HomeAssistantDriver.VENDOR == "Home Assistant"
assert HomeAssistantDriver.ROLE == "linux"
assert HomeAssistantDriver.TYPE_LABEL == "OS"
assert HomeAssistantDriver.USES_SSH is False
assert HomeAssistantDriver.default_port == 8123
assert any(rule.mandatory for rule in HomeAssistantDriver.HTTP_FINGERPRINT)
assert [spec.port for spec in HomeAssistantDriver.PORT_SPECS or []] == [8123]
# --- arguments ---------------------------------------------------------------------------
def test_the_token_comes_from_a_token_profile_before_the_password() -> None:
device = HomeAssistantDriver("ha", "", "pw", optional_args={"token_value": "tok"})
assert device.token == "tok"
def test_the_token_can_come_as_the_password() -> None:
assert HomeAssistantDriver("ha", "", "tok").token == "tok"
def test_plain_websocket_on_the_default_port() -> None:
device = HomeAssistantDriver("192.0.2.21", "", "tok")
assert device.port == 8123
assert device.url == "ws://192.0.2.21:8123/api/websocket"
def test_tls_on_port_443_or_when_asked() -> None:
assert (
HomeAssistantDriver("ha.example", "", "t", optional_args={"port": 443}).url
== "wss://ha.example:443/api/websocket"
)
assert (
HomeAssistantDriver("ha.example", "", "t", optional_args={"use_ssl": True}).url
== "wss://ha.example:8123/api/websocket"
)
def test_an_ipv6_address_is_bracketed() -> None:
assert (
HomeAssistantDriver("2001:db8::21", "", "t").url == "ws://[2001:db8::21]:8123/api/websocket"
)
def test_open_without_a_token_refuses() -> None:
with pytest.raises(ConnectionException, match="token"):
HomeAssistantDriver("ha", "", "").open()
# --- connection --------------------------------------------------------------------------
def test_open_takes_the_live_session(monkeypatch: pytest.MonkeyPatch) -> None:
fake = FakeSupervisor()
device = HomeAssistantDriver("ha", "", "tok")
monkeypatch.setattr(device, "_open_transport", lambda: fake)
device.open()
assert device.transport is fake
assert device.is_alive() == {"is_alive": True}
def test_a_getter_before_open_raises() -> None:
with pytest.raises(ConnectionException):
HomeAssistantDriver("ha", "", "tok").get_facts()
def test_close_closes_the_transport_once(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
driver.close()
driver.close()
assert fake.closed
assert driver.transport is None
assert driver.is_alive() == {"is_alive": False}
# --- getters -----------------------------------------------------------------------------
def test_get_facts(driver: HomeAssistantDriver) -> None:
facts = driver.get_facts()
assert facts["hostname"] == "ha-lab-01"
assert facts["os_version"] == "Home Assistant OS 18.4"
assert facts["interface_list"] == ["enp6s18", "wlan0"]
def test_facts_without_a_supervisor_come_from_core_alone(fake: FakeSupervisor) -> None:
fake.answers[("get", "/host/info")] = HomeAssistantError("unknown_command", "Unknown command.")
device = HomeAssistantDriver("192.0.2.21", "", "tok")
device.transport = fake
facts = device.get_facts()
assert facts == {
"vendor": "Home Assistant",
"model": "Home Assistant (without Supervisor)",
"hostname": "192.0.2.21",
"fqdn": "192.0.2.21",
"os_version": "Home Assistant Core 2026.11.3",
"serial_number": "",
"uptime": -1.0,
"interface_list": [],
}
def test_a_failed_read_of_the_facts_raises(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
fake.answers[("get", "/host/info")] = REFUSED
with pytest.raises(HomeAssistantError):
driver.get_facts()
def test_get_interfaces_and_addresses(driver: HomeAssistantDriver) -> None:
assert driver.get_interfaces()["enp6s18"]["is_up"] is True
assert driver.get_interfaces_ip()["enp6s18"]["ipv4"] == {"192.0.2.21": {"prefix_length": 24}}
def test_get_available_updates(driver: HomeAssistantDriver) -> None:
names = [u["name"] for u in driver.get_available_updates()]
assert names == ["core", "os", "a0d7b954_vscode"]
def test_a_failed_read_of_the_updates_raises(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
fake.answers[("get", "/addons")] = REFUSED
with pytest.raises(HomeAssistantError):
driver.get_available_updates()
def test_get_host_status(driver: HomeAssistantDriver) -> None:
status = driver.get_host_status()
assert status["reboot_required"] is False
assert status["filesystems"] and status["filesystems"][0]["mountpoint"] == "/mnt/data"
def test_get_services_reads_each_add_ons_boot_setting(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
services = driver.get_services()
assert [s["name"] for s in services] == [
"core_mosquitto",
"core_samba",
"a0d7b954_vscode",
"a0d7b954_ssh",
]
assert services[2]["enabled"] is False
assert {
"endpoint": "/addons/a0d7b954_vscode/info",
"method": "get",
"data": None,
"wait": None,
} in fake.calls
def test_get_running_backups(driver: HomeAssistantDriver) -> None:
assert [b["kind"] for b in driver.get_running_backups()] == ["backup"]
# --- services ----------------------------------------------------------------------------
@pytest.mark.parametrize("action", ["start", "stop", "restart"])
def test_manage_service_runs_the_add_on_action(
driver: HomeAssistantDriver, fake: FakeSupervisor, action: str
) -> None:
outcome = driver.manage_service("core_samba", action)
assert outcome["success"] is True
assert fake.posted() == [(f"/addons/core_samba/{action}", None)]
@pytest.mark.parametrize(("action", "boot"), [("enable", "auto"), ("disable", "manual")])
def test_enable_and_disable_set_the_boot_option(
driver: HomeAssistantDriver, fake: FakeSupervisor, action: str, boot: str
) -> None:
assert driver.manage_service("core_samba", action)["success"] is True
assert fake.posted() == [("/addons/core_samba/options", {"boot": boot})]
def test_an_unknown_action_is_refused(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
with pytest.raises(ValueError):
driver.manage_service("core_samba", "uninstall")
assert fake.posted() == []
@pytest.mark.parametrize("name", ["core_nothing", "../host", "core samba"])
def test_an_add_on_that_is_not_installed_is_refused(
driver: HomeAssistantDriver, fake: FakeSupervisor, name: str
) -> None:
with pytest.raises(ValueError):
driver.manage_service(name, "start")
assert fake.posted() == []
def test_a_refused_service_action_is_reported(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
fake.answers[("post", "/addons/core_samba/start")] = REFUSED
outcome = driver.manage_service("core_samba", "start")
assert outcome == {"success": False, "output": "unknown_error: refused by the Supervisor"}
# --- refreshing and applying updates -----------------------------------------------------
def test_refresh_reloads_the_update_information(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
assert driver.refresh_available_updates()["success"] is True
assert fake.posted() == [("/reload_updates", None)]
def test_a_refused_refresh_is_reported(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
fake.answers[("post", "/reload_updates")] = REFUSED
assert driver.refresh_available_updates()["success"] is False
@pytest.mark.parametrize("name", ["core;reboot", "a b", ""])
def test_apply_updates_refuses_unsafe_names(driver: HomeAssistantDriver, name: str) -> None:
with pytest.raises(ValueError):
driver.apply_updates([name])
def test_an_update_that_is_not_pending_runs_nothing(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
outcome = driver.apply_updates(["core_samba"])
assert outcome["success"] is False
assert "core_samba" in outcome["error"]
assert fake.posted() == []
def test_one_add_on_update(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
lines: list[str] = []
outcome = driver.apply_updates(["a0d7b954_vscode"], log=lines.append)
assert outcome["success"] is True
assert fake.posted() == [("/store/addons/a0d7b954_vscode/update", {"backup": False})]
assert lines[0] == "Updating Studio Code Server 7.2.0 -> 7.3.0"
assert outcome["output"] == "\n".join(lines)
update_call = [c for c in fake.calls if c["method"] == "post"][0]
assert update_call["wait"] == driver_module.UPDATE_WAIT
def test_everything_pending_runs_add_ons_first_and_the_os_last(
driver: HomeAssistantDriver, fake: FakeSupervisor, monkeypatch: pytest.MonkeyPatch
) -> None:
fake.answers[("post", "/core/update")] = ConnectionLost("closed")
fake.answers[("post", "/os/update")] = ConnectionLost("closed")
reopened: list[bool] = []
monkeypatch.setattr(driver, "_open_transport", lambda: reopened.append(True) or fake)
outcome = driver.apply_updates([])
assert outcome["success"] is True
assert fake.posted() == [
("/store/addons/a0d7b954_vscode/update", {"backup": False}),
("/core/update", {"backup": False}),
("/os/update", {}),
]
assert reopened == [True]
assert "Home Assistant Core is restarting" in outcome["output"]
assert "the host restarts" in outcome["output"]
def test_a_supervisor_update(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
supervisor = load("supervisor-info")
supervisor.update(update_available=True, version_latest="2026.12.0")
fake.answers[("get", "/supervisor/info")] = supervisor
assert driver.apply_updates(["supervisor"])["success"] is True
assert fake.posted() == [("/supervisor/update", {})]
def test_a_refused_update_stops_the_run(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
fake.answers[("post", "/store/addons/a0d7b954_vscode/update")] = REFUSED
outcome = driver.apply_updates([])
assert outcome["success"] is False
assert outcome["error"] == "Studio Code Server: unknown_error: refused by the Supervisor"
assert fake.posted() == [("/store/addons/a0d7b954_vscode/update", {"backup": False})]
def test_home_assistant_not_coming_back_after_core_ends_the_run(
driver: HomeAssistantDriver, fake: FakeSupervisor, monkeypatch: pytest.MonkeyPatch
) -> None:
fake.answers[("post", "/core/update")] = ConnectionLost("closed")
clock = iter([0.0, 10.0, 2000.0])
monkeypatch.setattr(driver_module.time, "monotonic", lambda: next(clock))
monkeypatch.setattr(driver_module.time, "sleep", lambda _: None)
def refuse() -> Any:
raise ConnectionException("connection refused")
monkeypatch.setattr(driver, "_open_transport", refuse)
outcome = driver.apply_updates(["core", "os"])
assert outcome["success"] is False
assert "did not come back" in outcome["error"]
assert ("/os/update", {}) not in fake.posted()
def test_home_assistant_coming_back_after_a_while(
driver: HomeAssistantDriver, fake: FakeSupervisor, monkeypatch: pytest.MonkeyPatch
) -> None:
fake.answers[("post", "/core/update")] = ConnectionLost("closed")
monkeypatch.setattr(driver_module.time, "sleep", lambda _: None)
attempts: list[int] = []
def back_on_the_third() -> Any:
attempts.append(1)
if len(attempts) < 3:
raise ConnectionException("connection refused")
return fake
monkeypatch.setattr(driver, "_open_transport", back_on_the_third)
assert driver.apply_updates(["core", "os"])["success"] is True
assert len(attempts) == 3
# --- power -------------------------------------------------------------------------------
@pytest.mark.parametrize(
("method", "endpoint"), [("reboot_host", "/host/reboot"), ("shutdown_host", "/host/shutdown")]
)
def test_power_actions(
driver: HomeAssistantDriver, fake: FakeSupervisor, method: str, endpoint: str
) -> None:
getattr(driver, method)()
assert fake.posted() == [(endpoint, {})]
def test_a_reboot_that_drops_the_connection_is_accepted(
driver: HomeAssistantDriver, fake: FakeSupervisor
) -> None:
fake.answers[("post", "/host/reboot")] = ConnectionLost("closed")
driver.reboot_host()
def test_a_refused_reboot_raises(driver: HomeAssistantDriver, fake: FakeSupervisor) -> None:
fake.answers[("post", "/host/reboot")] = REFUSED
with pytest.raises(RuntimeError, match="refused"):
driver.reboot_host()
def test_closing_a_dropped_connection_does_not_raise(
driver: HomeAssistantDriver, fake: FakeSupervisor, monkeypatch: pytest.MonkeyPatch
) -> None:
def broken() -> None:
raise OSError("socket is gone")
monkeypatch.setattr(fake, "close", broken)
driver.close()
assert driver.transport is None
+309
View File
@@ -0,0 +1,309 @@
"""The parsers: Supervisor answers in, the contract's dicts out."""
from __future__ import annotations
from napalm_homeassistant.parsers import (
board_model,
parse_facts,
parse_host_status,
parse_interfaces,
parse_interfaces_ip,
parse_running_backups,
parse_services,
parse_updates,
uptime_seconds,
)
from tests.conftest import load
GIB = 1024**3
# --- facts -------------------------------------------------------------------------------
def test_facts_of_a_home_assistant_os_vm() -> None:
facts = parse_facts(load("host-info"), load("os-info"), load("network-info"))
assert facts == {
"vendor": "Home Assistant",
"model": "Virtual Machine",
"hostname": "ha-lab-01",
"fqdn": "ha-lab-01",
"os_version": "Home Assistant OS 18.4",
"serial_number": "",
"uptime": 1_728_000.0,
"interface_list": ["enp6s18", "wlan0"],
}
def test_facts_of_a_supervised_install_name_no_board() -> None:
os_info = load("os-info")
os_info["board"] = None
host = load("host-info")
host["operating_system"] = "Debian GNU/Linux 13 (trixie)"
facts = parse_facts(host, os_info, load("network-info"))
assert facts["model"] == "Home Assistant Supervised"
assert facts["os_version"] == "Debian GNU/Linux 13 (trixie)"
def test_known_boards_have_their_product_names() -> None:
assert board_model("green") == "Home Assistant Green"
assert board_model("yellow") == "Home Assistant Yellow"
assert board_model("rpi5-64") == "Raspberry Pi 5"
assert board_model("generic-x86-64") == "Generic x86-64"
def test_an_unknown_board_is_named_as_the_supervisor_names_it() -> None:
assert board_model("odroid-m1s") == "odroid-m1s"
def test_uptime_is_unknown_without_a_boot_timestamp() -> None:
host = load("host-info")
host["boot_timestamp"] = None
assert uptime_seconds(host) == -1.0
def test_uptime_is_unknown_without_the_host_clock() -> None:
host = load("host-info")
del host["dt_utc"]
assert uptime_seconds(host) == -1.0
# --- interfaces --------------------------------------------------------------------------
def test_interfaces() -> None:
interfaces = parse_interfaces(load("network-info"))
assert interfaces["enp6s18"] == {
"is_up": True,
"is_enabled": True,
"description": "",
"last_flapped": -1.0,
"speed": -1.0,
"mtu": -1,
"mac_address": "02:00:5E:10:00:21",
}
assert interfaces["wlan0"]["is_up"] is False
assert interfaces["wlan0"]["is_enabled"] is False
def test_interface_addresses() -> None:
addresses = parse_interfaces_ip(load("network-info"))
assert addresses == {
"enp6s18": {
"ipv4": {"192.0.2.21": {"prefix_length": 24}},
"ipv6": {
"2001:db8::21": {"prefix_length": 64},
"fe80::5dbe:d5ae:4e3f:77bc": {"prefix_length": 64},
},
}
}
def test_an_interface_without_addresses_is_left_out() -> None:
network = load("network-info")
network["interfaces"][0]["ipv4"]["address"] = []
network["interfaces"][0]["ipv6"] = None
assert parse_interfaces_ip(network) == {}
# --- updates -----------------------------------------------------------------------------
def test_pending_updates_of_os_core_and_add_ons() -> None:
updates = parse_updates(
load("core-info"), load("os-info"), load("supervisor-info"), load("addons")
)
assert updates == [
{
"name": "core",
"current_version": "2026.11.3",
"new_version": "2026.12.0",
"origin": "stable",
"title": "Home Assistant Core",
},
{
"name": "os",
"current_version": "18.4",
"new_version": "18.5",
"origin": "stable",
"title": "Home Assistant OS",
},
{
"name": "a0d7b954_vscode",
"current_version": "7.2.0",
"new_version": "7.3.0",
"origin": "a0d7b954",
"title": "Studio Code Server",
},
]
def test_a_supervisor_update_is_listed() -> None:
supervisor = load("supervisor-info")
supervisor.update(update_available=True, version_latest="2026.12.0")
updates = parse_updates(load("core-info"), load("os-info"), supervisor, {"addons": []})
assert {
"name": "supervisor",
"current_version": "2026.11.0",
"new_version": "2026.12.0",
"origin": "stable",
"title": "Home Assistant Supervisor",
} in updates
def test_nothing_pending_is_an_empty_list() -> None:
core = load("core-info")
core["update_available"] = False
os_info = load("os-info")
os_info["update_available"] = False
assert parse_updates(core, os_info, load("supervisor-info"), {"addons": []}) == []
def test_a_supervised_install_has_no_os_update() -> None:
os_info = load("os-info")
os_info.update(version=None, version_latest=None, update_available=False, board=None)
core = load("core-info")
core["update_available"] = False
assert parse_updates(core, os_info, load("supervisor-info"), {"addons": []}) == []
# --- host status -------------------------------------------------------------------------
def test_host_status_with_nothing_pending() -> None:
status = parse_host_status(load("host-info"), load("os-info"), load("resolution-info"))
assert status == {
"reboot_required": False,
"reboot_reason": None,
"auto_updates": None,
"package_manager": None,
"filesystems": [
{
"mountpoint": "/mnt/data",
"total": int(30.8 * GIB),
"used": int(12.3 * GIB),
"available": int(17.1 * GIB),
}
],
}
def test_an_installed_os_waiting_for_the_reboot_names_both_versions() -> None:
os_info = load("os-info")
os_info["version_pending"] = "18.5"
status = parse_host_status(load("host-info"), os_info, load("resolution-info"))
assert status["reboot_required"] is True
assert status["reboot_reason"] == "Home Assistant OS 18.5 installed, 18.4 running"
def test_the_supervisors_reboot_issue_requires_a_reboot() -> None:
resolution = load("resolution-info")
resolution["issues"].append(
{"uuid": "ab", "type": "reboot_required", "context": "system", "reference": None}
)
status = parse_host_status(load("host-info"), load("os-info"), resolution)
assert status["reboot_required"] is True
assert status["reboot_reason"] == "the Supervisor reports a reboot required"
def test_disk_figures_missing_leave_the_filesystems_unread() -> None:
host = load("host-info")
host["disk_total"] = None
status = parse_host_status(host, load("os-info"), load("resolution-info"))
assert status["filesystems"] is None
# --- add-ons -----------------------------------------------------------------------------
def test_add_ons_as_services() -> None:
services = parse_services(load("addons"), load("addon-boot"))
assert services == [
{"name": "core_mosquitto", "running": True, "enabled": True, "pid": 0, "result": "success"},
{"name": "core_samba", "running": True, "enabled": True, "pid": 0, "result": "success"},
{
"name": "a0d7b954_vscode",
"running": False,
"enabled": False,
"pid": 0,
"result": "success",
},
{
"name": "a0d7b954_ssh",
"running": False,
"enabled": True,
"pid": 0,
"result": "exit-code",
},
]
def test_an_add_on_in_an_unknown_state_has_no_result() -> None:
addons = load("addons")
addons["addons"][0]["state"] = "unknown"
assert parse_services(addons, load("addon-boot"))[0]["result"] is None
def test_an_add_on_without_its_boot_setting_is_not_enabled() -> None:
services = parse_services(load("addons"), {})
assert [s["enabled"] for s in services] == [False, False, False, False]
# --- running backups ---------------------------------------------------------------------
def test_a_backup_in_progress_is_running() -> None:
assert parse_running_backups(load("jobs-info")) == [
{
"kind": "backup",
"job": None,
"task": "0a1b2c3d4e5f60718293a4b5c6d7e8f9",
"guests": [],
"since": 1_796_284_500,
}
]
def test_a_backup_nested_under_another_job_is_found() -> None:
jobs = load("jobs-info")
backup = jobs["jobs"].pop(0)
jobs["jobs"][1]["child_jobs"] = [backup]
assert [b["task"] for b in parse_running_backups(jobs)] == [backup["uuid"]]
def test_no_backup_running_is_an_empty_list() -> None:
jobs = load("jobs-info")
jobs["jobs"][0]["done"] = True
assert parse_running_backups(jobs) == []
def test_a_backup_without_a_creation_time_has_no_start() -> None:
jobs = load("jobs-info")
jobs["jobs"][0]["created"] = None
assert parse_running_backups(jobs)[0]["since"] is None
+253
View File
@@ -0,0 +1,253 @@
"""The WebSocket session with the socket replaced: what it sends, what it makes of answers."""
from __future__ import annotations
import hashlib
import json
from typing import Any
import pytest
from napalm.base.exceptions import ConnectAuthError, ConnectionException
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
from napalm_homeassistant.transport import (
ConnectionLost,
HomeAssistantError,
Session,
start_session,
)
TOKEN = "token-123"
AUTH_REQUIRED = {"type": "auth_required", "ha_version": "2026.11.3"}
AUTH_OK = {"type": "auth_ok", "ha_version": "2026.11.3"}
CERT = b"certificate-der"
class FakeSocket:
def __init__(self, *inbound: Any) -> None:
self.inbound = list(inbound)
self.sent: list[dict[str, Any]] = []
self.timeouts: list[float | None] = []
self.closed = False
def send(self, text: str) -> None:
self.sent.append(json.loads(text))
def recv(self, timeout: float | None) -> str:
self.timeouts.append(timeout)
item = self.inbound.pop(0)
if isinstance(item, BaseException):
raise item
return item if isinstance(item, str) else json.dumps(item)
def close(self) -> None:
self.closed = True
def result(request_id: int, value: Any) -> dict[str, Any]:
return {"id": request_id, "type": "result", "success": True, "result": value}
def logged_in(*inbound: Any) -> tuple[Session, FakeSocket]:
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK, *inbound)
session = Session(socket, timeout=30.0)
session.authenticate(TOKEN)
return session, socket
# --- login -------------------------------------------------------------------------------
def test_login_sends_the_token_and_keeps_the_version() -> None:
session, socket = logged_in()
assert socket.sent == [{"type": "auth", "access_token": TOKEN}]
assert session.ha_version == "2026.11.3"
def test_a_refused_token_is_an_authentication_error_that_does_not_name_it() -> None:
socket = FakeSocket(AUTH_REQUIRED, {"type": "auth_invalid", "message": "Invalid access token"})
with pytest.raises(ConnectAuthError) as raised:
Session(socket, timeout=30.0).authenticate(TOKEN)
assert "Invalid access token" in str(raised.value)
assert TOKEN not in str(raised.value)
def test_a_server_that_does_not_ask_for_a_login_is_refused_before_the_token_leaves() -> None:
socket = FakeSocket({"type": "hello"})
with pytest.raises(ConnectionException):
Session(socket, timeout=30.0).authenticate(TOKEN)
assert socket.sent == []
def test_an_unexpected_answer_to_the_login_is_a_connection_error() -> None:
socket = FakeSocket(AUTH_REQUIRED, {"type": "something_else"})
with pytest.raises(ConnectionException):
Session(socket, timeout=30.0).authenticate(TOKEN)
# --- calls -------------------------------------------------------------------------------
def test_a_supervisor_call_is_numbered_and_answered_by_its_id() -> None:
session, socket = logged_in(
{"id": 1, "type": "event", "event": {}},
result(7, "someone else's"),
result(1, {"hostname": "ha-lab-01"}),
result(2, {"version": "18.4"}),
)
assert session.supervisor("/host/info") == {"hostname": "ha-lab-01"}
assert session.supervisor("/os/info") == {"version": "18.4"}
assert socket.sent[1:] == [
{"id": 1, "type": "supervisor/api", "endpoint": "/host/info", "method": "get"},
{"id": 2, "type": "supervisor/api", "endpoint": "/os/info", "method": "get"},
]
def test_a_call_with_data_sends_it() -> None:
session, socket = logged_in(result(1, {}))
session.supervisor("/addons/core_samba/options", "post", {"boot": "auto"})
assert socket.sent[1]["data"] == {"boot": "auto"}
assert socket.sent[1]["method"] == "post"
def test_a_long_call_lifts_home_assistants_limit_and_waits_as_long_as_asked() -> None:
session, socket = logged_in(result(1, {}))
session.supervisor("/core/update", "post", {"backup": False}, wait=1800.0)
assert socket.sent[1]["timeout"] is None
assert socket.timeouts[-1] == 1800.0
def test_a_short_call_waits_the_session_timeout() -> None:
session, socket = logged_in(result(1, {}))
session.supervisor("/host/info")
assert "timeout" not in socket.sent[1]
assert socket.timeouts[-1] == 30.0
def test_a_refused_call_raises_with_home_assistants_code() -> None:
session, _ = logged_in(
{
"id": 1,
"type": "result",
"success": False,
"error": {"code": "unknown_command", "message": "Unknown command."},
}
)
with pytest.raises(HomeAssistantError) as raised:
session.supervisor("/host/info")
assert raised.value.code == "unknown_command"
assert raised.value.message == "Unknown command."
def test_a_refusal_without_details_still_raises() -> None:
session, _ = logged_in({"id": 1, "type": "result", "success": False})
with pytest.raises(HomeAssistantError) as raised:
session.supervisor("/host/info")
assert raised.value.code == "unknown_error"
def test_no_answer_in_time_is_a_connection_error() -> None:
session, _ = logged_in(TimeoutError())
with pytest.raises(ConnectionException, match="30"):
session.supervisor("/host/info")
def test_a_closed_connection_is_reported_as_lost() -> None:
session, _ = logged_in(ConnectionLost("closed"))
with pytest.raises(ConnectionLost):
session.supervisor("/host/info")
def test_an_answer_that_is_no_json_is_a_connection_error() -> None:
session, _ = logged_in("<html>")
with pytest.raises(ConnectionException):
session.supervisor("/host/info")
def test_close_closes_the_socket() -> None:
session, socket = logged_in()
session.close()
assert socket.closed
# --- certificate -------------------------------------------------------------------------
def test_a_certificate_other_than_the_trusted_one_is_refused_before_the_token_leaves() -> None:
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
seen: list[dict[str, Any]] = []
check = CertificateCheck(
{"tls_fingerprints": {"8123": "00" * 32}, "tls_certificate_observer": seen.append},
"192.0.2.21",
8123,
)
with pytest.raises(TlsCertificateMismatch):
start_session(socket, TOKEN, timeout=30.0, check=check, certificate=CERT)
assert socket.sent == []
assert socket.closed
assert seen[0]["accepted"] is False
def test_the_trusted_certificate_is_reported_once_the_login_stands() -> None:
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
seen: list[dict[str, Any]] = []
expected = hashlib.sha256(CERT).hexdigest()
check = CertificateCheck(
{"tls_fingerprints": {"8123": expected}, "tls_certificate_observer": seen.append},
"192.0.2.21",
8123,
)
session = start_session(socket, TOKEN, timeout=30.0, check=check, certificate=CERT)
assert session.ha_version == "2026.11.3"
assert seen[0]["accepted"] is True
def test_a_plain_connection_logs_in_without_a_certificate() -> None:
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
session = start_session(socket, TOKEN, timeout=30.0)
assert socket.sent == [{"type": "auth", "access_token": TOKEN}]
assert session.ha_version == "2026.11.3"
def test_a_failed_login_closes_the_socket() -> None:
socket = FakeSocket(AUTH_REQUIRED, {"type": "auth_invalid", "message": "no"})
with pytest.raises(ConnectAuthError):
start_session(socket, TOKEN, timeout=30.0)
assert socket.closed
def test_an_answer_that_is_no_object_is_a_connection_error() -> None:
session, _ = logged_in("[1, 2]")
with pytest.raises(ConnectionException):
session.supervisor("/host/info")