File: test_backups.py

package info (click to toggle)
python-aiohasupervisor 0.3.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 932 kB
  • sloc: python: 4,666; sh: 37; makefile: 3
file content (671 lines) | stat: -rw-r--r-- 21,568 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
"""Test backups supervisor client."""

import asyncio
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from pathlib import PurePath
from typing import Any

from aioresponses import CallbackResult, aioresponses
import pytest
from yarl import URL

from aiohasupervisor import SupervisorClient
from aiohasupervisor.models import (
    AddonSet,
    BackupLocationAttributes,
    BackupsOptions,
    DownloadBackupOptions,
    Folder,
    FreezeOptions,
    FullBackupOptions,
    FullRestoreOptions,
    PartialBackupOptions,
    PartialRestoreOptions,
    RemoveBackupOptions,
    UploadBackupOptions,
)

from . import load_fixture
from .const import SUPERVISOR_URL


async def test_backups_list(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backups list API."""
    responses.get(
        f"{SUPERVISOR_URL}/backups", status=200, body=load_fixture("backups_list.json")
    )
    backups = await supervisor_client.backups.list()
    assert backups[0].slug == "58bc7491"
    assert backups[0].type == "full"
    assert backups[0].date == datetime(2024, 4, 6, 7, 5, 40, 0, UTC)
    assert backups[0].compressed is True
    assert backups[0].content.homeassistant is True
    assert backups[0].content.folders == ["share", "addons/local", "ssl", "media"]
    assert backups[1].slug == "69558789"
    assert backups[1].type == "partial"


async def test_backups_info(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backups info API."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/info",
        status=200,
        body=load_fixture("backups_info.json"),
    )
    info = await supervisor_client.backups.info()
    assert info.backups[0].slug == "58bc7491"
    assert info.backups[1].slug == "69558789"
    assert info.days_until_stale == 30


async def test_backups_options(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backups options API."""
    responses.post(f"{SUPERVISOR_URL}/backups/options", status=200)
    assert (
        await supervisor_client.backups.set_options(BackupsOptions(days_until_stale=10))
        is None
    )
    assert responses.requests.keys() == {
        ("POST", URL(f"{SUPERVISOR_URL}/backups/options"))
    }


async def test_backups_reload(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backups reload API."""
    responses.post(f"{SUPERVISOR_URL}/backups/reload", status=200)
    assert await supervisor_client.backups.reload() is None
    assert responses.requests.keys() == {
        ("POST", URL(f"{SUPERVISOR_URL}/backups/reload"))
    }


@pytest.mark.parametrize("options", [None, FreezeOptions(timeout=1000)])
async def test_backups_freeze(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: FreezeOptions | None,
) -> None:
    """Test backups freeze API."""
    responses.post(f"{SUPERVISOR_URL}/backups/freeze", status=200)
    assert await supervisor_client.backups.freeze(options) is None
    assert responses.requests.keys() == {
        ("POST", URL(f"{SUPERVISOR_URL}/backups/freeze"))
    }


async def test_backups_thaw(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backups thaw API."""
    responses.post(f"{SUPERVISOR_URL}/backups/thaw", status=200)
    assert await supervisor_client.backups.thaw() is None
    assert responses.requests.keys() == {
        ("POST", URL(f"{SUPERVISOR_URL}/backups/thaw"))
    }


async def test_partial_backup_options() -> None:
    """Test partial backup options."""
    assert PartialBackupOptions(name="good", addons={"a"})
    assert PartialBackupOptions(name="good", folders={Folder.SSL})
    assert PartialBackupOptions(name="good", homeassistant=True)
    with pytest.raises(
        ValueError,
        match="At least one of addons, folders, or homeassistant must have a value",
    ):
        PartialBackupOptions(name="bad")


async def test_partial_restore_options() -> None:
    """Test partial restore options."""
    assert PartialRestoreOptions(addons={"a"})
    assert PartialRestoreOptions(folders={Folder.SSL})
    assert PartialRestoreOptions(homeassistant=True)
    with pytest.raises(
        ValueError,
        match="At least one of addons, folders, or homeassistant must have a value",
    ):
        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().to_dict() == {}

    assert PartialBackupOptions(
        location=["test", ".local"], folders={Folder.SSL}
    ).to_dict() == {
        "location": ["test", ".local"],
        "folders": ["ssl"],
    }
    assert PartialBackupOptions(location="test", folders={Folder.SSL}).to_dict() == {
        "location": "test",
        "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"):
        fixture = "backup_background.json"
    else:
        fixture = "backup_foreground.json"
    return CallbackResult(status=200, body=load_fixture(fixture))


@pytest.mark.parametrize(
    ("options", "slug", "has_timeout"),
    [
        (FullBackupOptions(name="Test", background=True), None, True),
        (FullBackupOptions(name="Test", background=False), "9ecf0028", False),
        (
            FullBackupOptions(name="Test", background=False, location="test"),
            "9ecf0028",
            False,
        ),
        (
            FullBackupOptions(
                name="Test", background=False, location={".local", "test"}
            ),
            "9ecf0028",
            False,
        ),
        (
            FullBackupOptions(
                name="Test", background=False, extra={"user": "test", "scheduled": True}
            ),
            "9ecf0028",
            False,
        ),
        (
            FullBackupOptions(name="Test", background=False, extra=None),
            "9ecf0028",
            False,
        ),
        (
            FullBackupOptions(
                name="test", background=False, filename=PurePath("backup.tar")
            ),
            "9ecf0028",
            False,
        ),
        (None, "9ecf0028", False),
    ],
)
async def test_backups_full_backup(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: FullBackupOptions | None,
    slug: str | None,
    has_timeout: bool,  # noqa: FBT001
) -> None:
    """Test backups full backup API."""
    responses.post(
        f"{SUPERVISOR_URL}/backups/new/full",
        callback=backup_callback,
    )
    result = await supervisor_client.backups.full_backup(options)
    assert result.job_id.hex == "dc9dbc16f6ad4de592ffa72c807ca2bf"
    assert result.slug == slug
    assert (
        bool(
            responses.requests[("POST", URL(f"{SUPERVISOR_URL}/backups/new/full"))][
                0
            ].kwargs["timeout"]
        )
        is has_timeout
    )


@pytest.mark.parametrize(
    ("options", "slug", "has_timeout"),
    [
        (
            PartialBackupOptions(name="Test", background=True, addons={"core_ssh"}),
            None,
            True,
        ),
        (
            PartialBackupOptions(name="Test", background=False, addons={"core_ssh"}),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(
                name="Test", background=False, location="test", addons={"core_ssh"}
            ),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(
                name="Test",
                background=False,
                location={".local", "test"},
                addons={"core_ssh"},
            ),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(
                name="Test",
                background=False,
                addons={"core_ssh"},
                extra={"user": "test", "scheduled": True},
            ),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(
                name="Test", background=False, addons={"core_ssh"}, extra=None
            ),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(
                name="Test",
                background=False,
                addons={"core_ssh"},
                filename=PurePath("backup.tar"),
            ),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(name="Test", background=None, addons={"core_ssh"}),
            "9ecf0028",
            False,
        ),
        (
            PartialBackupOptions(name="Test", background=None, addons=AddonSet.ALL),
            "9ecf0028",
            False,
        ),
    ],
)
async def test_backups_partial_backup(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: PartialBackupOptions,
    slug: str | None,
    has_timeout: bool,  # noqa: FBT001
) -> None:
    """Test backups full backup API."""
    responses.post(
        f"{SUPERVISOR_URL}/backups/new/partial",
        callback=backup_callback,
    )
    result = await supervisor_client.backups.partial_backup(options)
    assert result.job_id.hex == "dc9dbc16f6ad4de592ffa72c807ca2bf"
    assert result.slug == slug
    assert (
        bool(
            responses.requests[("POST", URL(f"{SUPERVISOR_URL}/backups/new/partial"))][
                0
            ].kwargs["timeout"]
        )
        is has_timeout
    )


async def test_backup_info(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backup info API."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/69558789/info",
        status=200,
        body=load_fixture("backup_info.json"),
    )
    result = await supervisor_client.backups.backup_info("69558789")
    assert result.slug == "69558789"
    assert result.type == "partial"
    assert result.date == datetime(2024, 5, 31, 0, 0, 0, 0, UTC)
    assert result.compressed is True
    assert result.addons[0].slug == "core_mosquitto"
    assert result.addons[0].name == "Mosquitto broker"
    assert result.addons[0].version == "6.4.0"
    assert result.addons[0].size == 0
    assert result.repositories == [
        "core",
        "local",
        "https://github.com/music-assistant/home-assistant-addon",
        "https://github.com/esphome/home-assistant-addon",
        "https://github.com/hassio-addons/repository",
    ]
    assert result.folders == []
    assert result.homeassistant_exclude_database is None
    assert result.extra is None
    assert result.location_attributes[".local"].protected is False
    assert result.location_attributes[".local"].size_bytes == 10123


async def test_backup_info_no_homeassistant(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backup info API with no home assistant."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/d13dedd0/info",
        status=200,
        body=load_fixture("backup_info_no_homeassistant.json"),
    )
    result = await supervisor_client.backups.backup_info("d13dedd0")
    assert result.slug == "d13dedd0"
    assert result.type == "partial"
    assert result.homeassistant is None


async def test_backup_info_with_extra(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backup info API with extras set by client."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/d13dedd0/info",
        status=200,
        body=load_fixture("backup_info_with_extra.json"),
    )
    result = await supervisor_client.backups.backup_info("d13dedd0")
    assert result.slug == "69558789"
    assert result.type == "partial"
    assert result.extra == {"user": "test", "scheduled": True}


async def test_backup_info_with_multiple_locations(
    responses: aioresponses, supervisor_client: SupervisorClient
) -> None:
    """Test backup info API with multiple locations."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/d13dedd0/info",
        status=200,
        body=load_fixture("backup_info_with_locations.json"),
    )
    result = await supervisor_client.backups.backup_info("d13dedd0")
    assert result.slug == "69558789"
    assert result.type == "partial"
    assert result.location_attributes[".local"].protected is False
    assert result.location_attributes[".local"].size_bytes == 10123
    assert result.location_attributes["Test"].protected is False
    assert result.location_attributes["Test"].size_bytes == 10123


@pytest.mark.parametrize(
    "options", [None, RemoveBackupOptions(location={"test", None})]
)
async def test_remove_backup(
    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", options) is None
    assert responses.requests.keys() == {
        ("DELETE", URL(f"{SUPERVISOR_URL}/backups/abc123"))
    }


@pytest.mark.parametrize(
    ("options", "has_timeout"),
    [
        (None, False),
        (FullRestoreOptions(password="abc123"), False),  # noqa: S106
        (FullRestoreOptions(background=True), True),
        (FullRestoreOptions(location="test"), False),
    ],
)
async def test_full_restore(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: FullRestoreOptions | None,
    has_timeout: bool,  # noqa: FBT001
) -> None:
    """Test full restore API."""
    responses.post(
        f"{SUPERVISOR_URL}/backups/abc123/restore/full",
        status=200,
        body=load_fixture("backup_restore.json"),
    )
    result = await supervisor_client.backups.full_restore("abc123", options)
    assert result.job_id.hex == "dc9dbc16f6ad4de592ffa72c807ca2bf"
    assert (
        bool(
            responses.requests[
                ("POST", URL(f"{SUPERVISOR_URL}/backups/abc123/restore/full"))
            ][0].kwargs["timeout"]
        )
        is has_timeout
    )


@pytest.mark.parametrize(
    ("options", "has_timeout"),
    [
        (PartialRestoreOptions(addons={"core_ssh"}), False),
        (PartialRestoreOptions(homeassistant=True, location=".local"), False),
        (
            PartialRestoreOptions(folders={Folder.SHARE, Folder.SSL}, location="test"),
            False,
        ),
        (PartialRestoreOptions(addons={"core_ssh"}, background=True), True),
        (PartialRestoreOptions(addons={"core_ssh"}, password="abc123"), False),  # noqa: S106
    ],
)
async def test_partial_restore(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: PartialRestoreOptions,
    has_timeout: bool,  # noqa: FBT001
) -> None:
    """Test partial restore API."""
    responses.post(
        f"{SUPERVISOR_URL}/backups/abc123/restore/partial",
        status=200,
        body=load_fixture("backup_restore.json"),
    )
    result = await supervisor_client.backups.partial_restore("abc123", options)
    assert result.job_id.hex == "dc9dbc16f6ad4de592ffa72c807ca2bf"
    assert (
        bool(
            responses.requests[
                ("POST", URL(f"{SUPERVISOR_URL}/backups/abc123/restore/partial"))
            ][0].kwargs["timeout"]
        )
        is has_timeout
    )


@pytest.mark.parametrize(
    ("options", "query"),
    [
        (None, ""),
        (
            UploadBackupOptions(location={".local", "test"}),
            "?location=.local&location=test",
        ),
        (UploadBackupOptions(filename=PurePath("backup.tar")), "?filename=backup.tar"),
    ],
)
async def test_upload_backup(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
    options: UploadBackupOptions | None,
    query: str,
) -> None:
    """Test upload backup API."""
    responses.post(
        f"{SUPERVISOR_URL}/backups/new/upload{query}",
        status=200,
        body=load_fixture("backup_uploaded.json"),
    )
    data = asyncio.StreamReader(loop=asyncio.get_running_loop())
    data.feed_data(b"backup test")
    data.feed_eof()

    result = await supervisor_client.backups.upload_backup(data, options)
    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,
    options: DownloadBackupOptions | None,
    query: str,
) -> None:
    """Test download backup API."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/7fed74c8/download{query}",
        status=200,
        body=b"backup test",
    )
    result = await supervisor_client.backups.download_backup("7fed74c8", options)
    assert isinstance(result, AsyncIterator)
    async for chunk in result:
        assert chunk == b"backup test"


@pytest.mark.parametrize(
    ("options", "as_dict"),
    [
        (
            PartialBackupOptions(name="Test", folders={Folder.SHARE}),
            {"name": "Test", "folders": ["share"]},
        ),
        (PartialBackupOptions(addons={"core_ssh"}), {"addons": ["core_ssh"]}),
        (PartialBackupOptions(addons=AddonSet.ALL), {"addons": "ALL"}),
        (
            PartialBackupOptions(
                homeassistant=True, homeassistant_exclude_database=True
            ),
            {"homeassistant": True, "homeassistant_exclude_database": True},
        ),
        (
            PartialBackupOptions(
                folders={Folder.SSL}, compressed=True, background=True
            ),
            {"folders": ["ssl"], "compressed": True, "background": True},
        ),
        (
            PartialBackupOptions(
                homeassistant=True, location=[".cloud_backup", "test"]
            ),
            {"homeassistant": True, "location": [".cloud_backup", "test"]},
        ),
        (
            PartialBackupOptions(homeassistant=True, location="test"),
            {"homeassistant": True, "location": "test"},
        ),
        (
            PartialBackupOptions(homeassistant=True, filename=PurePath("backup.tar")),
            {"homeassistant": True, "filename": "backup.tar"},
        ),
    ],
)
async def test_partial_backup_model(
    options: PartialBackupOptions, as_dict: dict[str, Any]
) -> None:
    """Test partial backup model parsing and serializing."""
    assert PartialBackupOptions.from_dict(as_dict) == options
    assert options.to_dict() == as_dict


@pytest.mark.parametrize(
    ("options", "as_dict"),
    [
        (FullBackupOptions(name="Test"), {"name": "Test"}),
        (FullBackupOptions(password="test"), {"password": "test"}),  # noqa: S106
        (FullBackupOptions(compressed=True), {"compressed": True}),
        (
            FullBackupOptions(homeassistant_exclude_database=True),
            {"homeassistant_exclude_database": True},
        ),
        (FullBackupOptions(background=True), {"background": True}),
        (
            FullBackupOptions(location=[".cloud_backup", "test"]),
            {"location": [".cloud_backup", "test"]},
        ),
        (FullBackupOptions(location="test"), {"location": "test"}),
        (
            FullBackupOptions(filename=PurePath("backup.tar")),
            {"filename": "backup.tar"},
        ),
    ],
)
async def test_full_backup_model(
    options: FullBackupOptions, as_dict: dict[str, Any]
) -> None:
    """Test full backup model parsing and serializing."""
    assert FullBackupOptions.from_dict(as_dict) == options
    assert options.to_dict() == as_dict


async def test_backups_list_location_attributes(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
) -> None:
    """Test location attributes field in backups list."""
    responses.get(
        f"{SUPERVISOR_URL}/backups",
        status=200,
        body=load_fixture("backups_list_location_attributes.json"),
    )

    result = await supervisor_client.backups.list()
    assert result[0].location_attributes == {
        ".local": BackupLocationAttributes(
            protected=True,
            size_bytes=10240,
        ),
        "test": BackupLocationAttributes(
            protected=True,
            size_bytes=10240,
        ),
    }


async def test_backup_info_location_attributes(
    responses: aioresponses,
    supervisor_client: SupervisorClient,
) -> None:
    """Test location attributes field in backup info."""
    responses.get(
        f"{SUPERVISOR_URL}/backups/d9c48f8b/info",
        status=200,
        body=load_fixture("backup_info_location_attributes.json"),
    )

    result = await supervisor_client.backups.backup_info("d9c48f8b")
    assert result.location_attributes == {
        ".local": BackupLocationAttributes(
            protected=True,
            size_bytes=10240,
        ),
        "test": BackupLocationAttributes(
            protected=True,
            size_bytes=10240,
        ),
    }