| 1 |
"""Tests for Account API.""" |
| 2 |
|
| 3 |
import re |
| 4 |
from typing import Any |
| 5 |
|
| 6 |
from aiohttp import ClientError |
| 7 |
import pytest |
| 8 |
from syrupy import SnapshotAssertion |
| 9 |
|
| 10 |
from hass_nabucasa import Cloud |
| 11 |
from hass_nabucasa.account_api import ( |
| 12 |
AccountApiError, |
| 13 |
AccountServicesDetails, |
| 14 |
) |
| 15 |
from tests.common import extract_log_messages |
| 16 |
from tests.utils.aiohttp import AiohttpClientMocker |
| 17 |
|
| 18 |
|
| 19 |
@pytest.mark.parametrize( |
| 20 |
"exception,mockargs,exception_msg", |
| 21 |
[ |
| 22 |
[ |
| 23 |
AccountApiError, |
| 24 |
{"status": 500, "text": "Internal Server Error"}, |
| 25 |
"Failed to parse API response", |
| 26 |
], |
| 27 |
[ |
| 28 |
AccountApiError, |
| 29 |
{"status": 429, "text": "Too fast"}, |
| 30 |
"Failed to parse API response", |
| 31 |
], |
| 32 |
[ |
| 33 |
AccountApiError, |
| 34 |
{"exc": TimeoutError()}, |
| 35 |
"Timeout reached while calling API", |
| 36 |
], |
| 37 |
[ |
| 38 |
AccountApiError, |
| 39 |
{"exc": ClientError("boom!")}, |
| 40 |
"Failed to fetch: boom!", |
| 41 |
], |
| 42 |
[ |
| 43 |
AccountApiError, |
| 44 |
{"exc": Exception("boom!")}, |
| 45 |
"Unexpected error while calling API: boom!", |
| 46 |
], |
| 47 |
], |
| 48 |
ids=["500-error", "429-error", "timeout", "client-error", "unexpected-error"], |
| 49 |
) |
| 50 |
async def test_problems_getting_services( |
| 51 |
aioclient_mock: AiohttpClientMocker, |
| 52 |
cloud: Cloud, |
| 53 |
exception: Exception, |
| 54 |
mockargs: dict[str, Any], |
| 55 |
exception_msg: str, |
| 56 |
caplog: pytest.LogCaptureFixture, |
| 57 |
snapshot: SnapshotAssertion, |
| 58 |
): |
| 59 |
"""Test problems getting account services.""" |
| 60 |
aioclient_mock.get( |
| 61 |
f"https://{cloud.api_server}/account/services", |
| 62 |
**mockargs, |
| 63 |
) |
| 64 |
|
| 65 |
with pytest.raises(exception, match=re.escape(exception_msg)): |
| 66 |
await cloud.account.services() |
| 67 |
|
| 68 |
assert extract_log_messages(caplog) == snapshot |
| 69 |
|
| 70 |
|
| 71 |
@pytest.mark.parametrize( |
| 72 |
"services_response", |
| 73 |
[{"alexa": {"available": True}, "storage": {"available": False}}], |
| 74 |
) |
| 75 |
async def test_getting_services( |
| 76 |
aioclient_mock: AiohttpClientMocker, |
| 77 |
cloud: Cloud, |
| 78 |
services_response: AccountServicesDetails, |
| 79 |
caplog: pytest.LogCaptureFixture, |
| 80 |
snapshot: SnapshotAssertion, |
| 81 |
): |
| 82 |
"""Test getting account services.""" |
| 83 |
aioclient_mock.get( |
| 84 |
f"https://{cloud.api_server}/account/services", |
| 85 |
json=services_response, |
| 86 |
) |
| 87 |
|
| 88 |
services = await cloud.account.services() |
| 89 |
|
| 90 |
assert services == services_response |
| 91 |
assert extract_log_messages(caplog) == snapshot |