1
0
mirror of https://github.com/home-assistant/supervisor.git synced 2026-05-19 06:08:51 +01:00
Files
supervisor/tests/common.py
T
Stefan Agner c772a9bbb0 Replace fixed-duration sleeps after bus events with gather (#6803)
* Replace fixed-duration sleeps after bus events with gather

Several tests use ``await asyncio.sleep(...)`` to "wait for the
listener to run" after firing a bus event. The fixed duration is
real wall-clock time and the wait can be indeterministic — if the
handler chain happens to need slightly more time on a busy CI
runner, the assertion races the handler.

``Bus.fire_event`` returns the listener tasks since #6252; capture
and ``await asyncio.gather(*tasks)`` instead of sleeping. Touches
test_bus.py (the bus tests were poking scheduling instead of
verifying their assertions), test_home_assistant_watchdog.py,
test_plugin_base.py, addons/test_manager.py, docker/test_addon.py,
and test_store_execute_reload.py.

Other cleanups in the same spirit:

- ``_fire_test_event`` in addons/test_addon.py becomes ``async def``
  and gathers the listener tasks itself, so its 17 call sites
  collapse to a single ``await _fire_test_event(...)``.
- The two test_store_execute_reload.py sites that used the private
  ``_update_connectivity()`` helper are reworked to set the cached
  connectivity flag directly and fire the event themselves so they
  can gather the listener tasks the same way.
- The two ``sleep(1)`` post-pull drains in docker/test_interface.py
  collapse to ``sleep(0)`` (handler tasks are already gathered
  inside pull_image), saving ~2s.
- The ``sleep(0.01)`` waits inside ``container_events()`` task
  bodies (api/test_addons.py, api/test_store.py,
  backups/test_manager.py) are just one-yield-to-the-parent and
  become ``sleep(0)``.

Switching to ``gather`` exposes a few latent test mocks that were
silently swallowing TypeErrors as background-task failures before:

- ``CGroup.add_devices_allowed`` is ``async def`` but was patched
  as a plain MagicMock in docker/test_addon.py — now patched via
  ``new_callable=AsyncMock``.
- The watchdog does ``await (await self.start())`` /
  ``await (await self.restart())`` because ``App.start`` /
  ``App.restart`` return ``asyncio.Task``. The mocks in
  addons/test_addon.py (test_app_watchdog, test_watchdog_on_stop,
  test_watchdog_during_attach) needed
  ``AsyncMock(return_value=<settled future>)`` to mirror that
  shape rather than a plain MagicMock.

* Factor bus.fire_event + gather pattern into a helper

Per review feedback, the ``await asyncio.gather(*coresys.bus.fire_event(...))``
incantation was scattered across many call sites. Add
``tests.common.fire_bus_event`` that takes the coresys, event and data,
fires the event and awaits the spawned listener tasks. Convert all
matching sites to use it, including the ``_fire_test_event`` wrapper
in addons/test_addon.py which now just builds the
``DockerContainerStateEvent`` and delegates.
2026-05-06 12:02:28 +02:00

181 lines
5.6 KiB
Python

"""Common test functions."""
import asyncio
from collections.abc import 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.const import BusEvent
from supervisor.coresys import CoreSys
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
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))
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