Rename backup sync agent to backup agent (#130575)

* Rename sync agent module to agent

* Rename BackupSyncAgent to BackupAgent

* Fix test typo

* Rename async_get_backup_sync_agents to async_get_backup_agents

* Rename and clean up remaining sync things

* Update kitchen sink

* Apply suggestions from code review

* Update test_manager.py

---------

Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
Martin Hjelmare
2024-11-14 02:00:49 +01:00
committed by GitHub
parent 957ece747d
commit f99b319048
10 changed files with 150 additions and 152 deletions

View File

@@ -5,17 +5,17 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.hassio import is_hassio
from homeassistant.helpers.typing import ConfigType
from .agent import BackupAgent, UploadedBackup
from .const import DOMAIN, LOGGER
from .http import async_register_http_views
from .manager import BackupManager
from .models import BackupSyncMetadata
from .sync_agent import BackupSyncAgent, SyncedBackup
from .models import BackupUploadMetadata
from .websocket import async_register_websocket_handlers
__all__ = [
"BackupSyncAgent",
"BackupSyncMetadata",
"SyncedBackup",
"BackupAgent",
"BackupUploadMetadata",
"UploadedBackup",
]
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)

View File

@@ -1,4 +1,4 @@
"""Backup sync agents for the Backup integration."""
"""Backup agents for the Backup integration."""
from __future__ import annotations
@@ -9,21 +9,21 @@ from typing import Any, Protocol
from homeassistant.core import HomeAssistant
from .models import BackupSyncMetadata, BaseBackup
from .models import BackupUploadMetadata, BaseBackup
@dataclass(slots=True)
class SyncedBackup(BaseBackup):
"""Synced backup class."""
class UploadedBackup(BaseBackup):
"""Uploaded backup class."""
id: str
class BackupSyncAgent(abc.ABC):
"""Define the format that backup sync agents can have."""
class BackupAgent(abc.ABC):
"""Define the format that backup agents can have."""
def __init__(self, name: str) -> None:
"""Initialize the backup sync agent."""
"""Initialize the backup agent."""
self.name = name
@abc.abstractmethod
@@ -36,9 +36,9 @@ class BackupSyncAgent(abc.ABC):
) -> None:
"""Download a backup file.
The `id` parameter is the ID of the synced backup that was returned in async_list_backups.
The `id` parameter is the ID of the backup that was returned in async_list_backups.
The `path` parameter is the full file path to download the synced backup to.
The `path` parameter is the full file path to download the backup to.
"""
@abc.abstractmethod
@@ -46,28 +46,28 @@ class BackupSyncAgent(abc.ABC):
self,
*,
path: Path,
metadata: BackupSyncMetadata,
metadata: BackupUploadMetadata,
**kwargs: Any,
) -> None:
"""Upload a backup.
The `path` parameter is the full file path to the backup that should be synced.
The `path` parameter is the full file path to the backup that should be uploaded.
The `metadata` parameter contains metadata about the backup that should be synced.
The `metadata` parameter contains metadata about the backup that should be uploaded.
"""
@abc.abstractmethod
async def async_list_backups(self, **kwargs: Any) -> list[SyncedBackup]:
async def async_list_backups(self, **kwargs: Any) -> list[UploadedBackup]:
"""List backups."""
class BackupPlatformAgentProtocol(Protocol):
class BackupAgentPlatformProtocol(Protocol):
"""Define the format that backup platforms can have."""
async def async_get_backup_sync_agents(
async def async_get_backup_agents(
self,
*,
hass: HomeAssistant,
**kwargs: Any,
) -> list[BackupSyncAgent]:
"""Register the backup sync agent."""
) -> list[BackupAgent]:
"""Register the backup agent."""

View File

