1
0
mirror of https://github.com/home-assistant/supervisor.git synced 2026-07-02 19:35:42 +01:00
Files
supervisor/tests/common.py
T
Stefan Agner a973d22e35 Derive App state from container state (#6890)
* Derive App state from container state

The App.state setter mixed two responsibilities: it both mutated a
private `_state` field and dispatched side effects (WebSocket events,
issue dismissal, startup_event signaling). On top of that, an installed
but never-started app stayed in AppState.UNKNOWN forever, because the
attach() image-only fallback never fires a container state-change event
and the AppState therefore kept its constructor default. Conceptually,
ContainerState.UNKNOWN ("container does not exist") and AppState.UNKNOWN
("nothing observed yet") happened to share a name but meant different
things, which made the distinction easy to lose.

Make App.state a pure derived property. The source of truth is the last
observed ContainerState (cached on the App), plus a sticky operation-
error flag for start/stop failures that the docker event stream cannot
reflect. When no container has been observed yet, the derivation falls
back to install signals: an attached instance (image present) is
STOPPED, otherwise UNKNOWN. As a side effect, an installed-but-never-
started app now correctly reports STOPPED instead of UNKNOWN.

container_state_changed updates the cached container state and routes
all side effects through a single _emit_state_change helper that diffs
old vs new derived state. The two start/stop failure paths route
through _set_operation_error. Uninstall resets the cached signals so
the derivation naturally returns UNKNOWN.

Tests use a new tests/common.force_app_state helper that pokes the
underlying signals directly; the production class no longer carries
test-only setters.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Fix App state drive to AppState.UNKNOWN

* Unify state mutation through _update_state

Previously, state-driving signal changes were spread across two helpers
(_set_operation_error, _emit_state_change(old_state)) and required each
caller to capture self.state before mutating a private field — leaking
implementation details to call sites and raising the "why am I emitting
the old state?" question pointed out in code review.

Replace both helpers with a single _update_state(*, container_state=,
operation_error=) entry point. Callers describe what changed via
keyword arguments (None leaves a signal untouched); the helper captures
the previous state, applies the updates, recomputes the derived state
and emits side effects if anything changed.

Diff against a tracked _last_state instead of a freshly derived
"current" state, so that an out-of-band mutation between updates does
not silently shift the comparison baseline. The concrete case is
App.uninstall: instance.remove() clears the docker meta mid-flow, which
would otherwise reshape the derivation (RUNNING with no healthcheck
becomes STARTED instead of STARTUP) and suppress the STARTUP transition
that resolves the start-wait task. As a side effect, the initial
UNKNOWN -> STOPPED transition on attach is also now reliably emitted.

Switch the uninstall path to ContainerState.UNKNOWN ("we know there is
no container") rather than the constructor sentinel None.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Cache app state instead of deriving on every read

Building on the previous commit, make App.state a plain read of a
cached _state field rather than re-deriving on every property access.
The derivation moves to _derive_state(), and _update_state() is the
sole place that recomputes and assigns _state, so the value consumers
read always matches what was last emitted to listeners.

This removes the _last_state bookkeeping introduced previously: with a
single cached value there is no longer a separate "derived now" vs
"last emitted" distinction to reconcile, and out-of-band mutations
(e.g. instance.remove() clearing _meta during uninstall) can no longer
silently shift what state returns between updates.

Call _update_state() at the end of load() so the cached state settles
once attach() has run. Image-only attaches do not fire a docker event,
so without this an installed app would stay in the constructor-default
UNKNOWN until first start; this also makes the initial transition on
attach observable to listeners.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Pass operation error to _derive_state instead of storing it

The two state-driving signals were not symmetric. _container_state is
genuinely persisted state ("the last thing docker told us") that
re-derivation legitimately reads across calls. _operation_error, on the
other hand, is a momentary "force ERROR for this transition" signal; the
persistence of an error condition already lives in the cached _state.

Storing it as an instance attribute implied a sticky cross-call behavior
that no call path actually exercised: every caller either set it
explicitly right before deriving (start/stop failures, container events)
or ran argless only at load time, where no failure has occurred.

Drop the _operation_error field and pass operation_error as a parameter
to _derive_state(), defaulting to False in _update_state(). A container
observation now supersedes a prior error implicitly via the default,
which lets the container-event and uninstall call sites drop their
explicit operation_error=False.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Settle load state synchronously from current_state

The argless _update_state() settle at the end of load() raced attach()'s
container-state event. attach() fires DOCKER_CONTAINER_STATE_CHANGE via
the bus, which schedules the container_state_changed listener as a task
rather than running it inline. In the deprecated-arch early-return path
there is no await between attach() and the settle, so the listener had
not run yet: _container_state was still None and the settle derived
STOPPED (instance attached) — emitting a transient UNKNOWN->STOPPED even
for a running container before the listener corrected it. The main path
only avoided this incidentally, by having awaits (check_image,
save_persist) in between for the listener to run.

Derive the load-time state synchronously from instance.current_state()
instead of relying on the asynchronously delivered event. current_state()
returns the real container state, or UNKNOWN when only an image is
present (which derives to STOPPED), so both paths settle correctly
without racing the event.

Add a regression test that loading a running container settles to
STARTED, and mock current_state() in the state-listener test which
relies on a clean UNKNOWN baseline.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01 19:50:06 +02:00

242 lines
8.3 KiB
Python

"""Common test functions."""
import asyncio
from collections.abc import Callable, Sequence
from datetime import datetime
from functools import partial
from importlib import import_module
from inspect import getclosurevars
import json
from pathlib import Path
from typing import Any, Self
from dbus_fast.aio.message_bus import MessageBus
from supervisor.apps.app import App
from supervisor.const import AppState, BusEvent
from supervisor.coresys import CoreSys
from supervisor.docker.const import ContainerState
from supervisor.jobs.decorator import Job
from supervisor.resolution.validate import get_valid_modules
from supervisor.utils.yaml import read_yaml_file
from .dbus_service_mocks.base import DBusServiceMock
def force_app_state(app: App, state: AppState) -> None:
"""Drive an app's derived state to ``state`` by setting underlying signals.
The ``App.state`` value is derived from the last observed container
state and a momentary operation-error signal. Tests sometimes need a
specific AppState as setup without spinning up real Docker events;
this helper maps each AppState back to plausible signals and routes
them through the normal state update path.
"""
# pylint: disable=protected-access
container_state: ContainerState | None = None
operation_error = False
match state:
case AppState.UNKNOWN:
# The derivation falls back to STOPPED when ``instance.attached``
# is true; clear the docker metadata so the helper is
# deterministic regardless of prior fixture setup.
app.instance._meta = None
container_state = ContainerState.UNKNOWN
case AppState.STOPPED:
container_state = ContainerState.STOPPED
case AppState.STARTED:
container_state = ContainerState.HEALTHY
case AppState.STARTUP:
container_state = ContainerState.RUNNING
# STARTUP only resolves from RUNNING when the container has a
# healthcheck configured; ensure one is present in the mocked
# container metadata.
meta = app.instance._meta or {}
meta.setdefault("Config", {})["Healthcheck"] = {"Test": ["CMD", "true"]}
app.instance._meta = meta
case AppState.ERROR:
operation_error = True
app._update_state(container_state=container_state, operation_error=operation_error)
async def fire_bus_event(coresys: CoreSys, event: BusEvent, data: Any) -> None:
"""Fire a bus event and await its listener tasks.
``Bus.fire_event`` is sync and returns the listener tasks it spawned.
Tests that drive a system under test by firing a bus event need to
wait for those listener tasks to finish before asserting; this helper
bundles the gather so call sites stay short.
"""
await asyncio.gather(*coresys.bus.fire_event(event, data))
async def wait_for(
predicate: Callable[[], bool],
*,
timeout: float = 5.0,
interval: float = 0.01,
) -> None:
"""Poll a synchronous predicate until truthy or the deadline elapses.
Useful when a test fires a D-Bus signal (or another out-of-band
trigger) and needs to observe state mutated by the resulting async
chain — e.g. a signal handler that schedules its own follow-up
tasks. Completes the moment the predicate is true, so the wait
costs only what's actually needed; this avoids the choice between a
fixed sleep that's fast on idle and racy under load and a fixed
sleep that's robust under load and wasteful on idle.
"""
deadline = asyncio.get_running_loop().time() + timeout
while not predicate():
if asyncio.get_running_loop().time() >= deadline:
raise AssertionError(f"Predicate did not become true within {timeout}s")
await asyncio.sleep(interval)
def get_fixture_path(filename: str) -> Path:
"""Get path for fixture."""
return Path(Path(__file__).parent.joinpath("fixtures"), filename)
def load_json_fixture(filename: str) -> Any:
"""Load a json fixture."""
path = get_fixture_path(filename)
return json.loads(path.read_text(encoding="utf-8"))
def load_yaml_fixture(filename: str) -> Any:
"""Load a YAML fixture."""
path = get_fixture_path(filename)
return read_yaml_file(path)
def load_fixture(filename: str) -> str:
"""Load a fixture."""
path = get_fixture_path(filename)
return path.read_text(encoding="utf-8")
def load_binary_fixture(filename: str) -> bytes:
"""Load a fixture without decoding."""
path = get_fixture_path(filename)
return path.read_bytes()
def exists_fixture(filename: str) -> bool:
"""Check if a fixture exists."""
path = get_fixture_path(filename)
return path.exists()
async def mock_dbus_services(
to_mock: dict[str, list[str] | str | None], bus: MessageBus
) -> dict[str, dict[str, DBusServiceMock] | DBusServiceMock]:
"""Mock specified dbus services on bus.
to_mock is dictionary where the key is a dbus service to mock (module must exist
in dbus_service_mocks). Value is the object path for the mocked service. Can also
be a list of object paths or None (if the mocked service defines the object path).
A dictionary is returned where the key is the dbus service to mock and the value
is the instance of the mocked service. If a list of object paths is provided,
the value is a dictionary where the key is the object path and value is the
mocked instance of the service for that object path.
"""
services: dict[str, list[DBusServiceMock] | DBusServiceMock] = {}
requested_names: set[str] = set()
for module in await asyncio.get_running_loop().run_in_executor(
None, partial(get_valid_modules, base=__file__), "dbus_service_mocks"
):
if module in to_mock:
service_module = import_module(f"{__package__}.dbus_service_mocks.{module}")
if service_module.BUS_NAME not in requested_names:
await bus.request_name(service_module.BUS_NAME)
requested_names.add(service_module.BUS_NAME)
if isinstance(to_mock[module], list):
services[module] = {
obj_path: service_module.setup(obj_path).export(bus)
for obj_path in to_mock[module]
}
else:
services[module] = service_module.setup(to_mock[module]).export(bus)
return services
def get_job_decorator(func) -> Job:
"""Get Job object of decorated function."""
# Access the closure of the wrapper function
job = getclosurevars(func).nonlocals["self"]
if not isinstance(job, Job):
raise TypeError(f"{func.__qualname__} is not a Job")
return job
def reset_last_call(func, group: str | None = None) -> None:
"""Reset last call for a function using the Job decorator."""
get_job_decorator(func).set_last_call(datetime.min, group)
def is_in_list(a: list, b: list):
"""Check if all elements in list a are in list b in order.
Taken from https://stackoverflow.com/a/69175987/12156188.
"""
for c in a:
if c in b:
b = b[b.index(c) :]
else:
return False
return True
class MockResponse:
"""Mock response for aiohttp requests."""
def __init__(self, *, status=200, text=""):
"""Initialize mock response."""
self.status = status
self._text = text
def update_text(self, text: str):
"""Update the text of the response."""
self._text = text
async def read(self):
"""Read the response body."""
return self._text.encode("utf-8")
async def text(self) -> str:
"""Return the response body as text."""
return self._text
async def __aenter__(self):
"""Enter the context manager."""
return self
async def __aexit__(self, exc_type, exc, tb):
"""Exit the context manager."""
class AsyncIterator:
"""Make list/fixture into async iterator for test mocks."""
def __init__(self, seq: Sequence[Any]) -> None:
"""Initialize with sequence."""
self.iter = iter(seq)
def __aiter__(self) -> Self:
"""Implement aiter."""
return self
async def __anext__(self) -> Any:
"""Return next in sequence."""
try:
return next(self.iter)
except StopIteration:
raise StopAsyncIteration from None