"""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//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