@@ -31,9 +31,9 @@ from homeassistant.helpers.json import json_bytes
from homeassistant.util import dt as dt_util
from homeassistant.util.json import json_loads_object
from .agent import BackupAgent, BackupAgentPlatformProtocol
from .const import DOMAIN, EXCLUDE_FROM_BACKUP, LOGGER
from .models import BackupSyncMetadata, BaseBackup
from .sync_agent import BackupPlatformAgentProtocol, BackupSyncAgent
from .models import BackupUploadMetadata, BaseBackup
BUF_SIZE = 2**20 * 4 # 4MB
@@ -87,7 +87,7 @@ class BaseBackupManager(abc.ABC, Generic[_BackupT]):
self.backups: dict[str, _BackupT] = {}
self.loaded_platforms = False
self.platforms: dict[str, BackupPlatformProtocol] = {}
self.sync_agents: dict[str, BackupSyncAgent] = {}
self.backup_agents: dict[str, BackupAgent] = {}
self.syncing = False
@callback
@@ -109,14 +109,14 @@ class BaseBackupManager(abc.ABC, Generic[_BackupT]):
self,
hass: HomeAssistant,
integration_domain: str,
platform: BackupPlatformAgentProtocol,
platform: BackupAgentPlatformProtocol,
) -> None:
"""Add a platform to the backup manager."""
if not hasattr(platform, "async_get_backup_sync_agents"):
if not hasattr(platform, "async_get_backup_agents"):
return
agents = await platform.async_get_backup_sync_agents(hass=hass)
self.sync_agents.update(
agents = await platform.async_get_backup_agents(hass=hass)
self.backup_agents.update(
{f"{integration_domain}.{agent.name}": agent for agent in agents}
)
@@ -169,7 +169,7 @@ class BaseBackupManager(abc.ABC, Generic[_BackupT]):
wait_for_platforms=True,
)
LOGGER.debug("Loaded %s platforms", len(self.platforms))
LOGGER.debug("Loaded %s agents", len(self.sync_agents))
LOGGER.debug("Loaded %s agents", len(self.backup_agents))
self.loaded_platforms = True
@abc.abstractmethod
@@ -210,8 +210,8 @@ class BaseBackupManager(abc.ABC, Generic[_BackupT]):
"""Receive and store a backup file from upload."""
@abc.abstractmethod
async def async_sync_backup(self, *, slug: str, **kwargs: Any) -> None:
"""Sync a backup."""
async def async_upload_backup(self, *, slug: str, **kwargs: Any) -> None:
"""Upload a backup."""
class BackupManager(BaseBackupManager[Backup]):
@@ -223,11 +223,11 @@ class BackupManager(BaseBackupManager[Backup]):
self.backup_dir = Path(hass.config.path("backups"))
self.loaded_backups = False
async def async_sync_backup(self, *, slug: str, **kwargs: Any) -> None:
"""Sync a backup."""
async def async_upload_backup(self, *, slug: str, **kwargs: Any) -> None:
"""Upload a backup."""
await self.load_platforms()
if not self.sync_agents:
if not self.backup_agents:
return
if not (backup := await self.async_get_backup(slug=slug)):
@@ -238,7 +238,7 @@ class BackupManager(BaseBackupManager[Backup]):
*(
agent.async_upload_backup(
path=backup.path,
metadata=BackupSyncMetadata(
metadata=BackupUploadMetadata(
homeassistant=HAVERSION,
size=backup.size,
date=backup.date,
@@ -246,13 +246,13 @@ class BackupManager(BaseBackupManager[Backup]):
name=backup.name,
),
)
for agent in self.sync_agents.values()
for agent in self.backup_agents.values()
),
return_exceptions=True,
)
for result in sync_backup_results:
if isinstance(result, Exception):
LOGGER.error("Error during backup sync - %s", result)
LOGGER.error("Error during backup upload - %s", result)
self.syncing = False
async def load_backups(self) -> None:

View File

@@ -18,8 +18,8 @@ class BaseBackup:
@dataclass()
class BackupSyncMetadata:
"""Backup sync metadata."""
class BackupUploadMetadata:
"""Backup upload metadata."""
date: str # The date the backup was created
slug: str # The slug of the backup

View File

