Debian Codegraph @

tests/test_files.py

raw
1 """Tests for Files."""
2
3 from collections.abc import AsyncIterator, Iterable
4 import re
5 from typing import Any
6 from unittest.mock import AsyncMock, Mock, call, patch
7
8 from aiohttp import ClientError
9 import pytest
10 from syrupy import SnapshotAssertion
11
12 from hass_nabucasa import Cloud
13 from hass_nabucasa.api import CloudApiNonRetryableError
14 from hass_nabucasa.files import FilesError, calculate_b64md5
15 from tests.common import extract_log_messages
16 from tests.utils.aiohttp import AiohttpClientMocker
17
18 FILES_API_URL = "https://files.api.fakeurl/path?X-Amz-Algorithm=***"
19
20
21 STORED_BACKUP = {
22 "Key": "backup.tar",
23 "Size": 1024,
24 "LastModified": "2021-07-01T12:00:00Z",
25 "Metadata": {"beer": "me"},
26 }
27
28
29 @pytest.mark.parametrize(
30 "exception,msg",
31 [
32 [TimeoutError, "Timeout reached while calling API"],
33 [ClientError, "Failed to fetch"],
34 [Exception, "Unexpected error while calling API"],
35 ],
36 )
37 async def test_upload_exceptions_while_getting_details(
38 aioclient_mock: AiohttpClientMocker,
39 cloud: Cloud,
40 exception: Exception,
41 msg: str,
42 ):
43 """Test handling exceptions when fetching upload details."""
44 aioclient_mock.get(
45 f"https://{cloud.api_server}/files/upload_details",
46 exc=exception("Boom!"),
47 )
48
49 with pytest.raises(FilesError, match=msg):
50 await cloud.files.upload(
51 storage_type="test",
52 open_stream=AsyncMock(),
53 filename="lorem.ipsum",
54 base64md5hash="hash",
55 size=1337,
56 metadata={"awesome": True},
57 )
58
59
60 @pytest.mark.parametrize(
61 "putmockargs,msg",
62 [
63 [
64 {"exc": TimeoutError("Boom!")},
65 "Timeout reached while calling API: total allowed time is 43200.0 seconds",
66 ],
67 [{"exc": ClientError("Boom!")}, "Failed to fetch: Boom!"],
68 [{"exc": Exception("Boom!")}, "Unexpected error while calling API: Boom!"],
69 [{"status": 400}, "Failed to upload: (400) "],
70 [
71 {"status": 400, "text": "Unknown error structure"},
72 "Failed to upload: (400) Unknown error structure",
73 ],
74 [
75 {
76 "status": 400,
77 "text": "<Message>Pretty error\nWith a linebreak</Message>",
78 },
79 "Failed to upload: (400) Pretty error With a linebreak",
80 ],
81 [
82 {
83 "status": 400,
84 "text": "<Message>What is this?",
85 },
86 "Failed to upload: (400) <Message>What is this?",
87 ],
88 [
89 {
90 "status": 400,
91 "text": f"{'a' * 512}",
92 },
93 f"Failed to upload: (400) {'a' * 256}",
94 ],
95 [
96 {
97 "status": 403,
98 "text": "<Message>Pretty error\nWith a linebreak</Message>",
99 },
100 "Failed to upload: (403) Pretty error With a linebreak",
101 ],
102 [
103 {
104 "status": 500,
105 "text": "<Message>Pretty error\nWith a linebreak</Message>",
106 },
107 "Failed to upload: (500) ",
108 ],
109 ],
110 )
111 async def test_upload_exceptions_while_uploading(
112 aioclient_mock: AiohttpClientMocker,
113 cloud: Cloud,
114 putmockargs: dict[str, Any],
115 msg: str,
116 caplog: pytest.LogCaptureFixture,
117 snapshot: SnapshotAssertion,
118 ):
119 """Test handling exceptions during file upload."""
120 aioclient_mock.get(
121 f"https://{cloud.api_server}/files/upload_details",
122 json={"url": FILES_API_URL, "headers": {}},
123 )
124
125 aioclient_mock.put(FILES_API_URL, **putmockargs)
126
127 with pytest.raises(FilesError, match=f"^{re.escape(msg)}$"):
128 await cloud.files.upload(
129 storage_type="test",
130 open_stream=AsyncMock(),
131 filename="lorem.ipsum",
132 base64md5hash="hash",
133 size=1337,
134 metadata={"awesome": True},
135 )
136 assert extract_log_messages(caplog) == snapshot
137
138
139 @pytest.mark.parametrize(
140 "exception,getmockargs",
141 [
142 [
143 FilesError,
144 {"status": 400, "json": {"message": "NC-CE-01"}},
145 ],
146 [
147 CloudApiNonRetryableError,
148 {"status": 400, "json": {"message": "NC-CE-03"}},
149 ],
150 [
151 FilesError,
152 {"status": 500, "text": "Internal Server Error"},
153 ],
154 ],
155 )
156 async def test_upload_bad_status_while_getting_upload_details(
157 aioclient_mock: AiohttpClientMocker,
158 cloud: Cloud,
159 exception: Exception,
160 getmockargs: dict[str, Any],
161 caplog: pytest.LogCaptureFixture,
162 snapshot: SnapshotAssertion,
163 ):
164 """Test handling bad status codes when fetching upload details."""
165 aioclient_mock.get(
166 f"https://{cloud.api_server}/files/upload_details",
167 **getmockargs,
168 )
169
170 with pytest.raises(exception):
171 await cloud.files.upload(
172 storage_type="test",
173 open_stream=AsyncMock(),
174 filename="lorem.ipsum",
175 base64md5hash="hash",
176 size=1337,
177 metadata={"awesome": True},
178 )
179
180 assert extract_log_messages(caplog) == snapshot
181
182
183 async def test_upload_returning_403_and_expired_subscription(
184 aioclient_mock: AiohttpClientMocker,
185 cloud_with_expired_subscription: Cloud,
186 caplog: pytest.LogCaptureFixture,
187 snapshot: SnapshotAssertion,
188 ):
189 """Test handling 403 when the subscription is expired."""
190 cloud = cloud_with_expired_subscription
191
192 aioclient_mock.get(
193 f"https://{cloud.api_server}/files/upload_details",
194 status=403,
195 json={"message": "Forbidden"},
196 )
197
198 with pytest.raises(CloudApiNonRetryableError, match="Subscription has expired"):
199 await cloud.files.upload(
200 storage_type="test",
201 open_stream=AsyncMock(),
202 filename="lorem.ipsum",
203 base64md5hash="hash",
204 size=1337,
205 metadata={"awesome": True},
206 )
207
208 assert extract_log_messages(caplog) == snapshot
209
210
211 @pytest.mark.parametrize(
212 "exception,putmockargs",
213 [
214 [
215 FilesError,
216 {"status": 400, "json": {"message": "Oh no!"}},
217 ],
218 [
219 FilesError,
220 {"status": 500, "text": "Internal Server Error"},
221 ],
222 ],
223 )
224 async def test_upload_bad_status_while_uploading(
225 aioclient_mock: AiohttpClientMocker,
226 cloud: Cloud,
227 exception: Exception,
228 putmockargs: dict[str, Any],
229 caplog: pytest.LogCaptureFixture,
230 snapshot: SnapshotAssertion,
231 ):
232 """Test handling bad status codes during file upload."""
233 aioclient_mock.get(
234 f"https://{cloud.api_server}/files/upload_details",
235 json={"url": FILES_API_URL, "headers": {}},
236 )
237
238 aioclient_mock.put(FILES_API_URL, **putmockargs)
239
240 with pytest.raises(exception):
241 await cloud.files.upload(
242 storage_type="test",
243 open_stream=AsyncMock(),
244 filename="lorem.ipsum",
245 base64md5hash="hash",
246 size=1337,
247 metadata={"awesome": True},
248 )
249
250 assert extract_log_messages(caplog) == snapshot
251
252
253 async def test_upload(
254 aioclient_mock: AiohttpClientMocker,
255 cloud: Cloud,
256 caplog: pytest.LogCaptureFixture,
257 snapshot: SnapshotAssertion,
258 ):
259 """Test successful file upload."""
260 aioclient_mock.get(
261 f"https://{cloud.api_server}/files/upload_details",
262 json={"url": FILES_API_URL, "headers": {}},
263 )
264 aioclient_mock.get(
265 f"https://{cloud.api_server}/v2/files/test",
266 json=[STORED_BACKUP],
267 )
268
269 aioclient_mock.put(FILES_API_URL, status=200)
270
271 await cloud.files.upload(
272 storage_type="test",
273 open_stream=AsyncMock(),
274 filename="lorem.ipsum",
275 base64md5hash="hash",
276 size=1337,
277 metadata={"awesome": True},
278 )
279
280 assert extract_log_messages(caplog) == snapshot
281
282
283 @pytest.mark.parametrize(
284 "exception,msg",
285 [
286 [TimeoutError, "Timeout reached while calling API"],
287 [ClientError, "Failed to fetch"],
288 [Exception, "Unexpected error while calling API"],
289 ],
290 )
291 async def test_download_exceptions_while_getting_details(
292 aioclient_mock: AiohttpClientMocker,
293 cloud: Cloud,
294 exception: Exception,
295 msg: str,
296 ):
297 """Test handling exceptions when fetching download details."""
298 aioclient_mock.get(
299 f"https://{cloud.api_server}/files/download_details/test/lorem.ipsum",
300 exc=exception("Boom!"),
301 )
302
303 with pytest.raises(FilesError, match=msg):
304 await cloud.files.download(
305 storage_type="test",
306 filename="lorem.ipsum",
307 )
308
309
310 @pytest.mark.parametrize(
311 "exception,msg",
312 [
313 [TimeoutError, "Timeout reached while calling API"],
314 [ClientError, "Failed to fetch"],
315 [Exception, "Unexpected error while calling API"],
316 ],
317 )
318 async def test_upload_exceptions_while_downloading(
319 aioclient_mock: AiohttpClientMocker,
320 cloud: Cloud,
321 exception: Exception,
322 msg: str,
323 ):
324 """Test handling exceptions during file download."""
325 aioclient_mock.get(
326 f"https://{cloud.api_server}/files/download_details/test/lorem.ipsum",
327 json={"url": FILES_API_URL},
328 )
329
330 aioclient_mock.get(FILES_API_URL, exc=exception("Boom!"))
331
332 with pytest.raises(FilesError, match=msg):
333 await cloud.files.download(
334 storage_type="test",
335 filename="lorem.ipsum",
336 )
337
338
339 @pytest.mark.parametrize(
340 "exception,getmockargs",
341 [
342 [
343 CloudApiNonRetryableError,
344 {"status": 400, "json": {"message": "NC-SH-FH-03 (abc-123)"}},
345 ],
346 [
347 CloudApiNonRetryableError,
348 {"status": 400, "json": {"message": "NC-CE-03"}},
349 ],
350 [
351 FilesError,
352 {"status": 400, "json": {"message": "NC-CE-01"}},
353 ],
354 [
355 FilesError,
356 {"status": 500, "text": "Internal Server Error"},
357 ],
358 ],
359 )
360 async def test_upload_bad_status_while_getting_download_details(
361 aioclient_mock: AiohttpClientMocker,
362 cloud: Cloud,
363 exception: Exception,
364 getmockargs: dict[str, Any],
365 caplog: pytest.LogCaptureFixture,
366 snapshot: SnapshotAssertion,
367 ):
368 """Test handling bad status codes when fetching download details."""
369 aioclient_mock.get(
370 f"https://{cloud.api_server}/files/download_details/test/lorem.ipsum",
371 **getmockargs,
372 )
373
374 with pytest.raises(exception):
375 await cloud.files.download(
376 storage_type="test",
377 filename="lorem.ipsum",
378 )
379
380 assert extract_log_messages(caplog) == snapshot
381
382
383 @pytest.mark.parametrize(
384 "exception,getmockargs",
385 [
386 [
387 FilesError,
388 {"status": 400, "json": {"message": "Oh no!"}},
389 ],
390 [
391 FilesError,
392 {"status": 500, "text": "Internal Server Error"},
393 ],
394 ],
395 )
396 async def test_upload_bad_status_while_downloading(
397 aioclient_mock: AiohttpClientMocker,
398 cloud: Cloud,
399 exception: Exception,
400 getmockargs: dict[str, Any],
401 caplog: pytest.LogCaptureFixture,
402 snapshot: SnapshotAssertion,
403 ):
404 """Test handling bad status codes during file download."""
405 aioclient_mock.get(
406 f"https://{cloud.api_server}/files/download_details/test/lorem.ipsum",
407 json={"url": FILES_API_URL},
408 )
409
410 aioclient_mock.get(FILES_API_URL, **getmockargs)
411
412 with pytest.raises(exception):
413 await cloud.files.download(
414 storage_type="test",
415 filename="lorem.ipsum",
416 )
417
418 assert extract_log_messages(caplog) == snapshot
419
420
421 async def test_download(
422 aioclient_mock: AiohttpClientMocker,
423 cloud: Cloud,
424 caplog: pytest.LogCaptureFixture,
425 snapshot: SnapshotAssertion,
426 ):
427 """Test successful file download."""
428 aioclient_mock.get(
429 f"https://{cloud.api_server}/files/download_details/test/lorem.ipsum",
430 json={"url": FILES_API_URL},
431 )
432
433 aioclient_mock.get(FILES_API_URL, status=200)
434
435 await cloud.files.download(
436 storage_type="test",
437 filename="lorem.ipsum",
438 )
439 assert "Downloading test file with name lorem.ipsum" in caplog.text
440 assert len(aioclient_mock.mock_calls) == 2
441 assert extract_log_messages(caplog) == snapshot
442
443
444 async def test_list(
445 aioclient_mock: AiohttpClientMocker,
446 cloud: Cloud,
447 caplog: pytest.LogCaptureFixture,
448 snapshot: SnapshotAssertion,
449 ):
450 """Test listing files."""
451 aioclient_mock.get(
452 f"https://{cloud.api_server}/v2/files/test",
453 json=[STORED_BACKUP],
454 )
455
456 files = await cloud.files.list(storage_type="test")
457
458 assert files[0] == STORED_BACKUP
459 assert len(aioclient_mock.mock_calls) == 1
460 assert extract_log_messages(caplog) == snapshot
461
462
463 async def test_list_with_clear_cache(
464 aioclient_mock: AiohttpClientMocker,
465 cloud: Cloud,
466 caplog: pytest.LogCaptureFixture,
467 snapshot: SnapshotAssertion,
468 ):
469 """Test listing files."""
470 aioclient_mock.get(
471 f"https://{cloud.api_server}/v2/files/test?clearCache=true",
472 json=[STORED_BACKUP],
473 )
474
475 files = await cloud.files.list(storage_type="test", clear_cache=True)
476
477 assert files[0] == STORED_BACKUP
478 assert len(aioclient_mock.mock_calls) == 1
479 assert extract_log_messages(caplog) == snapshot
480
481
482 @pytest.mark.parametrize(
483 "exception,msg",
484 [
485 [TimeoutError, "Timeout reached while calling API"],
486 [ClientError, "Failed to fetch"],
487 [Exception, "Unexpected error while calling API"],
488 ],
489 )
490 async def test_exceptions_while_listing(
491 aioclient_mock: AiohttpClientMocker,
492 cloud: Cloud,
493 exception: Exception,
494 msg: str,
495 ):
496 """Test handling exceptions during file download."""
497 aioclient_mock.get(
498 f"https://{cloud.api_server}/v2/files/test", exc=exception("Boom!")
499 )
500
501 with pytest.raises(FilesError, match=msg):
502 await cloud.files.list(storage_type="test")
503
504 assert len(aioclient_mock.mock_calls) == 1
505
506
507 async def test_delete(
508 aioclient_mock: AiohttpClientMocker,
509 cloud: Cloud,
510 caplog: pytest.LogCaptureFixture,
511 snapshot: SnapshotAssertion,
512 ):
513 """Test listing files."""
514 aioclient_mock.delete(f"https://{cloud.api_server}/files")
515
516 await cloud.files.delete(storage_type="test", filename="lorem.ipsum")
517
518 assert len(aioclient_mock.mock_calls) == 1
519 assert aioclient_mock.mock_calls[0][2] == {
520 "filename": "lorem.ipsum",
521 "storage_type": "test",
522 }
523 assert extract_log_messages(caplog) == snapshot
524
525
526 @pytest.mark.parametrize(
527 "exception_msg,deletemockargs",
528 [
529 [
530 "Failed to fetch: (400) ",
531 {"status": 400, "json": {"message": "NC-CE-01"}},
532 ],
533 [
534 "Failed to fetch: (500) ",
535 {"status": 500, "text": "Internal Server Error"},
536 ],
537 ],
538 )
539 async def test_exceptions_while_deleting(
540 aioclient_mock: AiohttpClientMocker,
541 cloud: Cloud,
542 exception_msg: str,
543 deletemockargs: dict[str, Any],
544 caplog: pytest.LogCaptureFixture,
545 snapshot: SnapshotAssertion,
546 ):
547 """Test handling exceptions during file download."""
548 aioclient_mock.delete(f"https://{cloud.api_server}/files", **deletemockargs)
549
550 with pytest.raises(FilesError, match=re.escape(exception_msg)):
551 await cloud.files.delete(storage_type="test", filename="lorem.ipsum")
552 assert len(aioclient_mock.mock_calls) == 1
553 assert extract_log_messages(caplog) == snapshot
554
555
556 async def aiter_from_iter(iterable: Iterable) -> AsyncIterator:
557 """Convert an iterable to an async iterator."""
558 for i in iterable:
559 yield i
560
561
562 async def test_upload_calls_on_progress(
563 aioclient_mock: AiohttpClientMocker,
564 cloud: Cloud,
565 ):
566 """Test that on_progress is called with cumulative bytes_uploaded."""
567 aioclient_mock.get(
568 f"https://{cloud.api_server}/files/upload_details",
569 json={"url": FILES_API_URL, "headers": {}},
570 )
571 aioclient_mock.get(
572 f"https://{cloud.api_server}/v2/files/test",
573 json=[STORED_BACKUP],
574 )
575 aioclient_mock.put(FILES_API_URL, status=200)
576
577 async def open_stream() -> AsyncIterator[bytes]:
578 return aiter_from_iter((b"backup", b"data"))
579
580 on_progress = Mock()
581
582 original_request = cloud.websession.request
583
584 async def consuming_request(method: str, url: str, **kwargs: Any) -> Any:
585 if method.upper() == "PUT" and hasattr(data := kwargs.get("data"), "__aiter__"):
586 chunks = [chunk async for chunk in data]
587
588 async def replay() -> AsyncIterator[bytes]:
589 for chunk in chunks:
590 yield chunk
591
592 kwargs["data"] = replay()
593 return await original_request(method, url, **kwargs)
594
595 with patch.object(cloud.websession, "request", consuming_request):
596 await cloud.files.upload(
597 storage_type="test",
598 open_stream=open_stream,
599 filename="lorem.ipsum",
600 base64md5hash="hash",
601 size=10,
602 on_progress=on_progress,
603 )
604
605 assert on_progress.call_args_list == [
606 call(bytes_uploaded=6),
607 call(bytes_uploaded=10),
608 ]
609
610
611 async def test_calculate_b64md5():
612 """Test calculating base64 md5 hash."""
613
614 async def open_stream() -> AsyncIterator[bytes]:
615 """Mock open stream."""
616 return aiter_from_iter((b"backup", b"data"))
617
618 assert await calculate_b64md5(open_stream, 10) == "p17gbFrsI2suQNBhkdO1Gw=="
619
620 with pytest.raises(
621 FilesError,
622 match="Indicated size 9 does not match actual size 10",
623 ):
624 await calculate_b64md5(open_stream, 9)