Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add remove and download backup location #35

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions aiohasupervisor/backups.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
BackupList,
BackupsInfo,
BackupsOptions,
DownloadBackupOptions,
FreezeOptions,
FullBackupOptions,
FullRestoreOptions,
NewBackup,
PartialBackupOptions,
PartialRestoreOptions,
RemoveBackupOptions,
UploadBackupOptions,
UploadedBackup,
)
Expand Down Expand Up @@ -81,9 +83,13 @@ async def backup_info(self, backup: str) -> BackupComplete:
result = await self._client.get(f"backups/{backup}/info")
return BackupComplete.from_dict(result.data)

async def remove_backup(self, backup: str) -> None:
async def remove_backup(
self, backup: str, options: RemoveBackupOptions | None = None
) -> None:
"""Remove a backup."""
await self._client.delete(f"backups/{backup}")
await self._client.delete(
f"backups/{backup}", json=options.to_dict() if options else None
)

async def full_restore(
self, backup: str, options: FullRestoreOptions | None = None
Expand Down Expand Up @@ -129,9 +135,17 @@ async def upload_backup(

return UploadedBackup.from_dict(result.data).slug

async def download_backup(self, backup: str) -> AsyncIterator[bytes]:
async def download_backup(
self, backup: str, options: DownloadBackupOptions | None = None
) -> AsyncIterator[bytes]:
"""Download backup and return stream."""
params = MultiDict()
if options and options.location:
params.add("location", options.location or "")

result = await self._client.get(
f"backups/{backup}/download", response_type=ResponseType.STREAM
f"backups/{backup}/download",
params=params,
response_type=ResponseType.STREAM,
)
return result.data
2 changes: 2 additions & 0 deletions aiohasupervisor/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ async def delete(
uri: str,
*,
params: dict[str, str] | MultiDict[str] | None = None,
json: dict[str, Any] | None = None,
timeout: ClientTimeout | None = DEFAULT_TIMEOUT,
) -> Response:
"""Handle a DELETE request to Supervisor."""
Expand All @@ -220,6 +221,7 @@ async def delete(
uri,
params=params,
response_type=ResponseType.NONE,
json=json,
timeout=timeout,
)

Expand Down
4 changes: 4 additions & 0 deletions aiohasupervisor/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@
BackupsInfo,
BackupsOptions,
BackupType,
DownloadBackupOptions,
Folder,
FreezeOptions,
FullBackupOptions,
FullRestoreOptions,
NewBackup,
PartialBackupOptions,
PartialRestoreOptions,
RemoveBackupOptions,
UploadBackupOptions,
)
from aiohasupervisor.models.discovery import (
Expand Down Expand Up @@ -209,13 +211,15 @@
"BackupsInfo",
"BackupsOptions",
"BackupType",
"DownloadBackupOptions",
"Folder",
"FreezeOptions",
"FullBackupOptions",
"FullRestoreOptions",
"NewBackup",
"PartialBackupOptions",
"PartialRestoreOptions",
"RemoveBackupOptions",
"UploadBackupOptions",
"Discovery",
"DiscoveryConfig",
Expand Down
18 changes: 16 additions & 2 deletions aiohasupervisor/models/backups.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from datetime import datetime
from enum import StrEnum

from .base import Request, ResponseData
from .base import DEFAULT, Request, ResponseData

# --- ENUMS ----

Expand Down Expand Up @@ -135,7 +135,7 @@ class FullBackupOptions(Request):
name: str | None = None
password: str | None = None
compressed: bool | None = None
location: set[str | None] | str | None = None
location: list[str | None] | str | None = DEFAULT # type: ignore[assignment]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically, I guess this is a breaking change, but we only introduced set[] support with #33 which isn't in a stable release, so changing that is fine.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea I noted that in the description

homeassistant_exclude_database: bool | None = None
background: bool | None = None
extra: dict | None = None
Expand Down Expand Up @@ -185,3 +185,17 @@ class UploadedBackup(ResponseData):
"""UploadedBackup model."""

slug: str


@dataclass(frozen=True, slots=True)
class RemoveBackupOptions(Request):
"""RemoveBackupOptions model."""

location: set[str | None] = None


@dataclass(frozen=True, slots=True)
class DownloadBackupOptions(Request):
"""DownloadBackupOptions model."""

location: str | None = DEFAULT # type: ignore[assignment]
56 changes: 51 additions & 5 deletions tests/test_backups.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
from aiohasupervisor import SupervisorClient
from aiohasupervisor.models import (
BackupsOptions,
DownloadBackupOptions,
Folder,
FreezeOptions,
FullBackupOptions,
PartialBackupOptions,
PartialRestoreOptions,
RemoveBackupOptions,
UploadBackupOptions,
)

Expand Down Expand Up @@ -131,6 +133,32 @@ async def test_partial_restore_options() -> None:
PartialRestoreOptions(background=True)


async def test_backup_options_location() -> None:
"""Test location field in backup options."""
assert FullBackupOptions(location=["test", None]).to_dict() == {
"location": ["test", None]
}
assert FullBackupOptions(location="test").to_dict() == {"location": "test"}
assert FullBackupOptions(location=None).to_dict() == {"location": None}
assert FullBackupOptions().to_dict() == {}

assert PartialBackupOptions(
location=["test", None], folders={Folder.SSL}
).to_dict() == {
"location": ["test", None],
"folders": ["ssl"],
}
assert PartialBackupOptions(location="test", folders={Folder.SSL}).to_dict() == {
"location": "test",
"folders": ["ssl"],
}
assert PartialBackupOptions(location=None, folders={Folder.SSL}).to_dict() == {
"location": None,
"folders": ["ssl"],
}
assert PartialBackupOptions(folders={Folder.SSL}).to_dict() == {"folders": ["ssl"]}


def backup_callback(url: str, **kwargs: dict[str, Any]) -> CallbackResult: # noqa: ARG001
"""Return response based on whether backup was in background or not."""
if kwargs["json"] and kwargs["json"].get("background"):
Expand Down Expand Up @@ -323,12 +351,17 @@ async def test_backup_info_with_multiple_locations(
assert result.locations == {None, "Test"}


@pytest.mark.parametrize(
"options", [None, RemoveBackupOptions(location={"test", None})]
)
async def test_remove_backup(
responses: aioresponses, supervisor_client: SupervisorClient
responses: aioresponses,
supervisor_client: SupervisorClient,
options: RemoveBackupOptions | None,
) -> None:
"""Test remove backup API."""
responses.delete(f"{SUPERVISOR_URL}/backups/abc123", status=200)
assert await supervisor_client.backups.remove_backup("abc123") is None
assert await supervisor_client.backups.remove_backup("abc123", options) is None
assert responses.requests.keys() == {
("DELETE", URL(f"{SUPERVISOR_URL}/backups/abc123"))
}
Expand Down Expand Up @@ -398,14 +431,27 @@ async def test_upload_backup_to_locations(
assert result == "7fed74c8"


@pytest.mark.parametrize(
("options", "query"),
[
(None, ""),
(DownloadBackupOptions(location="test"), "?location=test"),
(DownloadBackupOptions(location=None), "?location="),
],
)
async def test_download_backup(
responses: aioresponses, supervisor_client: SupervisorClient
responses: aioresponses,
supervisor_client: SupervisorClient,
options: DownloadBackupOptions | None,
query: str,
) -> None:
"""Test download backup API."""
responses.get(
f"{SUPERVISOR_URL}/backups/7fed74c8/download", status=200, body=b"backup test"
f"{SUPERVISOR_URL}/backups/7fed74c8/download{query}",
status=200,
body=b"backup test",
)
result = await supervisor_client.backups.download_backup("7fed74c8")
result = await supervisor_client.backups.download_backup("7fed74c8", options)
assert isinstance(result, AsyncIterator)
async for chunk in result:
assert chunk == b"backup test"
Loading