@@ -17,12 +17,12 @@ def async_register_websocket_handlers(hass: HomeAssistant, with_hassio: bool) ->
"""Register websocket commands."""
websocket_api.async_register_command(hass, backup_agents_download)
websocket_api.async_register_command(hass, backup_agents_info)
websocket_api.async_register_command(hass, backup_agents_list_synced_backups)
websocket_api.async_register_command(hass, backup_agents_list_backups)
if with_hassio:
websocket_api.async_register_command(hass, handle_backup_end)
websocket_api.async_register_command(hass, handle_backup_start)
websocket_api.async_register_command(hass, handle_backup_sync)
websocket_api.async_register_command(hass, handle_backup_upload)
return
websocket_api.async_register_command(hass, handle_details)
@@ -173,26 +173,26 @@ async def handle_backup_end(
@websocket_api.ws_require_user(only_supervisor=True)
@websocket_api.websocket_command(
{
vol.Required("type"): "backup/sync",
vol.Required("type"): "backup/upload",
vol.Required("data"): {
vol.Required("slug"): str,
},
}
)
@websocket_api.async_response
async def handle_backup_sync(
async def handle_backup_upload(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Backup sync notification."""
LOGGER.debug("Backup sync notification")
"""Backup upload."""
LOGGER.debug("Backup upload notification")
data = msg["data"]
try:
await hass.data[DATA_MANAGER].async_sync_backup(slug=data["slug"])
await hass.data[DATA_MANAGER].async_upload_backup(slug=data["slug"])
except Exception as err: # noqa: BLE001
connection.send_error(msg["id"], "backup_sync_failed", str(err))
connection.send_error(msg["id"], "backup_upload_failed", str(err))
return
connection.send_result(msg["id"])
@@ -212,25 +212,25 @@ async def backup_agents_info(
connection.send_result(
msg["id"],
{
"agents": [{"id": agent_id} for agent_id in manager.sync_agents],
"agents": [{"id": agent_id} for agent_id in manager.backup_agents],
"syncing": manager.syncing,
},
)
@websocket_api.require_admin
@websocket_api.websocket_command({vol.Required("type"): "backup/agents/synced"})
@websocket_api.websocket_command({vol.Required("type"): "backup/agents/list_backups"})
@websocket_api.async_response
async def backup_agents_list_synced_backups(
async def backup_agents_list_backups(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Return a list of synced backups."""
"""Return a list of uploaded backups."""
manager = hass.data[DATA_MANAGER]
backups: list[dict[str, Any]] = []
await manager.load_platforms()
for agent_id, agent in manager.sync_agents.items():
for agent_id, agent in manager.backup_agents.items():
_listed_backups = await agent.async_list_backups()
backups.extend({**b.as_dict(), "agent_id": agent_id} for b in _listed_backups)
connection.send_result(msg["id"], backups)
@@ -241,7 +241,7 @@ async def backup_agents_list_synced_backups(
{
vol.Required("type"): "backup/agents/download",
vol.Required("agent"): str,
vol.Required("sync_id"): str,
vol.Required("backup_id"): str,
vol.Required("slug"): str,
}
)
@@ -251,18 +251,18 @@ async def backup_agents_download(
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Download a synced backup."""
"""Download an uploaded backup."""
manager = hass.data[DATA_MANAGER]
await manager.load_platforms()
if not (agent := manager.sync_agents.get(msg["agent"])):
if not (agent := manager.backup_agents.get(msg["agent"])):
connection.send_error(
msg["id"], "unknown_agent", f"Agent {msg['agent']} not found"
)
return
try:
await agent.async_download_backup(
id=msg["sync_id"],
id=msg["backup_id"],
path=Path(hass.config.path("backup"), f"{msg['slug']}.tar"),
)
except Exception as err: # noqa: BLE001

View File

@@ -8,9 +8,9 @@ from typing import Any
from uuid import uuid4
from homeassistant.components.backup import (
BackupSyncAgent,
BackupSyncMetadata,
SyncedBackup,
BackupAgent,
BackupUploadMetadata,
UploadedBackup,
)
from homeassistant.core import HomeAssistant
@@ -19,19 +19,19 @@ LOGGER = logging.getLogger(__name__)
async def async_get_backup_sync_agents(
hass: HomeAssistant,
) -> list[BackupSyncAgent]:
"""Register the backup sync agents."""
return [KitchenSinkBackupSyncAgent("syncer")]
) -> list[BackupAgent]:
"""Register the backup agents."""
return [KitchenSinkBackupAgent("syncer")]
class KitchenSinkBackupSyncAgent(BackupSyncAgent):
"""Kitchen sink backup sync agent."""
class KitchenSinkBackupAgent(BackupAgent):
"""Kitchen sink backup agent."""
def __init__(self, name: str) -> None:
"""Initialize the kitchen sink backup sync agent."""
super().__init__(name)
self._uploads = [
SyncedBackup(
UploadedBackup(
id="def456",
name="Kitchen sink syncer",
slug="abc123",
@@ -54,13 +54,13 @@ class KitchenSinkBackupSyncAgent(BackupSyncAgent):
self,
*,
path: Path,
metadata: BackupSyncMetadata,
metadata: BackupUploadMetadata,
**kwargs: Any,
) -> None:
"""Upload a backup."""
LOGGER.info("Uploading backup %s %s", path.name, metadata)
self._uploads.append(
SyncedBackup(
UploadedBackup(
id=uuid4().hex,
name=metadata.name,
slug=metadata.slug,
@@ -69,6 +69,6 @@ class KitchenSinkBackupSyncAgent(BackupSyncAgent):
)
)
async def async_list_backups(self, **kwargs: Any) -> list[SyncedBackup]:
async def async_list_backups(self, **kwargs: Any) -> list[UploadedBackup]:
"""List synced backups."""
return self._uploads

View File

@@ -7,9 +7,9 @@ from typing import Any
from unittest.mock import patch
from homeassistant.components.backup import DOMAIN
from homeassistant.components.backup.agent import BackupAgent, UploadedBackup
from homeassistant.components.backup.manager import Backup
from homeassistant.components.backup.models import BackupSyncMetadata
from homeassistant.components.backup.sync_agent import BackupSyncAgent, SyncedBackup
from homeassistant.components.backup.models import BackupUploadMetadata
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
@@ -23,8 +23,8 @@ TEST_BACKUP = Backup(
)
class BackupSyncAgentTest(BackupSyncAgent):
"""Test backup sync agent."""
class BackupAgentTest(BackupAgent):
"""Test backup agent."""
async def async_download_backup(
self,
@@ -39,15 +39,15 @@ class BackupSyncAgentTest(BackupSyncAgent):
self,
*,
path: Path,
metadata: BackupSyncMetadata,
metadata: BackupUploadMetadata,
**kwargs: Any,
) -> None:
"""Upload a backup."""
async def async_list_backups(self, **kwargs: Any) -> list[SyncedBackup]:
"""List synced backups."""
async def async_list_backups(self, **kwargs: Any) -> list[UploadedBackup]:
"""List backups."""
return [
SyncedBackup(
UploadedBackup(
id="abc123",
name="Test",
slug="abc123",

View File

@@ -67,7 +67,7 @@
'type': 'result',
})
# ---
# name: test_agents_synced[with_hassio]
# name: test_agents_list_backups[with_hassio]
dict({
'id': 1,
'result': list([
@@ -84,7 +84,7 @@
'type': 'result',
})
# ---
# name: test_agents_synced[without_hassio]
# name: test_agents_list_backups[without_hassio]
dict({
'id': 1,
'result': list([
@@ -142,7 +142,7 @@
'type': 'result',
})
# ---
# name: test_backup_end_excepion[exception0]
# name: test_backup_end_exception[exception0]
dict({
'error': dict({
'code': 'post_backup_actions_failed',
@@ -153,7 +153,7 @@
'type': 'result',
})
# ---
# name: test_backup_end_excepion[exception1]
# name: test_backup_end_exception[exception1]
dict({
'error': dict({
'code': 'post_backup_actions_failed',
@@ -164,7 +164,7 @@
'type': 'result',
})
# ---
# name: test_backup_end_excepion[exception2]
# name: test_backup_end_exception[exception2]
dict({
'error': dict({
'code': 'post_backup_actions_failed',
@@ -216,7 +216,7 @@
'type': 'result',
})
# ---
# name: test_backup_start_excepion[exception0]
# name: test_backup_start_exception[exception0]
dict({
'error': dict({
'code': 'pre_backup_actions_failed',
@@ -227,7 +227,7 @@
'type': 'result',
})
# ---
# name: test_backup_start_excepion[exception1]
# name: test_backup_start_exception[exception1]
dict({
'error': dict({
'code': 'pre_backup_actions_failed',
@@ -238,7 +238,7 @@
'type': 'result',
})
# ---
# name: test_backup_start_excepion[exception2]
# name: test_backup_start_exception[exception2]
dict({
'error': dict({
'code': 'pre_backup_actions_failed',
@@ -249,7 +249,7 @@
'type': 'result',
})
# ---
# name: test_backup_sync[with_hassio-hass_access_token]
# name: test_backup_upload[with_hassio-hass_access_token]
dict({
'error': dict({
'code': 'only_supervisor',
@@ -260,7 +260,7 @@
'type': 'result',
})
# ---
# name: test_backup_sync[with_hassio-hass_supervisor_access_token]
# name: test_backup_upload[with_hassio-hass_supervisor_access_token]
dict({
'id': 1,
'result': None,
@@ -268,7 +268,7 @@
'type': 'result',
})
# ---
# name: test_backup_sync[without_hassio-hass_access_token]
# name: test_backup_upload[without_hassio-hass_access_token]
dict({
'error': dict({
'code': 'unknown_command',
@@ -279,7 +279,7 @@
'type': 'result',
})
# ---
# name: test_backup_sync[without_hassio-hass_supervisor_access_token]
# name: test_backup_upload[without_hassio-hass_supervisor_access_token]
dict({
'error': dict({
'code': 'unknown_command',
@@ -290,10 +290,10 @@
'type': 'result',
})
# ---
# name: test_backup_sync_excepion[exception0]
# name: test_backup_upload_exception[exception0]
dict({
'error': dict({
'code': 'backup_sync_failed',
'code': 'backup_upload_failed',
'message': '',
}),
'id': 1,
@@ -301,10 +301,10 @@
'type': 'result',
})
# ---
# name: test_backup_sync_excepion[exception1]
# name: test_backup_upload_exception[exception1]
dict({
'error': dict({
'code': 'backup_sync_failed',
'code': 'backup_upload_failed',
'message': 'Boom',
}),
'id': 1,
@@ -312,10 +312,10 @@
'type': 'result',
})
# ---
# name: test_backup_sync_excepion[exception2]
# name: test_backup_upload_exception[exception2]
dict({
'error': dict({
'code': 'backup_sync_failed',
'code': 'backup_upload_failed',
'message': 'Boom',
}),
'id': 1,

View File

@@ -10,17 +10,17 @@ import aiohttp
from multidict import CIMultiDict, CIMultiDictProxy
import pytest
from homeassistant.components.backup import BackupManager, BackupSyncMetadata
from homeassistant.components.backup import BackupManager, BackupUploadMetadata
from homeassistant.components.backup.agent import BackupAgentPlatformProtocol
from homeassistant.components.backup.manager import (
BackupPlatformProtocol,
BackupProgress,
)
from homeassistant.components.backup.sync_agent import BackupPlatformAgentProtocol
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component
from .common import TEST_BACKUP, BackupSyncAgentTest
from .common import TEST_BACKUP, BackupAgentTest
from tests.common import MockPlatform, mock_platform
@@ -55,7 +55,7 @@ async def _mock_backup_generation(
async def _setup_mock_domain(
hass: HomeAssistant,
platform: BackupPlatformProtocol | BackupPlatformAgentProtocol | None = None,
platform: BackupPlatformProtocol | BackupAgentPlatformProtocol | None = None,
) -> None:
"""Set up a mock domain."""
mock_platform(hass, "some_domain.backup", platform or MockPlatform())
@@ -196,7 +196,7 @@ async def test_loading_platforms(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(),
async_get_backup_agents=AsyncMock(),
),
)
await manager.load_platforms()
@@ -208,11 +208,11 @@ async def test_loading_platforms(
assert "Loaded 1 platforms" in caplog.text
async def test_loading_sync_agents(
async def test_loading_agents(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test loading backup sync agents."""
"""Test loading backup agents."""
manager = BackupManager(hass)
assert not manager.loaded_platforms
@@ -221,19 +221,17 @@ async def test_loading_sync_agents(
await _setup_mock_domain(
hass,
Mock(
async_get_backup_sync_agents=AsyncMock(
return_value=[BackupSyncAgentTest("test")]
),
async_get_backup_agents=AsyncMock(return_value=[BackupAgentTest("test")]),
),
)
await manager.load_platforms()
await hass.async_block_till_done()
assert manager.loaded_platforms
assert len(manager.sync_agents) == 1
assert len(manager.backup_agents) == 1
assert "Loaded 1 agents" in caplog.text
assert "some_domain.test" in manager.sync_agents
assert "some_domain.test" in manager.backup_agents
async def test_not_loading_bad_platforms(
@@ -271,10 +269,10 @@ async def test_syncing_backup(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(
async_get_backup_agents=AsyncMock(
return_value=[
BackupSyncAgentTest("agent1"),
BackupSyncAgentTest("agent2"),
BackupAgentTest("agent1"),
BackupAgentTest("agent2"),
]
),
),
@@ -289,17 +287,17 @@ async def test_syncing_backup(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=backup,
),
patch.object(BackupSyncAgentTest, "async_upload_backup") as mocked_upload,
patch.object(BackupAgentTest, "async_upload_backup") as mocked_upload,
patch(
"homeassistant.components.backup.manager.HAVERSION",
"2025.1.0",
),
):
await manager.async_sync_backup(slug=backup.slug)
await manager.async_upload_backup(slug=backup.slug)
assert mocked_upload.call_count == 2
first_call = mocked_upload.call_args_list[0]
assert first_call[1]["path"] == backup.path
assert first_call[1]["metadata"] == BackupSyncMetadata(
assert first_call[1]["metadata"] == BackupUploadMetadata(
date=backup.date,
homeassistant="2025.1.0",
name=backup.name,
@@ -307,7 +305,7 @@ async def test_syncing_backup(
slug=backup.slug,
)
assert "Error during backup sync" not in caplog.text
assert "Error during backup upload" not in caplog.text
@pytest.mark.usefixtures("mock_backup_generation")
@@ -320,7 +318,7 @@ async def test_syncing_backup_with_exception(
"""Test syncing a backup with exception."""
manager = BackupManager(hass)
class ModifiedBackupSyncAgentTest(BackupSyncAgentTest):
class ModifiedBackupSyncAgentTest(BackupAgentTest):
async def async_upload_backup(self, **kwargs: Any) -> None:
raise HomeAssistantError("Test exception")
@@ -329,7 +327,7 @@ async def test_syncing_backup_with_exception(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(
async_get_backup_agents=AsyncMock(
return_value=[
ModifiedBackupSyncAgentTest("agent1"),
ModifiedBackupSyncAgentTest("agent2"),
@@ -357,11 +355,11 @@ async def test_syncing_backup_with_exception(
),
):
mocked_upload.side_effect = HomeAssistantError("Test exception")
await manager.async_sync_backup(slug=backup.slug)
await manager.async_upload_backup(slug=backup.slug)
assert mocked_upload.call_count == 2
first_call = mocked_upload.call_args_list[0]
assert first_call[1]["path"] == backup.path
assert first_call[1]["metadata"] == BackupSyncMetadata(
assert first_call[1]["metadata"] == BackupUploadMetadata(
date=backup.date,
homeassistant="2025.1.0",
name=backup.name,
@@ -369,7 +367,7 @@ async def test_syncing_backup_with_exception(
slug=backup.slug,
)
assert "Error during backup sync - Test exception" in caplog.text
assert "Error during backup upload - Test exception" in caplog.text
@pytest.mark.usefixtures("mock_backup_generation")
@@ -387,7 +385,7 @@ async def test_syncing_backup_no_agents(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(return_value=[]),
async_get_backup_agents=AsyncMock(return_value=[]),
),
)
await manager.load_platforms()
@@ -395,9 +393,9 @@ async def test_syncing_backup_no_agents(
backup = await _mock_backup_generation(manager, mocked_json_bytes, mocked_tarfile)
with patch(
"homeassistant.components.backup.sync_agent.BackupSyncAgent.async_upload_backup"
"homeassistant.components.backup.agent.BackupAgent.async_upload_backup"
) as mocked_async_upload_backup:
await manager.async_sync_backup(slug=backup.slug)
await manager.async_upload_backup(slug=backup.slug)
assert mocked_async_upload_backup.call_count == 0
@@ -416,7 +414,7 @@ async def test_exception_plaform_pre(
Mock(
async_pre_backup=_mock_step,
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(),
async_get_backup_agents=AsyncMock(),
),
)
@@ -439,7 +437,7 @@ async def test_exception_plaform_post(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=_mock_step,
async_get_backup_sync_agents=AsyncMock(),
async_get_backup_agents=AsyncMock(),
),
)
@@ -462,7 +460,7 @@ async def test_loading_platforms_when_running_async_pre_backup_actions(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(),
async_get_backup_agents=AsyncMock(),
),
)
await manager.async_pre_backup_actions()
@@ -488,7 +486,7 @@ async def test_loading_platforms_when_running_async_post_backup_actions(
Mock(
async_pre_backup=AsyncMock(),
async_post_backup=AsyncMock(),
async_get_backup_sync_agents=AsyncMock(),
async_get_backup_agents=AsyncMock(),
),
)
await manager.async_post_backup_actions()

View File

@@ -12,7 +12,7 @@ from homeassistant.components.backup.models import BaseBackup
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .common import TEST_BACKUP, BackupSyncAgentTest, setup_backup_integration
from .common import TEST_BACKUP, BackupAgentTest, setup_backup_integration
from tests.typing import WebSocketGenerator
@@ -256,7 +256,7 @@ async def test_backup_start(
pytest.param(False, id="without_hassio"),
],
)
async def test_backup_sync(
async def test_backup_upload(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
@@ -265,18 +265,18 @@ async def test_backup_sync(
access_token_fixture_name: str,
with_hassio: bool,
) -> None:
"""Test handling of pre backup actions from a WS command."""
"""Test backup upload from a WS command."""
await setup_backup_integration(hass, with_hassio=with_hassio)
client = await hass_ws_client(hass, sync_access_token_proxy)
await hass.async_block_till_done()
with patch(
"homeassistant.components.backup.manager.BackupManager.async_sync_backup",
"homeassistant.components.backup.manager.BackupManager.async_upload_backup",
):
await client.send_json_auto_id(
{
"type": "backup/sync",
"type": "backup/upload",
"data": {
"slug": "abc123",
},
@@ -293,7 +293,7 @@ async def test_backup_sync(
Exception("Boom"),
],
)
async def test_backup_end_excepion(
async def test_backup_end_exception(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
@@ -322,26 +322,26 @@ async def test_backup_end_excepion(
Exception("Boom"),
],
)
async def test_backup_sync_excepion(
async def test_backup_upload_exception(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
hass_supervisor_access_token: str,
exception: Exception,
) -> None:
"""Test exception handling while running sync backup action from a WS command."""
"""Test exception handling while running backup upload from a WS command."""
await setup_backup_integration(hass, with_hassio=True)
client = await hass_ws_client(hass, hass_supervisor_access_token)
await hass.async_block_till_done()
with patch(
"homeassistant.components.backup.manager.BackupManager.async_sync_backup",
"homeassistant.components.backup.manager.BackupManager.async_upload_backup",
side_effect=exception,
):
await client.send_json_auto_id(
{
"type": "backup/sync",
"type": "backup/upload",
"data": {
"slug": "abc123",
},
@@ -358,7 +358,7 @@ async def test_backup_sync_excepion(
Exception("Boom"),
],
)
async def test_backup_start_excepion(
async def test_backup_start_exception(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
@@ -394,7 +394,7 @@ async def test_agents_info(
) -> None:
"""Test getting backup agents info."""
await setup_backup_integration(hass, with_hassio=with_hassio)
hass.data[DATA_MANAGER].sync_agents = {"domain.test": BackupSyncAgentTest("test")}
hass.data[DATA_MANAGER].backup_agents = {"domain.test": BackupAgentTest("test")}
client = await hass_ws_client(hass)
await hass.async_block_till_done()
@@ -410,20 +410,20 @@ async def test_agents_info(
pytest.param(False, id="without_hassio"),
],
)
async def test_agents_synced(
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
with_hassio: bool,
) -> None:
"""Test getting backup agents synced details."""
"""Test backup agents list backups details."""
await setup_backup_integration(hass, with_hassio=with_hassio)
hass.data[DATA_MANAGER].sync_agents = {"domain.test": BackupSyncAgentTest("test")}
hass.data[DATA_MANAGER].backup_agents = {"domain.test": BackupAgentTest("test")}
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json_auto_id({"type": "backup/agents/synced"})
await client.send_json_auto_id({"type": "backup/agents/list_backups"})
assert await client.receive_json() == snapshot
@@ -440,9 +440,9 @@ async def test_agents_download(
snapshot: SnapshotAssertion,
with_hassio: bool,
) -> None:
"""Test WS command to start downloading a synced backup."""
"""Test WS command to start downloading a backup."""
await setup_backup_integration(hass, with_hassio=with_hassio)
hass.data[DATA_MANAGER].sync_agents = {"domain.test": BackupSyncAgentTest("test")}
hass.data[DATA_MANAGER].backup_agents = {"domain.test": BackupAgentTest("test")}
client = await hass_ws_client(hass)
await hass.async_block_till_done()
@@ -452,10 +452,10 @@ async def test_agents_download(
"type": "backup/agents/download",
"slug": "abc123",
"agent": "domain.test",
"sync_id": "abc123",
"backup_id": "abc123",
}
)
with patch.object(BackupSyncAgentTest, "async_download_backup") as download_mock:
with patch.object(BackupAgentTest, "async_download_backup") as download_mock:
assert await client.receive_json() == snapshot
assert download_mock.call_args[1] == {
"id": "abc123",
@@ -468,9 +468,9 @@ async def test_agents_download_exception(
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test WS command to start downloading a synced backup throwing an exception."""
"""Test WS command to start downloading a backup throwing an exception."""
await setup_backup_integration(hass)
hass.data[DATA_MANAGER].sync_agents = {"domain.test": BackupSyncAgentTest("test")}
hass.data[DATA_MANAGER].backup_agents = {"domain.test": BackupAgentTest("test")}
client = await hass_ws_client(hass)
await hass.async_block_till_done()
@@ -480,10 +480,10 @@ async def test_agents_download_exception(
"type": "backup/agents/download",
"slug": "abc123",
"agent": "domain.test",
"sync_id": "abc123",
"backup_id": "abc123",
}
)
with patch.object(BackupSyncAgentTest, "async_download_backup") as download_mock:
with patch.object(BackupAgentTest, "async_download_backup") as download_mock:
download_mock.side_effect = Exception("Boom")
assert await client.receive_json() == snapshot
@@ -493,7 +493,7 @@ async def test_agents_download_unknown_agent(
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test downloading a synced backup with an unknown agent."""
"""Test downloading a backup with an unknown agent."""
await setup_backup_integration(hass)
client = await hass_ws_client(hass)
@@ -504,7 +504,7 @@ async def test_agents_download_unknown_agent(
"type": "backup/agents/download",
"slug": "abc123",
"agent": "domain.test",
"sync_id": "abc123",
"backup_id": "abc123",
}
)
assert await client.receive_json() == snapshot