mirror of
https://github.com/home-assistant/supervisor.git
synced 2026-05-19 06:08:51 +01:00
bc24fb5449
* Refactor API registration to support v1/v2 via shared methods - Add AppVersion StrEnum (V1, V2) to supervisor/api/const.py - Replace self.v2_app with self._v2_app and expose a versions property (dict[AppVersion, web.Application]) computed dynamically so that test fixtures reassigning self.webapp are automatically reflected in V1 - All _register_* methods now accept a required app: web.Application parameter; version-specific routes are gated with "if app is self.versions[AppVersion.V1/V2]:" - load() loops over enabled_versions (V1 always, V2 when feature-flagged) and calls each registration method once per version, no duplication - Static resources are registered before webapp.add_subapp() to avoid registering into a frozen router - add_subapp uses self.webapp directly for readability - Fold _register_v2_apps/_register_v2_backups/_register_v2_store into their respective unified methods; remove the now-defunct _register_v2_* helpers and the _api_apps/_api_backups/_api_store instance vars - _register_proxy and _register_ingress updated to accept app; legacy /homeassistant/* proxy routes gated behind V1 conditional Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add dual v1/v2 parametrization to API tests All 163 tests across 17 API modules that register identically on both v1 and v2 now run against both versions via api_client_with_prefix. - tests/api/conftest.py: advanced_logs_tester switched to api_client_with_prefix so log-endpoint tests are auto-parametrized; accepts optional v2_path_prefix kwarg for paths that differ by version - tests/api/test_{auth,discovery,dns,docker,hardware,host,ingress, jobs,mounts,network,os,resolution,security,services,supervisor}.py: api_client -> api_client_with_prefix with path prefix unpacking - supervisor/api/__init__.py: _register_panel() moved outside the version loop -- frontend static assets are V1-only - tests/api/test_panel.py: kept on plain api_client (V1-only) Tests intentionally kept V1-only: - auth/discovery: use indirect api_client parametrize for addon context - homeassistant: all tests call legacy /homeassistant/* paths (V1-only) - jobs (4 tests): inner @Job-decorated classes register names into a module-level set; re-running the same test raises RuntimeError Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Extend dual v1/v2 parametrization to homeassistant and jobs tests tests/api/conftest.py: - Add core_api_client_with_root fixture parametrized over three paths: v1-core: /core/... (canonical v1 path) v1-legacy: /homeassistant/... (legacy v1 alias, same handlers) v2-core: /v2/core/... (canonical v2 path) tests/api/test_homeassistant.py: - Switch all 17 api_client tests to core_api_client_with_root so each test runs against all three access paths (v1 canonical, v1 legacy alias, v2 canonical), exercising every registered route tests/api/test_jobs.py: - Promote four inner TestClass definitions to module-level helpers (_JobsTreeTestHelper, _JobManualCleanupTestHelper, _JobsSortedTestHelper, _JobWithErrorTestHelper) so that @Job name registration into the global _JOB_NAMES set only happens once at import time rather than on each parametrized test run - Replace closure references to outer-scope coresys with self.coresys - Use api_client_with_prefix for dual-version coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix typo Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
269 lines
8.4 KiB
Python
269 lines
8.4 KiB
Python
"""Fixtures for API tests."""
|
|
|
|
from collections.abc import Awaitable, Callable
|
|
from unittest.mock import ANY, AsyncMock, MagicMock
|
|
|
|
from aiohttp import web
|
|
from aiohttp.test_utils import TestClient
|
|
import pytest
|
|
|
|
from supervisor.api import RestAPI
|
|
from supervisor.const import REQUEST_FROM, FeatureFlag
|
|
from supervisor.coresys import CoreSys
|
|
from supervisor.host.const import LogFormat, LogFormatter
|
|
|
|
DEFAULT_LOG_RANGE = "entries=:-99:100"
|
|
DEFAULT_LOG_RANGE_FOLLOW = "entries=:-99:18446744073709551615"
|
|
|
|
|
|
async def _common_test_api_advanced_logs(
|
|
path_prefix: str,
|
|
syslog_identifier: str,
|
|
formatter: LogFormatter,
|
|
api_client: TestClient,
|
|
journald_logs: MagicMock,
|
|
coresys: CoreSys,
|
|
os_available: None,
|
|
journal_logs_reader: MagicMock,
|
|
):
|
|
"""Template for tests of endpoints using advanced logs."""
|
|
resp = await api_client.get(f"{path_prefix}/logs")
|
|
assert resp.status == 200
|
|
assert resp.content_type == "text/plain"
|
|
|
|
journald_logs.assert_called_once_with(
|
|
params={"SYSLOG_IDENTIFIER": syslog_identifier},
|
|
range_header=DEFAULT_LOG_RANGE,
|
|
accept=LogFormat.JOURNAL,
|
|
)
|
|
journal_logs_reader.assert_called_with(ANY, formatter, False)
|
|
|
|
journald_logs.reset_mock()
|
|
journal_logs_reader.reset_mock()
|
|
|
|
resp = await api_client.get(f"{path_prefix}/logs?no_colors")
|
|
assert resp.status == 200
|
|
assert resp.content_type == "text/plain"
|
|
|
|
journald_logs.assert_called_once_with(
|
|
params={"SYSLOG_IDENTIFIER": syslog_identifier},
|
|
range_header=DEFAULT_LOG_RANGE,
|
|
accept=LogFormat.JOURNAL,
|
|
)
|
|
journal_logs_reader.assert_called_with(ANY, formatter, True)
|
|
|
|
journald_logs.reset_mock()
|
|
journal_logs_reader.reset_mock()
|
|
|
|
resp = await api_client.get(f"{path_prefix}/logs/follow")
|
|
assert resp.status == 200
|
|
assert resp.content_type == "text/plain"
|
|
|
|
journald_logs.assert_called_once_with(
|
|
params={"SYSLOG_IDENTIFIER": syslog_identifier, "follow": ""},
|
|
range_header=DEFAULT_LOG_RANGE_FOLLOW,
|
|
accept=LogFormat.JOURNAL,
|
|
)
|
|
journal_logs_reader.assert_called_with(ANY, formatter, False)
|
|
|
|
journald_logs.reset_mock()
|
|
journal_logs_reader.reset_mock()
|
|
|
|
mock_response = MagicMock()
|
|
mock_response.text = AsyncMock(
|
|
return_value='{"CONTAINER_LOG_EPOCH": "12345"}\n{"CONTAINER_LOG_EPOCH": "12345"}\n'
|
|
)
|
|
journald_logs.return_value.__aenter__.return_value = mock_response
|
|
|
|
resp = await api_client.get(f"{path_prefix}/logs/latest")
|
|
assert resp.status == 200
|
|
|
|
assert journald_logs.call_count == 2
|
|
|
|
# Check the first call for getting epoch
|
|
epoch_call = journald_logs.call_args_list[0]
|
|
assert epoch_call[1]["params"] == {"CONTAINER_NAME": syslog_identifier}
|
|
assert epoch_call[1]["range_header"] == "entries=:-1:2"
|
|
|
|
# Check the second call for getting logs with the epoch
|
|
logs_call = journald_logs.call_args_list[1]
|
|
assert logs_call[1]["params"]["SYSLOG_IDENTIFIER"] == syslog_identifier
|
|
assert logs_call[1]["params"]["CONTAINER_LOG_EPOCH"] == "12345"
|
|
assert logs_call[1]["range_header"] == "entries=:0:18446744073709551615"
|
|
journal_logs_reader.assert_called_with(ANY, formatter, True)
|
|
|
|
journald_logs.reset_mock()
|
|
journal_logs_reader.reset_mock()
|
|
|
|
resp = await api_client.get(f"{path_prefix}/logs/boots/0")
|
|
assert resp.status == 200
|
|
assert resp.content_type == "text/plain"
|
|
|
|
journald_logs.assert_called_once_with(
|
|
params={"SYSLOG_IDENTIFIER": syslog_identifier, "_BOOT_ID": "ccc"},
|
|
range_header=DEFAULT_LOG_RANGE,
|
|
accept=LogFormat.JOURNAL,
|
|
)
|
|
|
|
journald_logs.reset_mock()
|
|
|
|
resp = await api_client.get(f"{path_prefix}/logs/boots/0/follow")
|
|
assert resp.status == 200
|
|
assert resp.content_type == "text/plain"
|
|
|
|
journald_logs.assert_called_once_with(
|
|
params={
|
|
"SYSLOG_IDENTIFIER": syslog_identifier,
|
|
"_BOOT_ID": "ccc",
|
|
"follow": "",
|
|
},
|
|
range_header=DEFAULT_LOG_RANGE_FOLLOW,
|
|
accept=LogFormat.JOURNAL,
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def advanced_logs_tester(
|
|
api_client_with_prefix: tuple[TestClient, str],
|
|
journald_logs: MagicMock,
|
|
coresys: CoreSys,
|
|
os_available,
|
|
journal_logs_reader: MagicMock,
|
|
) -> Callable[..., Awaitable[None]]:
|
|
"""Fixture that returns a function to test advanced logs endpoints.
|
|
|
|
This allows tests to avoid explicitly passing all the required fixtures.
|
|
|
|
Usage:
|
|
async def test_my_logs(advanced_logs_tester):
|
|
await advanced_logs_tester("/path/prefix", "syslog_identifier")
|
|
"""
|
|
api_client, api_prefix = api_client_with_prefix
|
|
|
|
async def test_logs(
|
|
path_prefix: str,
|
|
syslog_identifier: str,
|
|
formatter: LogFormatter = LogFormatter.PLAIN,
|
|
*,
|
|
v2_path_prefix: str | None = None,
|
|
):
|
|
effective_path = (
|
|
v2_path_prefix
|
|
if (api_prefix and v2_path_prefix is not None)
|
|
else path_prefix
|
|
)
|
|
await _common_test_api_advanced_logs(
|
|
f"{api_prefix}{effective_path}",
|
|
syslog_identifier,
|
|
formatter,
|
|
api_client,
|
|
journald_logs,
|
|
coresys,
|
|
os_available,
|
|
journal_logs_reader,
|
|
)
|
|
|
|
return test_logs
|
|
|
|
|
|
@pytest.fixture(name="api_client_v2")
|
|
async def fixture_api_client_v2(aiohttp_client, coresys: CoreSys) -> TestClient:
|
|
"""Fixture for RestAPI client with v2 API enabled."""
|
|
coresys.config.set_feature_flag(FeatureFlag.SUPERVISOR_V2_API, True)
|
|
|
|
@web.middleware
|
|
async def _security_middleware(request: web.Request, handler: web.RequestHandler):
|
|
request[REQUEST_FROM] = coresys.homeassistant
|
|
return await handler(request)
|
|
|
|
api = RestAPI(coresys)
|
|
api.webapp = web.Application(middlewares=[_security_middleware])
|
|
api.start = AsyncMock()
|
|
await api.load()
|
|
yield await aiohttp_client(api.webapp)
|
|
|
|
|
|
@pytest.fixture(
|
|
name="api_client_with_prefix",
|
|
params=[pytest.param("", id="v1"), pytest.param("/v2", id="v2")],
|
|
)
|
|
async def fixture_api_client_with_prefix(
|
|
request: pytest.FixtureRequest,
|
|
api_client: TestClient,
|
|
api_client_v2: TestClient,
|
|
) -> tuple[TestClient, str]:
|
|
"""Fixture providing (client, path_prefix) for both v1 and v2 API paths.
|
|
|
|
Use this for APIs whose behavior is identical between v1 and v2 to confirm
|
|
both versions work correctly.
|
|
"""
|
|
if request.param == "":
|
|
return api_client, ""
|
|
return api_client_v2, "/v2"
|
|
|
|
|
|
@pytest.fixture(
|
|
name="core_api_client_with_root",
|
|
params=[
|
|
pytest.param("/core", id="v1-core"),
|
|
pytest.param("/homeassistant", id="v1-legacy"),
|
|
pytest.param("/v2/core", id="v2-core"),
|
|
],
|
|
)
|
|
async def fixture_core_api_client_with_root(
|
|
request: pytest.FixtureRequest,
|
|
api_client: TestClient,
|
|
api_client_v2: TestClient,
|
|
) -> tuple[TestClient, str]:
|
|
"""Fixture providing (client, path_root) for Home Assistant Core API endpoints.
|
|
|
|
Parametrizes over all three registered access paths:
|
|
v1-core: /core/... (canonical v1 path)
|
|
v1-legacy: /homeassistant/... (legacy v1 alias, same handlers)
|
|
v2-core: /v2/core/... (canonical v2 path)
|
|
"""
|
|
root: str = request.param
|
|
client = api_client_v2 if root.startswith("/v2") else api_client
|
|
return client, root
|
|
|
|
|
|
@pytest.fixture(
|
|
name="app_api_client_with_root",
|
|
params=[pytest.param("/addons", id="v1"), pytest.param("/v2/apps", id="v2")],
|
|
)
|
|
async def fixture_app_api_client_with_root(
|
|
request: pytest.FixtureRequest,
|
|
api_client: TestClient,
|
|
api_client_v2: TestClient,
|
|
) -> tuple[TestClient, str]:
|
|
"""Fixture providing (client, path_root) for both v1 and v2 app management paths.
|
|
|
|
v1 root: /addons/{slug}/...
|
|
v2 root: /v2/apps/{slug}/...
|
|
"""
|
|
root: str = request.param
|
|
client = api_client if root == "/addons" else api_client_v2
|
|
return client, root
|
|
|
|
|
|
@pytest.fixture(
|
|
name="store_app_api_client_with_root",
|
|
params=[
|
|
pytest.param("store/addons", id="v1"),
|
|
pytest.param("v2/store/apps", id="v2"),
|
|
],
|
|
)
|
|
async def fixture_store_app_api_client_with_root(
|
|
request: pytest.FixtureRequest,
|
|
api_client: TestClient,
|
|
api_client_v2: TestClient,
|
|
) -> tuple[TestClient, str]:
|
|
"""Fixture providing (client, resource_root) for both v1 and v2 store app paths.
|
|
|
|
v1 root: store/addons/{slug}/...
|
|
v2 root: v2/store/apps/{slug}/...
|
|
"""
|
|
resource: str = request.param
|
|
client = api_client_v2 if resource.startswith("v2/") else api_client
|
|
return client, resource
|