Use the Dropbox upload progress callback for backup uploads (#186777)

This commit is contained in:
Ruslan Sayfutdinov
2026-10-17 07:33:37 +02:00
committed by GitHub
parent 9c9ac81614
commit dc60903c76
2 changed files with 19 additions and 26 deletions
+7 -10
View File
@@ -185,16 +185,13 @@ class DropboxBackupAgent(BackupAgent):
metadata_path = f"/{metadata_filename}"
file_stream = await open_stream()
async def stream_with_progress() -> AsyncIterator[bytes]:
# upload_file sends each buffered chunk before reading more of the stream.
bytes_uploaded = 0
async for chunk in file_stream:
bytes_uploaded += len(chunk)
on_progress(bytes_uploaded=bytes_uploaded)
yield chunk
await self._api.upload_file(backup_path, stream_with_progress())
await self._api.upload_file(
backup_path,
file_stream,
progress_callback=lambda bytes_uploaded: on_progress(
bytes_uploaded=bytes_uploaded
),
)
metadata_stream = _async_string_iterator(json.dumps(backup.as_dict()))
+12 -16
View File
@@ -6,6 +6,7 @@ from dataclasses import replace
from io import StringIO
import json
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, Mock, call, patch
import pytest
@@ -507,7 +508,9 @@ async def test_agents_upload_fail(
call_count = 0
async def upload_side_effect(path: str, stream: AsyncIterator[bytes]) -> None:
async def upload_side_effect(
path: str, stream: AsyncIterator[bytes], **kwargs: Any
) -> None:
nonlocal call_count
call_count += 1
async for _ in stream:
@@ -547,20 +550,8 @@ async def test_agents_upload_progress(
hass: HomeAssistant,
mock_dropbox_client: Mock,
) -> None:
"""Test that upload progress is reported as the backup stream is consumed."""
uploaded: dict[str, bytes] = {}
async def upload_side_effect(path: str, stream: AsyncIterator[bytes]) -> None:
uploaded[path] = b"".join([chunk async for chunk in stream])
async def backup_stream() -> AsyncIterator[bytes]:
yield b"abc"
yield b"defgh"
async def open_stream() -> AsyncIterator[bytes]:
return backup_stream()
mock_dropbox_client.upload_file = AsyncMock(side_effect=upload_side_effect)
"""Test that upload progress reported by the client is forwarded."""
open_stream = AsyncMock()
on_progress = Mock()
(agent,) = await async_get_backup_agents(hass)
@@ -571,7 +562,12 @@ async def test_agents_upload_progress(
)
backup_filename = suggested_filename(TEST_AGENT_BACKUP).rsplit(".", 1)[0]
assert uploaded[f"/{backup_filename}.tar"] == b"abcdefgh"
upload_call = mock_dropbox_client.upload_file.call_args_list[0]
assert upload_call.args == (f"/{backup_filename}.tar", open_stream.return_value)
# The client calls the callback after each chunk it sends
progress_callback = upload_call.kwargs["progress_callback"]
progress_callback(3)
progress_callback(8)
assert on_progress.call_args_list == [
call(bytes_uploaded=3),
call(bytes_uploaded=8),