Remove backup helper (#143558)

* Remove backup helper

* Update aws_s3 tests
This commit is contained in:
Erik Montnemery 2025-06-30 14:11:10 +02:00 committed by GitHub
parent ee8830cc77
commit 741a3d5009
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 88 additions and 296 deletions

View File

@ -75,7 +75,6 @@ from .core_config import async_process_ha_core_config
from .exceptions import HomeAssistantError from .exceptions import HomeAssistantError
from .helpers import ( from .helpers import (
area_registry, area_registry,
backup,
category_registry, category_registry,
config_validation as cv, config_validation as cv,
device_registry, device_registry,
@ -880,10 +879,6 @@ async def _async_set_up_integrations(
if "recorder" in all_domains: if "recorder" in all_domains:
recorder.async_initialize_recorder(hass) recorder.async_initialize_recorder(hass)
# Initialize backup
if "backup" in all_domains:
backup.async_initialize_backup(hass)
stages: list[tuple[str, set[str], int | None]] = [ stages: list[tuple[str, set[str], int | None]] = [
*( *(
(name, domain_group, timeout) (name, domain_group, timeout)

View File

@ -2,9 +2,9 @@
from homeassistant.config_entries import SOURCE_SYSTEM from homeassistant.config_entries import SOURCE_SYSTEM
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, discovery_flow from homeassistant.helpers import config_validation as cv, discovery_flow
from homeassistant.helpers.backup import DATA_BACKUP
from homeassistant.helpers.hassio import is_hassio from homeassistant.helpers.hassio import is_hassio
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
@ -37,7 +37,6 @@ from .manager import (
IdleEvent, IdleEvent,
IncorrectPasswordError, IncorrectPasswordError,
ManagerBackup, ManagerBackup,
ManagerStateEvent,
NewBackup, NewBackup,
RestoreBackupEvent, RestoreBackupEvent,
RestoreBackupStage, RestoreBackupStage,
@ -72,12 +71,12 @@ __all__ = [
"IncorrectPasswordError", "IncorrectPasswordError",
"LocalBackupAgent", "LocalBackupAgent",
"ManagerBackup", "ManagerBackup",
"ManagerStateEvent",
"NewBackup", "NewBackup",
"RestoreBackupEvent", "RestoreBackupEvent",
"RestoreBackupStage", "RestoreBackupStage",
"RestoreBackupState", "RestoreBackupState",
"WrittenBackup", "WrittenBackup",
"async_get_manager",
"suggested_filename", "suggested_filename",
"suggested_filename_from_name_date", "suggested_filename_from_name_date",
] ]
@ -104,13 +103,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
backup_manager = BackupManager(hass, reader_writer) backup_manager = BackupManager(hass, reader_writer)
hass.data[DATA_MANAGER] = backup_manager hass.data[DATA_MANAGER] = backup_manager
try:
await backup_manager.async_setup() await backup_manager.async_setup()
except Exception as err:
hass.data[DATA_BACKUP].manager_ready.set_exception(err)
raise
else:
hass.data[DATA_BACKUP].manager_ready.set_result(None)
async_register_websocket_handlers(hass, with_hassio) async_register_websocket_handlers(hass, with_hassio)
@ -143,3 +136,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: BackupConfigEntry) -> bo
async def async_unload_entry(hass: HomeAssistant, entry: BackupConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: BackupConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
@callback
def async_get_manager(hass: HomeAssistant) -> BackupManager:
"""Get the backup manager instance.
Raises HomeAssistantError if the backup integration is not available.
"""
if DATA_MANAGER not in hass.data:
raise HomeAssistantError("Backup integration is not available")
return hass.data[DATA_MANAGER]

View File

@ -1,38 +0,0 @@
"""Websocket commands for the Backup integration."""
from typing import Any
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.backup import async_subscribe_events
from .const import DATA_MANAGER
from .manager import ManagerStateEvent
@callback
def async_register_websocket_handlers(hass: HomeAssistant) -> None:
"""Register websocket commands."""
websocket_api.async_register_command(hass, handle_subscribe_events)
@websocket_api.require_admin
@websocket_api.websocket_command({vol.Required("type"): "backup/subscribe_events"})
@websocket_api.async_response
async def handle_subscribe_events(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Subscribe to backup events."""
def on_event(event: ManagerStateEvent) -> None:
connection.send_message(websocket_api.event_message(msg["id"], event))
if DATA_MANAGER in hass.data:
manager = hass.data[DATA_MANAGER]
on_event(manager.last_event)
connection.subscriptions[msg["id"]] = async_subscribe_events(hass, on_event)
connection.send_result(msg["id"])

View File

@ -8,10 +8,6 @@ from datetime import datetime
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.backup import (
async_subscribe_events,
async_subscribe_platform_events,
)
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN, LOGGER from .const import DOMAIN, LOGGER
@ -56,8 +52,8 @@ class BackupDataUpdateCoordinator(DataUpdateCoordinator[BackupCoordinatorData]):
update_interval=None, update_interval=None,
) )
self.unsubscribe: list[Callable[[], None]] = [ self.unsubscribe: list[Callable[[], None]] = [
async_subscribe_events(hass, self._on_event), backup_manager.async_subscribe_events(self._on_event),
async_subscribe_platform_events(hass, self._on_event), backup_manager.async_subscribe_platform_events(self._on_event),
] ]
self.backup_manager = backup_manager self.backup_manager = backup_manager

View File

@ -36,7 +36,6 @@ from homeassistant.helpers import (
issue_registry as ir, issue_registry as ir,
start, start,
) )
from homeassistant.helpers.backup import DATA_BACKUP
from homeassistant.helpers.json import json_bytes from homeassistant.helpers.json import json_bytes
from homeassistant.util import dt as dt_util, json as json_util from homeassistant.util import dt as dt_util, json as json_util
@ -372,12 +371,10 @@ class BackupManager:
# Latest backup event and backup event subscribers # Latest backup event and backup event subscribers
self.last_event: ManagerStateEvent = BlockedEvent() self.last_event: ManagerStateEvent = BlockedEvent()
self.last_action_event: ManagerStateEvent | None = None self.last_action_event: ManagerStateEvent | None = None
self._backup_event_subscriptions = hass.data[ self._backup_event_subscriptions: list[Callable[[ManagerStateEvent], None]] = []
DATA_BACKUP self._backup_platform_event_subscriptions: list[
].backup_event_subscriptions Callable[[BackupPlatformEvent], None]
self._backup_platform_event_subscriptions = hass.data[ ] = []
DATA_BACKUP
].backup_platform_event_subscriptions
async def async_setup(self) -> None: async def async_setup(self) -> None:
"""Set up the backup manager.""" """Set up the backup manager."""
@ -1385,6 +1382,32 @@ class BackupManager:
for subscription in self._backup_event_subscriptions: for subscription in self._backup_event_subscriptions:
subscription(event) subscription(event)
@callback
def async_subscribe_events(
self,
on_event: Callable[[ManagerStateEvent], None],
) -> Callable[[], None]:
"""Subscribe events."""
def remove_subscription() -> None:
self._backup_event_subscriptions.remove(on_event)
self._backup_event_subscriptions.append(on_event)
return remove_subscription
@callback
def async_subscribe_platform_events(
self,
on_event: Callable[[BackupPlatformEvent], None],
) -> Callable[[], None]:
"""Subscribe to backup platform events."""
def remove_subscription() -> None:
self._backup_platform_event_subscriptions.remove(on_event)
self._backup_platform_event_subscriptions.append(on_event)
return remove_subscription
def _create_automatic_backup_failed_issue( def _create_automatic_backup_failed_issue(
self, translation_key: str, translation_placeholders: dict[str, str] | None self, translation_key: str, translation_placeholders: dict[str, str] | None
) -> None: ) -> None:

View File

@ -19,9 +19,14 @@ from homeassistant.components.onboarding import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.backup import async_get_manager as async_get_backup_manager
from . import BackupManager, Folder, IncorrectPasswordError, http as backup_http from . import (
BackupManager,
Folder,
IncorrectPasswordError,
async_get_manager,
http as backup_http,
)
if TYPE_CHECKING: if TYPE_CHECKING:
from homeassistant.components.onboarding import OnboardingStoreData from homeassistant.components.onboarding import OnboardingStoreData
@ -54,7 +59,7 @@ def with_backup_manager[_ViewT: BaseOnboardingView, **_P](
if self._data["done"]: if self._data["done"]:
raise HTTPUnauthorized raise HTTPUnauthorized
manager = await async_get_backup_manager(request.app[KEY_HASS]) manager = async_get_manager(request.app[KEY_HASS])
return await func(self, manager, request, *args, **kwargs) return await func(self, manager, request, *args, **kwargs)
return with_backup return with_backup

View File

@ -10,7 +10,11 @@ from homeassistant.helpers import config_validation as cv
from .config import Day, ScheduleRecurrence from .config import Day, ScheduleRecurrence
from .const import DATA_MANAGER, LOGGER from .const import DATA_MANAGER, LOGGER
from .manager import DecryptOnDowloadNotSupported, IncorrectPasswordError from .manager import (
DecryptOnDowloadNotSupported,
IncorrectPasswordError,
ManagerStateEvent,
)
from .models import BackupNotFound, Folder from .models import BackupNotFound, Folder
@ -30,6 +34,7 @@ def async_register_websocket_handlers(hass: HomeAssistant, with_hassio: bool) ->
websocket_api.async_register_command(hass, handle_create_with_automatic_settings) websocket_api.async_register_command(hass, handle_create_with_automatic_settings)
websocket_api.async_register_command(hass, handle_delete) websocket_api.async_register_command(hass, handle_delete)
websocket_api.async_register_command(hass, handle_restore) websocket_api.async_register_command(hass, handle_restore)
websocket_api.async_register_command(hass, handle_subscribe_events)
websocket_api.async_register_command(hass, handle_config_info) websocket_api.async_register_command(hass, handle_config_info)
websocket_api.async_register_command(hass, handle_config_update) websocket_api.async_register_command(hass, handle_config_update)
@ -417,3 +422,22 @@ def handle_config_update(
changes.pop("type") changes.pop("type")
manager.config.update(**changes) manager.config.update(**changes)
connection.send_result(msg["id"]) connection.send_result(msg["id"])
@websocket_api.require_admin
@websocket_api.websocket_command({vol.Required("type"): "backup/subscribe_events"})
@websocket_api.async_response
async def handle_subscribe_events(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Subscribe to backup events."""
def on_event(event: ManagerStateEvent) -> None:
connection.send_message(websocket_api.event_message(msg["id"], event))
manager = hass.data[DATA_MANAGER]
on_event(manager.last_event)
connection.subscriptions[msg["id"]] = manager.async_subscribe_events(on_event)
connection.send_result(msg["id"])

View File

@ -48,13 +48,13 @@ from homeassistant.components.backup import (
RestoreBackupStage, RestoreBackupStage,
RestoreBackupState, RestoreBackupState,
WrittenBackup, WrittenBackup,
async_get_manager as async_get_backup_manager,
suggested_filename as suggested_backup_filename, suggested_filename as suggested_backup_filename,
suggested_filename_from_name_date, suggested_filename_from_name_date,
) )
from homeassistant.const import __version__ as HAVERSION from homeassistant.const import __version__ as HAVERSION
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.backup import async_get_manager as async_get_backup_manager
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from homeassistant.util.enum import try_parse_enum from homeassistant.util.enum import try_parse_enum
@ -839,7 +839,7 @@ async def backup_addon_before_update(
async def backup_core_before_update(hass: HomeAssistant) -> None: async def backup_core_before_update(hass: HomeAssistant) -> None:
"""Prepare for updating core.""" """Prepare for updating core."""
backup_manager = await async_get_backup_manager(hass) backup_manager = async_get_backup_manager(hass)
client = get_supervisor_client(hass) client = get_supervisor_client(hass)
try: try:

View File

@ -1,93 +0,0 @@
"""Helpers for the backup integration."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from homeassistant.components.backup import (
BackupManager,
BackupPlatformEvent,
ManagerStateEvent,
)
DATA_BACKUP: HassKey[BackupData] = HassKey("backup_data")
DATA_MANAGER: HassKey[BackupManager] = HassKey("backup")
@dataclass(slots=True)
class BackupData:
"""Backup data stored in hass.data."""
backup_event_subscriptions: list[Callable[[ManagerStateEvent], None]] = field(
default_factory=list
)
backup_platform_event_subscriptions: list[Callable[[BackupPlatformEvent], None]] = (
field(default_factory=list)
)
manager_ready: asyncio.Future[None] = field(default_factory=asyncio.Future)
@callback
def async_initialize_backup(hass: HomeAssistant) -> None:
"""Initialize backup data.
This creates the BackupData instance stored in hass.data[DATA_BACKUP] and
registers the basic backup websocket API which is used by frontend to subscribe
to backup events.
"""
from homeassistant.components.backup import basic_websocket # noqa: PLC0415
hass.data[DATA_BACKUP] = BackupData()
basic_websocket.async_register_websocket_handlers(hass)
async def async_get_manager(hass: HomeAssistant) -> BackupManager:
"""Get the backup manager instance.
Raises HomeAssistantError if the backup integration is not available.
"""
if DATA_BACKUP not in hass.data:
raise HomeAssistantError("Backup integration is not available")
await hass.data[DATA_BACKUP].manager_ready
return hass.data[DATA_MANAGER]
@callback
def async_subscribe_events(
hass: HomeAssistant,
on_event: Callable[[ManagerStateEvent], None],
) -> Callable[[], None]:
"""Subscribe to backup events."""
backup_event_subscriptions = hass.data[DATA_BACKUP].backup_event_subscriptions
def remove_subscription() -> None:
backup_event_subscriptions.remove(on_event)
backup_event_subscriptions.append(on_event)
return remove_subscription
@callback
def async_subscribe_platform_events(
hass: HomeAssistant,
on_event: Callable[[BackupPlatformEvent], None],
) -> Callable[[], None]:
"""Subscribe to backup platform events."""
backup_platform_event_subscriptions = hass.data[
DATA_BACKUP
].backup_platform_event_subscriptions
def remove_subscription() -> None:
backup_platform_event_subscriptions.remove(on_event)
backup_platform_event_subscriptions.append(on_event)
return remove_subscription

View File

@ -23,7 +23,6 @@ from homeassistant.components.aws_s3.const import (
) )
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import setup_integration from . import setup_integration
@ -43,7 +42,6 @@ async def setup_backup_integration(
patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
): ):
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {}) assert await async_setup_component(hass, BACKUP_DOMAIN, {})
await setup_integration(hass, mock_config_entry) await setup_integration(hass, mock_config_entry)

View File

@ -19,7 +19,6 @@ from homeassistant.components.azure_storage.const import (
) )
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import setup_integration from . import setup_integration
@ -39,7 +38,6 @@ async def setup_backup_integration(
patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
): ):
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {}) assert await async_setup_component(hass, BACKUP_DOMAIN, {})
await setup_integration(hass, mock_config_entry) await setup_integration(hass, mock_config_entry)

View File

@ -19,7 +19,6 @@ from homeassistant.components.backup import (
from homeassistant.components.backup.backup import CoreLocalBackupAgent from homeassistant.components.backup.backup import CoreLocalBackupAgent
from homeassistant.components.backup.const import DATA_MANAGER from homeassistant.components.backup.const import DATA_MANAGER
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_platform from tests.common import mock_platform
@ -132,7 +131,6 @@ async def setup_backup_integration(
) -> dict[str, Mock]: ) -> dict[str, Mock]:
"""Set up the Backup integration.""" """Set up the Backup integration."""
backups = backups or {} backups = backups or {}
async_initialize_backup(hass)
with ( with (
patch("homeassistant.components.backup.is_hassio", return_value=with_hassio), patch("homeassistant.components.backup.is_hassio", return_value=with_hassio),
patch( patch(

View File

@ -6299,20 +6299,3 @@
'type': 'event', 'type': 'event',
}) })
# --- # ---
# name: test_subscribe_event_early
dict({
'event': dict({
'manager_state': 'idle',
}),
'id': 1,
'type': 'event',
})
# ---
# name: test_subscribe_event_early.1
dict({
'id': 1,
'result': None,
'success': True,
'type': 'result',
})
# ---

View File

@ -14,7 +14,6 @@ from syrupy.assertion import SnapshotAssertion
from homeassistant.components.backup import DOMAIN, AgentBackup from homeassistant.components.backup import DOMAIN, AgentBackup
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .common import ( from .common import (
@ -64,7 +63,6 @@ async def test_load_backups(
side_effect: Exception | None, side_effect: Exception | None,
) -> None: ) -> None:
"""Test load backups.""" """Test load backups."""
async_initialize_backup(hass)
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done() await hass.async_block_till_done()
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -84,7 +82,6 @@ async def test_upload(
hass_client: ClientSessionGenerator, hass_client: ClientSessionGenerator,
) -> None: ) -> None:
"""Test upload backup.""" """Test upload backup."""
async_initialize_backup(hass)
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done() await hass.async_block_till_done()
client = await hass_client() client = await hass_client()
@ -140,7 +137,6 @@ async def test_delete_backup(
unlink_path: Path | None, unlink_path: Path | None,
) -> None: ) -> None:
"""Test delete backup.""" """Test delete backup."""
async_initialize_backup(hass)
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done() await hass.async_block_till_done()
client = await hass_ws_client(hass) client = await hass_ws_client(hass)

View File

@ -10,7 +10,6 @@ from syrupy.assertion import SnapshotAssertion
from homeassistant.components import backup, onboarding from homeassistant.components import backup, onboarding
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import register_auth_provider from tests.common import register_auth_provider
@ -57,7 +56,6 @@ async def test_onboarding_view_after_done(
mock_onboarding_storage(hass_storage, {"done": [onboarding.const.STEP_USER]}) mock_onboarding_storage(hass_storage, {"done": [onboarding.const.STEP_USER]})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -111,7 +109,6 @@ async def test_onboarding_backup_info(
mock_onboarding_storage(hass_storage, {"done": []}) mock_onboarding_storage(hass_storage, {"done": []})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -232,7 +229,6 @@ async def test_onboarding_backup_restore(
mock_onboarding_storage(hass_storage, {"done": []}) mock_onboarding_storage(hass_storage, {"done": []})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -329,7 +325,6 @@ async def test_onboarding_backup_restore_error(
mock_onboarding_storage(hass_storage, {"done": []}) mock_onboarding_storage(hass_storage, {"done": []})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -373,7 +368,6 @@ async def test_onboarding_backup_restore_unexpected_error(
mock_onboarding_storage(hass_storage, {"done": []}) mock_onboarding_storage(hass_storage, {"done": []})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -399,7 +393,6 @@ async def test_onboarding_backup_upload(
mock_onboarding_storage(hass_storage, {"done": []}) mock_onboarding_storage(hass_storage, {"done": []})
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -30,8 +30,6 @@ from homeassistant.components.backup.manager import (
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import issue_registry as ir from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component
from .common import ( from .common import (
LOCAL_AGENT_ID, LOCAL_AGENT_ID,
@ -4057,29 +4055,6 @@ async def test_subscribe_event(
assert await client.receive_json() == snapshot assert await client.receive_json() == snapshot
async def test_subscribe_event_early(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test subscribe event before backup integration has started."""
async_initialize_backup(hass)
await setup_backup_integration(hass, with_hassio=False)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/subscribe_events"})
assert await client.receive_json() == snapshot
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
manager = hass.data[DATA_MANAGER]
manager.async_on_backup_event(
CreateBackupEvent(stage=None, state=CreateBackupState.IN_PROGRESS, reason=None)
)
assert await client.receive_json() == snapshot
@pytest.mark.parametrize( @pytest.mark.parametrize(
("agent_id", "backup_id", "password"), ("agent_id", "backup_id", "password"),
[ [

View File

@ -21,7 +21,6 @@ from homeassistant.components.cloud import DOMAIN
from homeassistant.components.cloud.backup import async_register_backup_agents_listener from homeassistant.components.cloud.backup import async_register_backup_agents_listener
from homeassistant.components.cloud.const import EVENT_CLOUD_EVENT from homeassistant.components.cloud.const import EVENT_CLOUD_EVENT
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.aiohttp import MockStreamReaderChunked from homeassistant.util.aiohttp import MockStreamReaderChunked
@ -37,8 +36,7 @@ async def setup_integration(
cloud: MagicMock, cloud: MagicMock,
cloud_logged_in: None, cloud_logged_in: None,
) -> AsyncGenerator[None]: ) -> AsyncGenerator[None]:
"""Set up cloud and backup integrations.""" """Set up cloud integration."""
async_initialize_backup(hass)
with ( with (
patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),

View File

@ -17,7 +17,6 @@ from homeassistant.components.backup import (
) )
from homeassistant.components.google_drive import DOMAIN from homeassistant.components.google_drive import DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .conftest import CONFIG_ENTRY_TITLE, TEST_AGENT_ID from .conftest import CONFIG_ENTRY_TITLE, TEST_AGENT_ID
@ -66,8 +65,7 @@ async def setup_integration(
config_entry: MockConfigEntry, config_entry: MockConfigEntry,
mock_api: MagicMock, mock_api: MagicMock,
) -> None: ) -> None:
"""Set up Google Drive and backup integrations.""" """Set up Google Drive integration."""
async_initialize_backup(hass)
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
mock_api.list_files = AsyncMock( mock_api.list_files = AsyncMock(

View File

@ -49,7 +49,6 @@ from homeassistant.components.hassio import DOMAIN
from homeassistant.components.hassio.backup import RESTORE_JOB_ID_ENV from homeassistant.components.hassio.backup import RESTORE_JOB_ID_ENV
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .test_init import MOCK_ENVIRON from .test_init import MOCK_ENVIRON
@ -326,7 +325,6 @@ async def setup_backup_integration(
hass: HomeAssistant, hassio_enabled: None, supervisor_client: AsyncMock hass: HomeAssistant, hassio_enabled: None, supervisor_client: AsyncMock
) -> None: ) -> None:
"""Set up Backup integration.""" """Set up Backup integration."""
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -466,7 +464,6 @@ async def test_agent_info(
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
supervisor_client.mounts.info.return_value = mounts supervisor_client.mounts.info.return_value = mounts
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
await client.send_json_auto_id({"type": "backup/agents/info"}) await client.send_json_auto_id({"type": "backup/agents/info"})
@ -1474,7 +1471,6 @@ async def test_reader_writer_create_per_agent_encryption(
) )
supervisor_client.jobs.get_job.return_value = TEST_JOB_NOT_DONE supervisor_client.jobs.get_job.return_value = TEST_JOB_NOT_DONE
supervisor_client.mounts.info.return_value = mounts supervisor_client.mounts.info.return_value = mounts
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
for command in commands: for command in commands:
@ -2610,7 +2606,6 @@ async def test_restore_progress_after_restart(
supervisor_client.jobs.get_job.return_value = get_job_result supervisor_client.jobs.get_job.return_value = get_job_result
async_initialize_backup(hass)
with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}): with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}):
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
@ -2634,7 +2629,6 @@ async def test_restore_progress_after_restart_report_progress(
supervisor_client.jobs.get_job.return_value = TEST_JOB_NOT_DONE supervisor_client.jobs.get_job.return_value = TEST_JOB_NOT_DONE
async_initialize_backup(hass)
with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}): with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}):
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
@ -2717,7 +2711,6 @@ async def test_restore_progress_after_restart_unknown_job(
supervisor_client.jobs.get_job.side_effect = SupervisorError supervisor_client.jobs.get_job.side_effect = SupervisorError
async_initialize_backup(hass)
with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}): with patch.dict(os.environ, MOCK_ENVIRON | {RESTORE_JOB_ID_ENV: TEST_JOB_ID}):
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
@ -2817,7 +2810,6 @@ async def test_config_load_config_info(
hass_storage.update(storage_data) hass_storage.update(storage_data)
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -26,7 +26,6 @@ from homeassistant.components.hassio.const import REQUEST_REFRESH_DELAY
from homeassistant.const import __version__ as HAVERSION from homeassistant.const import __version__ as HAVERSION
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -246,7 +245,6 @@ async def test_update_addon(hass: HomeAssistant, update_addon: AsyncMock) -> Non
async def setup_backup_integration(hass: HomeAssistant) -> None: async def setup_backup_integration(hass: HomeAssistant) -> None:
"""Set up the backup integration.""" """Set up the backup integration."""
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -27,7 +27,6 @@ from homeassistant.components.hassio.const import (
) )
from homeassistant.const import __version__ as HAVERSION from homeassistant.const import __version__ as HAVERSION
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -360,7 +359,6 @@ async def test_update_addon(
async def setup_backup_integration(hass: HomeAssistant) -> None: async def setup_backup_integration(hass: HomeAssistant) -> None:
"""Set up the backup integration.""" """Set up the backup integration."""
async_initialize_backup(hass)
assert await async_setup_component(hass, "backup", {}) assert await async_setup_component(hass, "backup", {})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -15,7 +15,6 @@ from homeassistant.components.backup import (
from homeassistant.components.kitchen_sink import DOMAIN from homeassistant.components.kitchen_sink import DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import instance_id from homeassistant.helpers import instance_id
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.typing import ClientSessionGenerator, WebSocketGenerator from tests.typing import ClientSessionGenerator, WebSocketGenerator
@ -36,8 +35,7 @@ async def backup_only() -> AsyncGenerator[None]:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
async def setup_integration(hass: HomeAssistant) -> AsyncGenerator[None]: async def setup_integration(hass: HomeAssistant) -> AsyncGenerator[None]:
"""Set up Kitchen Sink and backup integrations.""" """Set up Kitchen Sink integration."""
async_initialize_backup(hass)
with patch("homeassistant.components.backup.is_hassio", return_value=False): with patch("homeassistant.components.backup.is_hassio", return_value=False):
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}}) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})

View File

@ -21,7 +21,6 @@ from homeassistant.components.onedrive.backup import (
from homeassistant.components.onedrive.const import DATA_BACKUP_AGENT_LISTENERS, DOMAIN from homeassistant.components.onedrive.const import DATA_BACKUP_AGENT_LISTENERS, DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH from homeassistant.config_entries import SOURCE_REAUTH
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import setup_integration from . import setup_integration
@ -36,8 +35,7 @@ async def setup_backup_integration(
hass: HomeAssistant, hass: HomeAssistant,
mock_config_entry: MockConfigEntry, mock_config_entry: MockConfigEntry,
) -> AsyncGenerator[None]: ) -> AsyncGenerator[None]:
"""Set up onedrive and backup integrations.""" """Set up onedrive integration."""
async_initialize_backup(hass)
with ( with (
patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),

View File

@ -32,7 +32,6 @@ from homeassistant.const import (
CONF_USERNAME, CONF_USERNAME,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.aiohttp import MockStreamReader, MockStreamReaderChunked from homeassistant.util.aiohttp import MockStreamReader, MockStreamReaderChunked
@ -161,8 +160,7 @@ async def setup_dsm_with_filestation(
hass: HomeAssistant, hass: HomeAssistant,
mock_dsm_with_filestation: MagicMock, mock_dsm_with_filestation: MagicMock,
): ):
"""Mock setup of synology dsm config entry and backup integration.""" """Mock setup of synology dsm config entry."""
async_initialize_backup(hass)
with ( with (
patch( patch(
"homeassistant.components.synology_dsm.common.SynologyDSM", "homeassistant.components.synology_dsm.common.SynologyDSM",
@ -220,7 +218,6 @@ async def test_agents_not_loaded(
) -> None: ) -> None:
"""Test backup agent with no loaded config entry.""" """Test backup agent with no loaded config entry."""
with patch("homeassistant.components.backup.is_hassio", return_value=False): with patch("homeassistant.components.backup.is_hassio", return_value=False):
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}}) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -13,7 +13,6 @@ from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup
from homeassistant.components.webdav.backup import async_register_backup_agents_listener from homeassistant.components.webdav.backup import async_register_backup_agents_listener
from homeassistant.components.webdav.const import DATA_BACKUP_AGENT_LISTENERS, DOMAIN from homeassistant.components.webdav.const import DATA_BACKUP_AGENT_LISTENERS, DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.backup import async_initialize_backup
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .const import BACKUP_METADATA from .const import BACKUP_METADATA
@ -31,7 +30,6 @@ async def setup_backup_integration(
patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
): ):
async_initialize_backup(hass)
assert await async_setup_component(hass, BACKUP_DOMAIN, {}) assert await async_setup_component(hass, BACKUP_DOMAIN, {})
mock_config_entry.add_to_hass(hass) mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.config_entries.async_setup(mock_config_entry.entry_id)

View File

@ -1,41 +0,0 @@
"""The tests for the backup helpers."""
import asyncio
from unittest.mock import patch
import pytest
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import backup as backup_helper
from homeassistant.setup import async_setup_component
async def test_async_get_manager(hass: HomeAssistant) -> None:
"""Test async_get_manager."""
backup_helper.async_initialize_backup(hass)
task = asyncio.create_task(backup_helper.async_get_manager(hass))
assert await async_setup_component(hass, BACKUP_DOMAIN, {})
await hass.async_block_till_done()
manager = await task
assert manager is hass.data[backup_helper.DATA_MANAGER]
async def test_async_get_manager_no_backup(hass: HomeAssistant) -> None:
"""Test async_get_manager when the backup integration is not enabled."""
with pytest.raises(HomeAssistantError, match="Backup integration is not available"):
await backup_helper.async_get_manager(hass)
async def test_async_get_manager_backup_failed_setup(hass: HomeAssistant) -> None:
"""Test test_async_get_manager when the backup integration can't be set up."""
backup_helper.async_initialize_backup(hass)
with patch(
"homeassistant.components.backup.manager.BackupManager.async_setup",
side_effect=Exception("Boom!"),
):
assert not await async_setup_component(hass, BACKUP_DOMAIN, {})
with pytest.raises(Exception, match="Boom!"):
await backup_helper.async_get_manager(hass)