mirror of
https://github.com/home-assistant/supervisor.git
synced 2026-05-19 14:18:53 +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>
255 lines
8.4 KiB
Python
255 lines
8.4 KiB
Python
"""Test Resolution API."""
|
|
|
|
from http import HTTPStatus
|
|
from unittest.mock import AsyncMock
|
|
|
|
from aiohttp.test_utils import TestClient
|
|
import pytest
|
|
|
|
from supervisor.const import (
|
|
ATTR_ISSUES,
|
|
ATTR_SUGGESTIONS,
|
|
ATTR_UNHEALTHY,
|
|
ATTR_UNSUPPORTED,
|
|
CoreState,
|
|
)
|
|
from supervisor.coresys import CoreSys
|
|
from supervisor.exceptions import ResolutionError
|
|
from supervisor.resolution.const import (
|
|
ContextType,
|
|
IssueType,
|
|
SuggestionType,
|
|
UnhealthyReason,
|
|
UnsupportedReason,
|
|
)
|
|
from supervisor.resolution.data import Issue, Suggestion
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_base(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test resolution manager api."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_unsupported_reason(UnsupportedReason.OS)
|
|
coresys.resolution.add_suggestion(
|
|
Suggestion(SuggestionType.CLEAR_FULL_BACKUP, ContextType.SYSTEM)
|
|
)
|
|
coresys.resolution.create_issue(IssueType.FREE_SPACE, ContextType.SYSTEM)
|
|
|
|
resp = await api_client.get(f"{prefix}/resolution/info")
|
|
result = await resp.json()
|
|
assert UnsupportedReason.OS in result["data"][ATTR_UNSUPPORTED]
|
|
assert (
|
|
result["data"][ATTR_SUGGESTIONS][-1]["type"] == SuggestionType.CLEAR_FULL_BACKUP
|
|
)
|
|
assert result["data"][ATTR_ISSUES][-1]["type"] == IssueType.FREE_SPACE
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_dismiss_suggestion(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test resolution manager dismiss suggestion api."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_suggestion(
|
|
clear_backup := Suggestion(SuggestionType.CLEAR_FULL_BACKUP, ContextType.SYSTEM)
|
|
)
|
|
|
|
assert coresys.resolution.suggestions[-1].type == SuggestionType.CLEAR_FULL_BACKUP
|
|
await api_client.delete(f"{prefix}/resolution/suggestion/{clear_backup.uuid}")
|
|
assert clear_backup not in coresys.resolution.suggestions
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_apply_suggestion(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test resolution manager suggestion apply api."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_suggestion(
|
|
clear_backup := Suggestion(SuggestionType.CLEAR_FULL_BACKUP, ContextType.SYSTEM)
|
|
)
|
|
coresys.resolution.add_suggestion(
|
|
create_backup := Suggestion(
|
|
SuggestionType.CREATE_FULL_BACKUP, ContextType.SYSTEM
|
|
)
|
|
)
|
|
|
|
mock_backups = AsyncMock()
|
|
mock_health = AsyncMock()
|
|
coresys.backups.do_backup_full = mock_backups
|
|
coresys.resolution.healthcheck = mock_health
|
|
|
|
await api_client.post(f"{prefix}/resolution/suggestion/{clear_backup.uuid}")
|
|
await api_client.post(f"{prefix}/resolution/suggestion/{create_backup.uuid}")
|
|
|
|
assert clear_backup not in coresys.resolution.suggestions
|
|
assert create_backup not in coresys.resolution.suggestions
|
|
|
|
assert mock_backups.called
|
|
assert mock_health.called
|
|
|
|
with pytest.raises(ResolutionError):
|
|
await coresys.resolution.apply_suggestion(clear_backup)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_dismiss_issue(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test resolution manager issue apply api."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_issue(
|
|
updated_failed := Issue(IssueType.UPDATE_FAILED, ContextType.SYSTEM)
|
|
)
|
|
|
|
assert coresys.resolution.issues[-1].type == IssueType.UPDATE_FAILED
|
|
await api_client.delete(f"{prefix}/resolution/issue/{updated_failed.uuid}")
|
|
assert updated_failed not in coresys.resolution.issues
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_unhealthy(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test resolution manager api."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_unhealthy_reason(UnhealthyReason.DOCKER)
|
|
|
|
resp = await api_client.get(f"{prefix}/resolution/info")
|
|
result = await resp.json()
|
|
assert result["data"][ATTR_UNHEALTHY][-1] == UnhealthyReason.DOCKER
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_check_options(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test client API with checks options."""
|
|
api_client, prefix = api_client_with_prefix
|
|
free_space = coresys.resolution.check.get("free_space")
|
|
|
|
assert free_space.enabled
|
|
await api_client.post(
|
|
f"{prefix}/resolution/check/{free_space.slug}/options", json={"enabled": False}
|
|
)
|
|
assert not free_space.enabled
|
|
|
|
await api_client.post(
|
|
f"{prefix}/resolution/check/{free_space.slug}/options", json={"enabled": True}
|
|
)
|
|
assert free_space.enabled
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_resolution_check_run(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test client API with run check."""
|
|
api_client, prefix = api_client_with_prefix
|
|
await coresys.core.set_state(CoreState.RUNNING)
|
|
free_space = coresys.resolution.check.get("free_space")
|
|
|
|
free_space.run_check = AsyncMock()
|
|
|
|
await api_client.post(f"{prefix}/resolution/check/{free_space.slug}/run")
|
|
|
|
assert free_space.run_check.called
|
|
|
|
|
|
async def test_api_resolution_suggestions_for_issue(
|
|
coresys: CoreSys, api_client_with_prefix: tuple[TestClient, str]
|
|
):
|
|
"""Test getting suggestions that fix an issue."""
|
|
api_client, prefix = api_client_with_prefix
|
|
coresys.resolution.add_issue(
|
|
corrupt_repo := Issue(IssueType.CORRUPT_REPOSITORY, ContextType.STORE, "repo_1")
|
|
)
|
|
|
|
resp = await api_client.get(
|
|
f"{prefix}/resolution/issue/{corrupt_repo.uuid}/suggestions"
|
|
)
|
|
result = await resp.json()
|
|
|
|
assert result["data"]["suggestions"] == []
|
|
|
|
coresys.resolution.add_suggestion(
|
|
execute_reset := Suggestion(
|
|
SuggestionType.EXECUTE_RESET, ContextType.STORE, "repo_1"
|
|
)
|
|
)
|
|
coresys.resolution.add_suggestion(
|
|
execute_remove := Suggestion(
|
|
SuggestionType.EXECUTE_REMOVE, ContextType.STORE, "repo_1"
|
|
)
|
|
)
|
|
|
|
resp = await api_client.get(
|
|
f"{prefix}/resolution/issue/{corrupt_repo.uuid}/suggestions"
|
|
)
|
|
result = await resp.json()
|
|
|
|
suggestion = [
|
|
su for su in result["data"]["suggestions"] if su["uuid"] == execute_reset.uuid
|
|
]
|
|
assert len(suggestion) == 1
|
|
assert suggestion[0]["auto"] is True
|
|
|
|
suggestion = [
|
|
su for su in result["data"]["suggestions"] if su["uuid"] == execute_remove.uuid
|
|
]
|
|
assert len(suggestion) == 1
|
|
assert suggestion[0]["auto"] is False
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("method", "url"),
|
|
[("delete", "/resolution/issue/bad"), ("get", "/resolution/issue/bad/suggestions")],
|
|
)
|
|
async def test_issue_not_found(
|
|
api_client_with_prefix: tuple[TestClient, str], method: str, url: str
|
|
):
|
|
"""Test issue not found error."""
|
|
api_client, prefix = api_client_with_prefix
|
|
resp = await api_client.request(method, f"{prefix}{url}")
|
|
assert resp.status == 404
|
|
body = await resp.json()
|
|
assert body["message"] == "Issue bad does not exist"
|
|
assert body["error_key"] == "resolution_issue_not_found_error"
|
|
assert body["extra_fields"] == {"uuid": "bad"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("method", "url"),
|
|
[("delete", "/resolution/suggestion/bad"), ("post", "/resolution/suggestion/bad")],
|
|
)
|
|
async def test_suggestion_not_found(
|
|
api_client_with_prefix: tuple[TestClient, str], method: str, url: str
|
|
):
|
|
"""Test suggestion not found error."""
|
|
api_client, prefix = api_client_with_prefix
|
|
resp = await api_client.request(method, f"{prefix}{url}")
|
|
assert resp.status == 404
|
|
body = await resp.json()
|
|
assert body["message"] == "Suggestion bad does not exist"
|
|
assert body["error_key"] == "resolution_suggestion_not_found_error"
|
|
assert body["extra_fields"] == {"uuid": "bad"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("method", "url"),
|
|
[("post", "/resolution/check/bad/options"), ("post", "/resolution/check/bad/run")],
|
|
)
|
|
async def test_check_not_found(
|
|
api_client_with_prefix: tuple[TestClient, str], method: str, url: str
|
|
):
|
|
"""Test check not found error."""
|
|
api_client, prefix = api_client_with_prefix
|
|
resp = await api_client.request(method, f"{prefix}{url}")
|
|
assert resp.status == HTTPStatus.NOT_FOUND
|
|
body = await resp.json()
|
|
assert body["message"] == "Check 'bad' does not exist"
|
|
assert body["error_key"] == "resolution_check_not_found_error"
|
|
assert body["extra_fields"] == {"check": "bad"}
|