1
0
mirror of https://github.com/home-assistant/supervisor.git synced 2026-05-19 14:18:53 +01:00
Files
supervisor/tests/api/test_docker.py
T
Mike Degatano bc24fb5449 Refactor API registration to support v1/v2 via shared methods (#6769)
* 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>
2026-04-27 23:39:47 +02:00

174 lines
5.7 KiB
Python

"""Test Docker API."""
from aiohttp.test_utils import TestClient
import pytest
from supervisor.coresys import CoreSys
from supervisor.resolution.const import ContextType, IssueType, SuggestionType
from supervisor.resolution.data import Issue, Suggestion
from tests.dbus_service_mocks.agent_system import System as SystemService
from tests.dbus_service_mocks.base import DBusServiceMock
@pytest.mark.asyncio
async def test_api_docker_info(api_client_with_prefix: tuple[TestClient, str]):
"""Test docker info api."""
api_client, prefix = api_client_with_prefix
resp = await api_client.get(f"{prefix}/docker/info")
result = await resp.json()
assert result["data"]["logging"] == "journald"
assert result["data"]["storage"] == "overlay2"
assert result["data"]["version"] == "1.0.0"
async def test_api_network_enable_ipv6(
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
):
"""Test setting docker network for enabled IPv6."""
api_client, prefix = api_client_with_prefix
assert coresys.docker.config.enable_ipv6 is None
resp = await api_client.post(f"{prefix}/docker/options", json={"enable_ipv6": True})
assert resp.status == 200
assert coresys.docker.config.enable_ipv6 is True
resp = await api_client.get(f"{prefix}/docker/info")
assert resp.status == 200
body = await resp.json()
assert body["data"]["enable_ipv6"] is True
async def test_api_network_mtu(
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
):
"""Test setting docker network MTU."""
api_client, prefix = api_client_with_prefix
assert coresys.docker.config.mtu is None
resp = await api_client.post(f"{prefix}/docker/options", json={"mtu": 1450})
assert resp.status == 200
assert coresys.docker.config.mtu == 1450
resp = await api_client.get(f"{prefix}/docker/info")
assert resp.status == 200
body = await resp.json()
assert body["data"]["mtu"] == 1450
# Test setting MTU to None
resp = await api_client.post(f"{prefix}/docker/options", json={"mtu": None})
assert resp.status == 200
assert coresys.docker.config.mtu is None
resp = await api_client.get(f"{prefix}/docker/info")
assert resp.status == 200
body = await resp.json()
assert body["data"]["mtu"] is None
async def test_api_network_combined_options(
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
):
"""Test setting both IPv6 and MTU together."""
api_client, prefix = api_client_with_prefix
assert coresys.docker.config.enable_ipv6 is None
assert coresys.docker.config.mtu is None
resp = await api_client.post(
f"{prefix}/docker/options", json={"enable_ipv6": True, "mtu": 1400}
)
assert resp.status == 200
assert coresys.docker.config.enable_ipv6 is True
assert coresys.docker.config.mtu == 1400
resp = await api_client.get(f"{prefix}/docker/info")
assert resp.status == 200
body = await resp.json()
assert body["data"]["enable_ipv6"] is True
assert body["data"]["mtu"] == 1400
async def test_registry_not_found(api_client_with_prefix: tuple[TestClient, str]):
"""Test registry not found error."""
api_client, prefix = api_client_with_prefix
resp = await api_client.delete(f"{prefix}/docker/registries/bad")
assert resp.status == 404
body = await resp.json()
assert body["message"] == "Hostname bad does not exist in registries"
@pytest.mark.parametrize("os_available", ["17.0.rc1"], indirect=True)
async def test_api_migrate_docker_storage_driver(
api_client_with_prefix: tuple[TestClient, str],
coresys: CoreSys,
os_agent_services: dict[str, DBusServiceMock],
os_available,
):
"""Test Docker storage driver migration."""
api_client, prefix = api_client_with_prefix
system_service: SystemService = os_agent_services["agent_system"]
system_service.MigrateDockerStorageDriver.calls.clear()
resp = await api_client.post(
f"{prefix}/docker/migrate-storage-driver",
json={"storage_driver": "overlayfs"},
)
assert resp.status == 200
assert system_service.MigrateDockerStorageDriver.calls == [("overlayfs",)]
assert (
Issue(IssueType.REBOOT_REQUIRED, ContextType.SYSTEM)
in coresys.resolution.issues
)
assert (
Suggestion(SuggestionType.EXECUTE_REBOOT, ContextType.SYSTEM)
in coresys.resolution.suggestions
)
@pytest.mark.parametrize("os_available", ["17.0.rc1"], indirect=True)
async def test_api_migrate_docker_storage_driver_invalid_backend(
api_client_with_prefix: tuple[TestClient, str],
os_available,
):
"""Test 400 is returned for invalid storage driver."""
api_client, prefix = api_client_with_prefix
resp = await api_client.post(
f"{prefix}/docker/migrate-storage-driver",
json={"storage_driver": "invalid"},
)
assert resp.status == 400
async def test_api_migrate_docker_storage_driver_not_os(
api_client_with_prefix: tuple[TestClient, str],
coresys: CoreSys,
):
"""Test 404 is returned if not running on HAOS."""
api_client, prefix = api_client_with_prefix
resp = await api_client.post(
f"{prefix}/docker/migrate-storage-driver",
json={"storage_driver": "overlayfs"},
)
assert resp.status == 404
@pytest.mark.parametrize("os_available", ["16.2"], indirect=True)
async def test_api_migrate_docker_storage_driver_old_os(
api_client_with_prefix: tuple[TestClient, str],
coresys: CoreSys,
os_available,
):
"""Test 404 is returned if OS is older than 17.0."""
api_client, prefix = api_client_with_prefix
resp = await api_client.post(
f"{prefix}/docker/migrate-storage-driver",
json={"storage_driver": "overlayfs"},
)
assert resp.status == 404