mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Convert backup tests in aws_s3 to end-to-end (#188321)
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
"""Test the AWS S3 backup platform."""
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from datetime import timedelta
|
||||
from io import StringIO
|
||||
import json
|
||||
from time import time
|
||||
from unittest.mock import ANY, AsyncMock, Mock, call, patch
|
||||
|
||||
from botocore.exceptions import ConnectTimeoutError
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
from pytest_homeassistant.typing import (
|
||||
@@ -16,9 +17,9 @@ from pytest_homeassistant.typing import (
|
||||
)
|
||||
|
||||
from homeassistant.components.aws_s3.backup import (
|
||||
CACHE_TTL,
|
||||
MULTIPART_MIN_PART_SIZE_BYTES,
|
||||
BotoCoreError,
|
||||
S3BackupAgent,
|
||||
async_register_backup_agents_listener,
|
||||
suggested_filenames,
|
||||
)
|
||||
@@ -27,18 +28,18 @@ from homeassistant.components.aws_s3.const import (
|
||||
DATA_BACKUP_AGENT_LISTENERS,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.components.backup import (
|
||||
DOMAIN as BACKUP_DOMAIN,
|
||||
AgentBackup,
|
||||
UploadBackupEvent,
|
||||
async_get_manager,
|
||||
)
|
||||
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import setup_integration
|
||||
from .const import USER_INPUT
|
||||
|
||||
from tests.components.backup.common import collect_upload_events, upload_backup_via_http
|
||||
|
||||
MIB = 2**20
|
||||
CHUNK_SIZES_MIB = (12, 12, 10, 12, 5)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_backup_integration(
|
||||
@@ -57,6 +58,28 @@ async def setup_backup_integration(
|
||||
yield
|
||||
|
||||
|
||||
def _get_object_response(content: bytes) -> dict[str, AsyncMock]:
|
||||
"""Return a get_object response with the given body."""
|
||||
return {"Body": AsyncMock(read=AsyncMock(return_value=content))}
|
||||
|
||||
|
||||
def _agent_backup(backup_id: str, name: str, date: str) -> AgentBackup:
|
||||
"""Return a minimal backup with the given identity."""
|
||||
return AgentBackup(
|
||||
backup_id=backup_id,
|
||||
date=date,
|
||||
addons=[],
|
||||
database_included=False,
|
||||
extra_metadata={},
|
||||
folders=[],
|
||||
homeassistant_included=False,
|
||||
homeassistant_version=None,
|
||||
name=name,
|
||||
protected=False,
|
||||
size=0,
|
||||
)
|
||||
|
||||
|
||||
async def test_suggested_filenames() -> None:
|
||||
"""Test the suggested_filenames function."""
|
||||
backup = AgentBackup(
|
||||
@@ -85,22 +108,34 @@ async def test_agents_info(
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test backup agent info."""
|
||||
"""Test backup agent info following config entry unload and setup."""
|
||||
client = await hass_ws_client(hass)
|
||||
local_agent = {"agent_id": "backup.local", "name": "local"}
|
||||
s3_agent = {
|
||||
"agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}",
|
||||
"name": mock_config_entry.title,
|
||||
}
|
||||
|
||||
await client.send_json_auto_id({"type": "backup/agents/info"})
|
||||
response = await client.receive_json()
|
||||
|
||||
assert response["success"]
|
||||
assert response["result"] == {
|
||||
"agents": [
|
||||
{"agent_id": "backup.local", "name": "local"},
|
||||
{
|
||||
"agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}",
|
||||
"name": mock_config_entry.title,
|
||||
},
|
||||
],
|
||||
}
|
||||
assert response["result"] == {"agents": [local_agent, s3_agent]}
|
||||
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
await client.send_json_auto_id({"type": "backup/agents/info"})
|
||||
response = await client.receive_json()
|
||||
assert response["success"]
|
||||
assert response["result"] == {"agents": [local_agent]}
|
||||
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
await client.send_json_auto_id({"type": "backup/agents/info"})
|
||||
response = await client.receive_json()
|
||||
assert response["success"]
|
||||
assert response["result"] == {"agents": [local_agent, s3_agent]}
|
||||
|
||||
|
||||
async def test_agents_list_backups(
|
||||
@@ -201,54 +236,41 @@ async def test_agents_get_backup_does_not_throw_on_not_found(
|
||||
|
||||
async def test_agents_list_backups_with_corrupted_metadata(
|
||||
hass: HomeAssistant,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
mock_client: MagicMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
mock_agent_backup: AgentBackup,
|
||||
) -> None:
|
||||
"""Test listing backups when one metadata file is corrupted."""
|
||||
# Create agent
|
||||
agent = S3BackupAgent(hass, mock_config_entry)
|
||||
|
||||
# Set up mock responses for both valid and corrupted metadata files
|
||||
paginate = mock_client.get_paginator.return_value.paginate
|
||||
paginate.return_value.__aiter__.return_value = [
|
||||
{
|
||||
"Contents": [
|
||||
{
|
||||
"Key": "valid_backup.metadata.json",
|
||||
"LastModified": "2023-01-01T00:00:00+00:00",
|
||||
},
|
||||
{
|
||||
"Key": "corrupted_backup.metadata.json",
|
||||
"LastModified": "2023-01-01T00:00:00+00:00",
|
||||
},
|
||||
{"Key": "valid_backup.metadata.json"},
|
||||
{"Key": "corrupted_backup.metadata.json"},
|
||||
]
|
||||
}
|
||||
]
|
||||
contents = {
|
||||
"valid_backup.metadata.json": json.dumps(mock_agent_backup.as_dict()).encode(),
|
||||
"corrupted_backup.metadata.json": b"{invalid json content",
|
||||
}
|
||||
mock_client.get_object.side_effect = lambda **kwargs: _get_object_response(
|
||||
contents[kwargs["Key"]]
|
||||
)
|
||||
|
||||
# Mock responses for get_object calls
|
||||
valid_metadata = json.dumps(mock_agent_backup.as_dict())
|
||||
corrupted_metadata = "{invalid json content"
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json_auto_id({"type": "backup/info"})
|
||||
response = await client.receive_json()
|
||||
|
||||
async def mock_get_object(**kwargs):
|
||||
"""Mock get_object with different responses based on the key."""
|
||||
key = kwargs.get("Key", "")
|
||||
if "valid_backup" in key:
|
||||
mock_body = AsyncMock()
|
||||
mock_body.read.return_value = valid_metadata.encode()
|
||||
return {"Body": mock_body}
|
||||
# Corrupted metadata
|
||||
mock_body = AsyncMock()
|
||||
mock_body.read.return_value = corrupted_metadata.encode()
|
||||
return {"Body": mock_body}
|
||||
|
||||
mock_client.get_object.side_effect = mock_get_object
|
||||
|
||||
backups = await agent.async_list_backups()
|
||||
assert len(backups) == 1
|
||||
assert backups[0].backup_id == mock_agent_backup.backup_id
|
||||
assert "Failed to process metadata file" in caplog.text
|
||||
assert response["success"]
|
||||
assert response["result"]["agent_errors"] == {}
|
||||
assert [b["backup_id"] for b in response["result"]["backups"]] == [
|
||||
mock_agent_backup.backup_id
|
||||
]
|
||||
assert (
|
||||
"Failed to process metadata file corrupted_backup.metadata.json" in caplog.text
|
||||
)
|
||||
|
||||
|
||||
async def test_agents_delete(
|
||||
@@ -339,63 +361,36 @@ async def test_agents_upload_network_failure(
|
||||
assert "Upload failed for aws_s3" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("freezer")
|
||||
@pytest.mark.parametrize(
|
||||
"backup_size", [MULTIPART_MIN_PART_SIZE_BYTES * 2], ids=["large"]
|
||||
)
|
||||
async def test_agents_upload_on_progress(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_client: MagicMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_agent_backup: AgentBackup,
|
||||
) -> None:
|
||||
"""Test agent upload backup emits UploadBackupEvent via on_progress."""
|
||||
client = await hass_client()
|
||||
agent_id = f"{DOMAIN}.{mock_config_entry.entry_id}"
|
||||
|
||||
manager = async_get_manager(hass)
|
||||
events: list[UploadBackupEvent] = []
|
||||
|
||||
def _collect(event: UploadBackupEvent) -> None:
|
||||
if isinstance(event, UploadBackupEvent):
|
||||
events.append(event)
|
||||
|
||||
unsub = manager.async_subscribe_events(_collect)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
|
||||
return_value=mock_agent_backup,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.read_backup",
|
||||
return_value=mock_agent_backup,
|
||||
),
|
||||
patch("pathlib.Path.open") as mocked_open,
|
||||
):
|
||||
mocked_open.return_value.read = Mock(
|
||||
side_effect=[
|
||||
b"a" * mock_agent_backup.size,
|
||||
b"",
|
||||
]
|
||||
with collect_upload_events(hass, agent_id) as events:
|
||||
resp = await upload_backup_via_http(
|
||||
await hass_client(),
|
||||
agent_id,
|
||||
mock_agent_backup,
|
||||
[b"a" * mock_agent_backup.size],
|
||||
)
|
||||
resp = await client.post(
|
||||
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
|
||||
data={"file": StringIO("test")},
|
||||
)
|
||||
|
||||
unsub()
|
||||
|
||||
assert resp.status == 201
|
||||
agent_id = f"{DOMAIN}.{mock_config_entry.entry_id}"
|
||||
agent_events = [e for e in events if e.agent_id == agent_id]
|
||||
assert len(agent_events) >= 2
|
||||
assert all(e.total_bytes == mock_agent_backup.size for e in agent_events)
|
||||
# Verify events report distinct increasing byte counts
|
||||
uploaded_bytes = [e.uploaded_bytes for e in agent_events]
|
||||
assert uploaded_bytes == sorted(uploaded_bytes)
|
||||
assert len(set(uploaded_bytes)) == len(uploaded_bytes)
|
||||
# Verify at least one intermediate event (uploaded_bytes < total_bytes)
|
||||
assert agent_events[0].uploaded_bytes < agent_events[0].total_bytes
|
||||
assert all(e.total_bytes == mock_agent_backup.size for e in events)
|
||||
# The manager emits the first (0) and last (backup size) events; the agent's
|
||||
# report of the second part is debounced
|
||||
assert [e.uploaded_bytes for e in events] == [
|
||||
0,
|
||||
MULTIPART_MIN_PART_SIZE_BYTES,
|
||||
mock_agent_backup.size,
|
||||
]
|
||||
|
||||
|
||||
async def test_agents_download(
|
||||
@@ -450,58 +445,31 @@ async def test_error_during_delete(
|
||||
|
||||
async def test_cache_expiration(
|
||||
hass: HomeAssistant,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
mock_client: MagicMock,
|
||||
mock_agent_backup: AgentBackup,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test that the cache expires correctly."""
|
||||
# Mock the entry
|
||||
mock_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={"bucket": "test-bucket"},
|
||||
unique_id="test-unique-id",
|
||||
title="Test S3",
|
||||
)
|
||||
mock_entry.runtime_data = MagicMock(client=mock_client)
|
||||
|
||||
# Create agent
|
||||
agent = S3BackupAgent(hass, mock_entry)
|
||||
|
||||
# Reset call counts from coordinator's initial refresh
|
||||
"""Test the backup list is cached until CACHE_TTL expires."""
|
||||
client = await hass_ws_client(hass)
|
||||
# The coordinator's first refresh also lists the bucket
|
||||
mock_client.reset_mock()
|
||||
|
||||
# Mock metadata response
|
||||
metadata_content = json.dumps(mock_agent_backup.as_dict())
|
||||
mock_body = AsyncMock()
|
||||
mock_body.read.return_value = metadata_content.encode()
|
||||
paginate = mock_client.get_paginator.return_value.paginate
|
||||
paginate.return_value.__aiter__.return_value = [
|
||||
{
|
||||
"Contents": [
|
||||
{
|
||||
"Key": "test.metadata.json",
|
||||
"LastModified": "2023-01-01T00:00:00+00:00",
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
mock_client.get_object.return_value = {"Body": mock_body}
|
||||
|
||||
# First call should query S3
|
||||
await agent.async_list_backups()
|
||||
await client.send_json_auto_id({"type": "backup/info"})
|
||||
response = await client.receive_json()
|
||||
assert len(response["result"]["backups"]) == 1
|
||||
assert mock_client.get_paginator.call_count == 1
|
||||
assert mock_client.get_object.call_count == 1
|
||||
|
||||
# Second call should use cache
|
||||
await agent.async_list_backups()
|
||||
await client.send_json_auto_id({"type": "backup/info"})
|
||||
response = await client.receive_json()
|
||||
assert len(response["result"]["backups"]) == 1
|
||||
assert mock_client.get_paginator.call_count == 1
|
||||
assert mock_client.get_object.call_count == 1
|
||||
|
||||
# Set cache to expire
|
||||
agent._cache_expiration = time() - 1
|
||||
|
||||
# Third call should query S3 again
|
||||
await agent.async_list_backups()
|
||||
freezer.tick(timedelta(seconds=CACHE_TTL + 1))
|
||||
await client.send_json_auto_id({"type": "backup/info"})
|
||||
response = await client.receive_json()
|
||||
assert len(response["result"]["backups"]) == 1
|
||||
assert mock_client.get_paginator.call_count == 2
|
||||
assert mock_client.get_object.call_count == 2
|
||||
|
||||
@@ -521,88 +489,35 @@ async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None:
|
||||
|
||||
async def test_list_backups_with_pagination(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
mock_client: MagicMock,
|
||||
) -> None:
|
||||
"""Test listing backups when paginating through multiple pages."""
|
||||
# Create agent
|
||||
agent = S3BackupAgent(hass, mock_config_entry)
|
||||
|
||||
# Create two different backups
|
||||
backup1 = AgentBackup(
|
||||
backup_id="backup1",
|
||||
date="2023-01-01T00:00:00+00:00",
|
||||
addons=[],
|
||||
database_included=False,
|
||||
extra_metadata={},
|
||||
folders=[],
|
||||
homeassistant_included=False,
|
||||
homeassistant_version=None,
|
||||
name="Backup 1",
|
||||
protected=False,
|
||||
size=0,
|
||||
)
|
||||
backup2 = AgentBackup(
|
||||
backup_id="backup2",
|
||||
date="2023-01-02T00:00:00+00:00",
|
||||
addons=[],
|
||||
database_included=False,
|
||||
extra_metadata={},
|
||||
folders=[],
|
||||
homeassistant_included=False,
|
||||
homeassistant_version=None,
|
||||
name="Backup 2",
|
||||
protected=False,
|
||||
size=0,
|
||||
)
|
||||
|
||||
# Setup two pages of results
|
||||
page1 = {
|
||||
"Contents": [
|
||||
{
|
||||
"Key": "backup1.metadata.json",
|
||||
"LastModified": "2023-01-01T00:00:00+00:00",
|
||||
},
|
||||
{"Key": "backup1.tar", "LastModified": "2023-01-01T00:00:00+00:00"},
|
||||
]
|
||||
}
|
||||
page2 = {
|
||||
"Contents": [
|
||||
{
|
||||
"Key": "backup2.metadata.json",
|
||||
"LastModified": "2023-01-02T00:00:00+00:00",
|
||||
},
|
||||
{"Key": "backup2.tar", "LastModified": "2023-01-02T00:00:00+00:00"},
|
||||
]
|
||||
}
|
||||
|
||||
# Setup mock client
|
||||
mock_client = mock_config_entry.runtime_data.client
|
||||
backup1 = _agent_backup("backup1", "Backup 1", "2023-01-01T00:00:00+00:00")
|
||||
backup2 = _agent_backup("backup2", "Backup 2", "2023-01-02T00:00:00+00:00")
|
||||
paginate = mock_client.get_paginator.return_value.paginate
|
||||
paginate.return_value.__aiter__.return_value = [
|
||||
page1,
|
||||
page2,
|
||||
{"Contents": [{"Key": "backup1.metadata.json"}, {"Key": "backup1.tar"}]},
|
||||
{"Contents": [{"Key": "backup2.metadata.json"}, {"Key": "backup2.tar"}]},
|
||||
]
|
||||
contents = {
|
||||
"backup1.metadata.json": json.dumps(backup1.as_dict()).encode(),
|
||||
"backup2.metadata.json": json.dumps(backup2.as_dict()).encode(),
|
||||
}
|
||||
mock_client.get_object.side_effect = lambda **kwargs: _get_object_response(
|
||||
contents[kwargs["Key"]]
|
||||
)
|
||||
|
||||
# Mock get_object responses based on the key
|
||||
async def mock_get_object(**kwargs):
|
||||
"""Mock get_object with different responses based on the key."""
|
||||
key = kwargs.get("Key", "")
|
||||
if "backup1" in key:
|
||||
mock_body = AsyncMock()
|
||||
mock_body.read.return_value = json.dumps(backup1.as_dict()).encode()
|
||||
return {"Body": mock_body}
|
||||
# backup2
|
||||
mock_body = AsyncMock()
|
||||
mock_body.read.return_value = json.dumps(backup2.as_dict()).encode()
|
||||
return {"Body": mock_body}
|
||||
client = await hass_ws_client(hass)
|
||||
await client.send_json_auto_id({"type": "backup/info"})
|
||||
response = await client.receive_json()
|
||||
|
||||
mock_client.get_object.side_effect = mock_get_object
|
||||
|
||||
# List backups and verify we got both
|
||||
backups = await agent.async_list_backups()
|
||||
assert len(backups) == 2
|
||||
backup_ids = {backup.backup_id for backup in backups}
|
||||
assert backup_ids == {"backup1", "backup2"}
|
||||
assert response["success"]
|
||||
assert response["result"]["agent_errors"] == {}
|
||||
assert {b["backup_id"] for b in response["result"]["backups"]} == {
|
||||
"backup1",
|
||||
"backup2",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -675,40 +590,6 @@ async def test_agent_delete_backup_parametrized(
|
||||
mock_client.delete_object.assert_any_call(Bucket="test", Key=expected_metadata_key)
|
||||
|
||||
|
||||
async def _upload_backup(
|
||||
hass_client: ClientSessionGenerator,
|
||||
agent_id: str,
|
||||
mock_agent_backup: AgentBackup,
|
||||
) -> None:
|
||||
"""Perform a backup upload with the necessary mocks set up."""
|
||||
client = await hass_client()
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
|
||||
return_value=mock_agent_backup,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.read_backup",
|
||||
return_value=mock_agent_backup,
|
||||
),
|
||||
patch("pathlib.Path.open") as mocked_open,
|
||||
):
|
||||
# we must emit at least two chunks
|
||||
# the "appendix" chunk triggers the upload of the final buffer part
|
||||
mocked_open.return_value.read = Mock(
|
||||
side_effect=[
|
||||
b"a" * mock_agent_backup.size,
|
||||
b"appendix",
|
||||
b"",
|
||||
]
|
||||
)
|
||||
resp = await client.post(
|
||||
f"/api/backup/upload?agent_id={agent_id}",
|
||||
data={"file": StringIO("test")},
|
||||
)
|
||||
assert resp.status == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config_entry_extra_data", "expected_key_prefix"),
|
||||
[
|
||||
@@ -726,10 +607,15 @@ async def test_agent_upload_small_backup_parametrized(
|
||||
expected_key_prefix: str,
|
||||
) -> None:
|
||||
"""Test agent upload small backup with and without prefix."""
|
||||
await _upload_backup(
|
||||
hass_client, f"{DOMAIN}.{mock_config_entry.entry_id}", mock_agent_backup
|
||||
resp = await upload_backup_via_http(
|
||||
await hass_client(),
|
||||
f"{DOMAIN}.{mock_config_entry.entry_id}",
|
||||
mock_agent_backup,
|
||||
# The "appendix" chunk triggers the upload of the final buffer part
|
||||
[b"a" * mock_agent_backup.size, b"appendix"],
|
||||
)
|
||||
|
||||
assert resp.status == 201
|
||||
assert f"Uploading backup {mock_agent_backup.backup_id}" in caplog.text
|
||||
assert mock_client.create_multipart_upload.await_count == 0
|
||||
assert mock_client.upload_part.await_count == 0
|
||||
@@ -766,10 +652,15 @@ async def test_agent_upload_large_backup_parametrized(
|
||||
expected_key_prefix: str,
|
||||
) -> None:
|
||||
"""Test agent upload large (multipart) backup with and without prefix."""
|
||||
await _upload_backup(
|
||||
hass_client, f"{DOMAIN}.{mock_config_entry.entry_id}", mock_agent_backup
|
||||
resp = await upload_backup_via_http(
|
||||
await hass_client(),
|
||||
f"{DOMAIN}.{mock_config_entry.entry_id}",
|
||||
mock_agent_backup,
|
||||
# The "appendix" chunk triggers the upload of the final buffer part
|
||||
[b"a" * mock_agent_backup.size, b"appendix"],
|
||||
)
|
||||
|
||||
assert resp.status == 201
|
||||
tar_filename, metadata_filename = suggested_filenames(mock_agent_backup)
|
||||
|
||||
tar_key = f"{expected_key_prefix}{tar_filename}"
|
||||
@@ -808,6 +699,32 @@ async def test_agent_upload_large_backup_parametrized(
|
||||
mock_client.put_object.assert_called_with(Bucket="test", Key=metadata_key, Body=ANY)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backup_size", [sum(CHUNK_SIZES_MIB) * MIB], ids=["51MiB"])
|
||||
async def test_multipart_upload_consistent_part_sizes(
|
||||
hass_client: ClientSessionGenerator,
|
||||
mock_client: MagicMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_agent_backup: AgentBackup,
|
||||
) -> None:
|
||||
"""Test multipart parts have a constant size regardless of stream chunking."""
|
||||
resp = await upload_backup_via_http(
|
||||
await hass_client(),
|
||||
f"{DOMAIN}.{mock_config_entry.entry_id}",
|
||||
mock_agent_backup,
|
||||
[b"x" * (size * MIB) for size in CHUNK_SIZES_MIB],
|
||||
)
|
||||
|
||||
assert resp.status == 201
|
||||
assert [len(c.kwargs["Body"]) for c in mock_client.upload_part.await_args_list] == [
|
||||
MULTIPART_MIN_PART_SIZE_BYTES,
|
||||
MULTIPART_MIN_PART_SIZE_BYTES,
|
||||
sum(CHUNK_SIZES_MIB) * MIB - 2 * MULTIPART_MIN_PART_SIZE_BYTES,
|
||||
]
|
||||
assert [
|
||||
c.kwargs["PartNumber"] for c in mock_client.upload_part.await_args_list
|
||||
] == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config_entry_extra_data", "expected_key_prefix"),
|
||||
[
|
||||
|
||||
@@ -6,12 +6,17 @@ from collections.abc import (
|
||||
Buffer,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Generator,
|
||||
Iterable,
|
||||
)
|
||||
from contextlib import contextmanager
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
from aiohttp import ClientResponse
|
||||
from aiohttp.test_utils import TestClient
|
||||
from pytest_homeassistant.common import mock_platform
|
||||
|
||||
from homeassistant.components.backup import (
|
||||
@@ -22,10 +27,13 @@ from homeassistant.components.backup import (
|
||||
BackupAgentPlatformProtocol,
|
||||
BackupNotFound,
|
||||
Folder,
|
||||
UploadBackupEvent,
|
||||
async_get_manager,
|
||||
)
|
||||
from homeassistant.components.backup.backup import CoreLocalBackupAgent
|
||||
from homeassistant.components.backup.const import BUF_SIZE, DATA_MANAGER
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.components.backup.manager import ManagerStateEvent
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
LOCAL_AGENT_ID = f"{DOMAIN}.local"
|
||||
@@ -192,7 +200,8 @@ async def setup_backup_integration(
|
||||
await setup_backup_platform(hass, domain=TEST_DOMAIN, platform=platform)
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
# The config entry is set up from a background discovery flow.
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
if LOCAL_AGENT_ID not in backups or with_hassio:
|
||||
return remote_agents_dict
|
||||
@@ -224,3 +233,51 @@ async def setup_backup_platform(
|
||||
mock_platform(hass, f"{domain}.backup", platform)
|
||||
assert await async_setup_component(hass, domain, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def upload_backup_via_http(
|
||||
client: TestClient,
|
||||
agent_id: str,
|
||||
backup: AgentBackup,
|
||||
chunks: Iterable[bytes] = (b"test",),
|
||||
) -> ClientResponse:
|
||||
"""Upload a backup to an agent through the backup upload view.
|
||||
|
||||
The manager reads the uploaded backup as `backup` and streams it to the
|
||||
agent as `chunks`, one stream chunk per item.
|
||||
"""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
|
||||
return_value=backup,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.backup.manager.read_backup",
|
||||
return_value=backup,
|
||||
),
|
||||
patch("pathlib.Path.open") as mocked_open,
|
||||
):
|
||||
mocked_open.return_value.read = Mock(side_effect=[*chunks, b""])
|
||||
return await client.post(
|
||||
f"/api/backup/upload?agent_id={agent_id}",
|
||||
data={"file": StringIO("test")},
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def collect_upload_events(
|
||||
hass: HomeAssistant, agent_id: str
|
||||
) -> Generator[list[UploadBackupEvent]]:
|
||||
"""Collect the upload events of an agent while the context is active."""
|
||||
events: list[UploadBackupEvent] = []
|
||||
|
||||
@callback
|
||||
def _collect(event: ManagerStateEvent) -> None:
|
||||
if isinstance(event, UploadBackupEvent) and event.agent_id == agent_id:
|
||||
events.append(event)
|
||||
|
||||
unsub = async_get_manager(hass).async_subscribe_events(_collect)
|
||||
try:
|
||||
yield events
|
||||
finally:
|
||||
unsub()
|
||||
|
||||
Reference in New Issue
Block a user