| 1 |
"""Test the cloud component.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from datetime import timedelta |
| 5 |
import json |
| 6 |
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch |
| 7 |
|
| 8 |
from freezegun import freeze_time |
| 9 |
import pytest |
| 10 |
|
| 11 |
import hass_nabucasa as cloud |
| 12 |
from hass_nabucasa.const import SubscriptionReconnectionReason |
| 13 |
from hass_nabucasa.utils import utcnow |
| 14 |
|
| 15 |
from .common import MockClient |
| 16 |
|
| 17 |
|
| 18 |
@pytest.fixture(autouse=True) |
| 19 |
def mock_subscription_info(aioclient_mock): |
| 20 |
"""Mock subscription info.""" |
| 21 |
aioclient_mock.get( |
| 22 |
"https://example.com/account/payments/subscription_info", |
| 23 |
json={ |
| 24 |
"success": True, |
| 25 |
"billing_plan_type": "mock-plan", |
| 26 |
}, |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
@pytest.fixture |
| 31 |
async def cl(cloud_client) -> cloud.Cloud: |
| 32 |
"""Mock cloud client.""" |
| 33 |
with patch( |
| 34 |
"hass_nabucasa.service_discovery.ServiceDiscovery.async_start_service_discovery", |
| 35 |
new=AsyncMock(), |
| 36 |
): |
| 37 |
yield cloud.Cloud( |
| 38 |
cloud_client, |
| 39 |
cloud.MODE_DEV, |
| 40 |
api_server="example.com", |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
def test_constructor_loads_info_from_constant(cloud_client): |
| 45 |
"""Test non-dev mode loads info from SERVERS constant.""" |
| 46 |
with ( |
| 47 |
patch.dict( |
| 48 |
cloud.DEFAULT_VALUES, |
| 49 |
{ |
| 50 |
"beer": { |
| 51 |
"cognito_client_id": "test-cognito_client_id", |
| 52 |
"user_pool_id": "test-user_pool_id", |
| 53 |
"region": "test-region", |
| 54 |
}, |
| 55 |
}, |
| 56 |
), |
| 57 |
patch.dict( |
| 58 |
cloud.DEFAULT_SERVERS, |
| 59 |
{ |
| 60 |
"beer": { |
| 61 |
"relayer": "test-relayer", |
| 62 |
"acme": "test-acme-directory-server", |
| 63 |
"remotestate": "test-google-actions-report-state-url", |
| 64 |
"account_link": "test-account-link-url", |
| 65 |
}, |
| 66 |
}, |
| 67 |
), |
| 68 |
): |
| 69 |
cl = cloud.Cloud(cloud_client, "beer") |
| 70 |
|
| 71 |
assert cl.mode == "beer" |
| 72 |
assert cl.cognito_client_id == "test-cognito_client_id" |
| 73 |
assert cl.user_pool_id == "test-user_pool_id" |
| 74 |
assert cl.region == "test-region" |
| 75 |
assert cl.relayer_server == "test-relayer" |
| 76 |
assert cl.acme_server == "test-acme-directory-server" |
| 77 |
assert cl.remotestate_server == "test-google-actions-report-state-url" |
| 78 |
assert cl.account_link_server == "test-account-link-url" |
| 79 |
|
| 80 |
|
| 81 |
async def test_initialize_loads_info(cl: cloud.Cloud) -> None: |
| 82 |
"""Test initialize will load info from config file. |
| 83 |
|
| 84 |
Also tests that on_initialized callbacks are called when initialization finishes. |
| 85 |
""" |
| 86 |
assert len(cl._on_start) == 2 |
| 87 |
cl._on_start.clear() |
| 88 |
assert len(cl._on_stop) == 3 |
| 89 |
cl._on_stop.clear() |
| 90 |
|
| 91 |
info_file = MagicMock( |
| 92 |
read_text=Mock( |
| 93 |
return_value=json.dumps( |
| 94 |
{ |
| 95 |
"id_token": "test-id-token", |
| 96 |
"access_token": "test-access-token", |
| 97 |
"refresh_token": "test-refresh-token", |
| 98 |
}, |
| 99 |
), |
| 100 |
), |
| 101 |
exists=Mock(return_value=True), |
| 102 |
) |
| 103 |
|
| 104 |
cl.iot = MagicMock() |
| 105 |
cl.iot.connect = AsyncMock() |
| 106 |
|
| 107 |
cl.remote = MagicMock() |
| 108 |
cl.remote.connect = AsyncMock() |
| 109 |
|
| 110 |
start_done_event = asyncio.Event() |
| 111 |
|
| 112 |
async def start_done(): |
| 113 |
start_done_event.set() |
| 114 |
|
| 115 |
cl._on_start.extend([cl.iot.connect, cl.remote.connect]) |
| 116 |
cl.register_on_initialized(start_done) |
| 117 |
|
| 118 |
with ( |
| 119 |
patch( |
| 120 |
"hass_nabucasa.Cloud._decode_claims", |
| 121 |
return_value={"custom:sub-exp": "2080-01-01"}, |
| 122 |
), |
| 123 |
patch( |
| 124 |
"hass_nabucasa.Cloud.user_info_path", |
| 125 |
new_callable=PropertyMock(return_value=info_file), |
| 126 |
), |
| 127 |
patch("hass_nabucasa.auth.CognitoAuth.async_check_token"), |
| 128 |
): |
| 129 |
await cl.initialize() |
| 130 |
await start_done_event.wait() |
| 131 |
|
| 132 |
assert cl.id_token == "test-id-token" |
| 133 |
assert cl.access_token == "test-access-token" |
| 134 |
assert cl.refresh_token == "test-refresh-token" |
| 135 |
assert len(cl.iot.connect.mock_calls) == 1 |
| 136 |
assert len(cl.remote.connect.mock_calls) == 1 |
| 137 |
|
| 138 |
|
| 139 |
async def test_initialize_loads_invalid_info( |
| 140 |
cloud_client: MockClient, |
| 141 |
cl: cloud.Cloud, |
| 142 |
caplog: pytest.LogCaptureFixture, |
| 143 |
) -> None: |
| 144 |
"""Test initialize load invalid info from config file.""" |
| 145 |
info_file = MagicMock( |
| 146 |
read_text=Mock(return_value="invalid json"), |
| 147 |
exists=Mock(return_value=True), |
| 148 |
relative_to=Mock(return_value=".cloud/production_auth.json"), |
| 149 |
) |
| 150 |
|
| 151 |
cl.iot = MagicMock() |
| 152 |
cl.iot.connect = AsyncMock() |
| 153 |
|
| 154 |
cl.remote = MagicMock() |
| 155 |
cl.remote.connect = AsyncMock() |
| 156 |
|
| 157 |
cl._on_start.extend([cl.iot.connect, cl.remote.connect]) |
| 158 |
|
| 159 |
with ( |
| 160 |
patch("hass_nabucasa.Cloud._decode_claims"), |
| 161 |
patch( |
| 162 |
"hass_nabucasa.Cloud.user_info_path", |
| 163 |
new_callable=PropertyMock(return_value=info_file), |
| 164 |
), |
| 165 |
): |
| 166 |
await cl.initialize() |
| 167 |
await asyncio.sleep(0) # Flush out scheduled callbacks |
| 168 |
|
| 169 |
assert cl.id_token is None |
| 170 |
assert len(cl.iot.connect.mock_calls) == 0 |
| 171 |
assert len(cl.remote.connect.mock_calls) == 0 |
| 172 |
assert ( |
| 173 |
"Error loading cloud authentication info from .cloud/production_auth.json: " |
| 174 |
"Expecting value: line 1 column 1 (char 0)" in caplog.text |
| 175 |
) |
| 176 |
assert cloud_client.mock_user |
| 177 |
assert cloud_client.mock_user[0] == ( |
| 178 |
"load_auth_data", |
| 179 |
"Home Assistant Cloud error", |
| 180 |
( |
| 181 |
"Unable to load authentication from .cloud/production_auth.json. " |
| 182 |
"[Please login again](/config/cloud)" |
| 183 |
), |
| 184 |
) |
| 185 |
|
| 186 |
|
| 187 |
async def test_logout_clears_info(cl: cloud.Cloud): |
| 188 |
"""Test logging out disconnects and removes info.""" |
| 189 |
assert len(cl._on_start) == 2 |
| 190 |
cl._on_start.clear() |
| 191 |
assert len(cl._on_stop) == 3 |
| 192 |
cl._on_stop.clear() |
| 193 |
|
| 194 |
info_file = MagicMock( |
| 195 |
exists=Mock(return_value=True), |
| 196 |
unlink=Mock(return_value=True), |
| 197 |
) |
| 198 |
|
| 199 |
cl.id_token = "id_token" |
| 200 |
cl.access_token = "access_token" |
| 201 |
cl.refresh_token = "refresh_token" |
| 202 |
|
| 203 |
cl.iot = MagicMock() |
| 204 |
cl.iot.disconnect = AsyncMock() |
| 205 |
|
| 206 |
cl.google_report_state = MagicMock() |
| 207 |
cl.google_report_state.disconnect = AsyncMock() |
| 208 |
|
| 209 |
cl.remote = MagicMock() |
| 210 |
cl.remote.disconnect = AsyncMock() |
| 211 |
|
| 212 |
cl._on_stop.extend( |
| 213 |
[cl.iot.disconnect, cl.remote.disconnect, cl.google_report_state.disconnect], |
| 214 |
) |
| 215 |
|
| 216 |
with patch( |
| 217 |
"hass_nabucasa.Cloud.user_info_path", |
| 218 |
new_callable=PropertyMock(return_value=info_file), |
| 219 |
): |
| 220 |
await cl.logout() |
| 221 |
|
| 222 |
assert len(cl.iot.disconnect.mock_calls) == 1 |
| 223 |
assert len(cl.google_report_state.disconnect.mock_calls) == 1 |
| 224 |
assert len(cl.remote.disconnect.mock_calls) == 1 |
| 225 |
assert cl.id_token is None |
| 226 |
assert cl.access_token is None |
| 227 |
assert cl.refresh_token is None |
| 228 |
assert info_file.unlink.called |
| 229 |
|
| 230 |
|
| 231 |
async def test_remove_data(cloud_client: MockClient, cl: cloud.Cloud) -> None: |
| 232 |
"""Test removing data.""" |
| 233 |
cloud_dir = cloud_client.base_path / ".cloud" |
| 234 |
cloud_dir.mkdir() |
| 235 |
open(cloud_dir / "unexpected_file", "w") |
| 236 |
|
| 237 |
await cl.remove_data() |
| 238 |
|
| 239 |
assert not cloud_dir.exists() |
| 240 |
|
| 241 |
|
| 242 |
async def test_remove_data_file(cloud_client: MockClient, cl: cloud.Cloud) -> None: |
| 243 |
"""Test removing data when .cloud is not a directory.""" |
| 244 |
cloud_dir = cloud_client.base_path / ".cloud" |
| 245 |
open(cloud_dir, "w") |
| 246 |
|
| 247 |
await cl.remove_data() |
| 248 |
|
| 249 |
assert not cloud_dir.exists() |
| 250 |
|
| 251 |
|
| 252 |
async def test_remove_data_started(cloud_client: MockClient, cl: cloud.Cloud) -> None: |
| 253 |
"""Test removing data when cloud is started.""" |
| 254 |
cloud_dir = cloud_client.base_path / ".cloud" |
| 255 |
cloud_dir.mkdir() |
| 256 |
|
| 257 |
cl.started = True |
| 258 |
with pytest.raises(ValueError, match="Cloud not stopped"): |
| 259 |
await cl.remove_data() |
| 260 |
|
| 261 |
assert cloud_dir.exists() |
| 262 |
cloud_dir.rmdir() |
| 263 |
|
| 264 |
|
| 265 |
def test_write_user_info(cl: cloud.Cloud): |
| 266 |
"""Test writing user info works.""" |
| 267 |
cl.id_token = "test-id-token" |
| 268 |
cl.access_token = "test-access-token" |
| 269 |
cl.refresh_token = "test-refresh-token" |
| 270 |
|
| 271 |
with patch("pathlib.Path.chmod"), patch("hass_nabucasa.atomic_write") as mock_write: |
| 272 |
cl._write_user_info() |
| 273 |
|
| 274 |
mock_file = mock_write.return_value.__enter__.return_value |
| 275 |
|
| 276 |
assert mock_file.write.called |
| 277 |
data = json.loads(mock_file.write.mock_calls[0][1][0]) |
| 278 |
assert data == { |
| 279 |
"access_token": "test-access-token", |
| 280 |
"id_token": "test-id-token", |
| 281 |
"refresh_token": "test-refresh-token", |
| 282 |
} |
| 283 |
|
| 284 |
|
| 285 |
def test_subscription_expired(cl: cloud.Cloud): |
| 286 |
"""Test subscription being expired after 3 days of expiration.""" |
| 287 |
token_val = {"custom:sub-exp": "2018-09-17"} |
| 288 |
|
| 289 |
with ( |
| 290 |
patch.object(cl, "_decode_claims", return_value=token_val), |
| 291 |
): |
| 292 |
assert not cl.subscription_expired |
| 293 |
|
| 294 |
with ( |
| 295 |
patch.object(cl, "_decode_claims", return_value=token_val), |
| 296 |
freeze_time("2018-09-23 23:59:59"), |
| 297 |
): |
| 298 |
assert not cl.subscription_expired |
| 299 |
|
| 300 |
with ( |
| 301 |
patch.object(cl, "_decode_claims", return_value=token_val), |
| 302 |
freeze_time("2018-09-24 00:00:01"), |
| 303 |
): |
| 304 |
assert cl.subscription_expired |
| 305 |
|
| 306 |
|
| 307 |
def test_subscription_not_expired(cl: cloud.Cloud): |
| 308 |
"""Test subscription not being expired.""" |
| 309 |
token_val = {"custom:sub-exp": "2018-09-19"} |
| 310 |
with ( |
| 311 |
patch.object(cl, "_decode_claims", return_value=token_val), |
| 312 |
): |
| 313 |
assert not cl.subscription_expired |
| 314 |
|
| 315 |
|
| 316 |
async def test_claims_decoding(cl: cloud.Cloud): |
| 317 |
"""Test decoding claims.""" |
| 318 |
payload = {"cognito:username": "abc123", "some": "value"} |
| 319 |
encoded_token = cloud.jwt.encode(payload, key="secret") |
| 320 |
|
| 321 |
await cl.update_token(encoded_token, None) |
| 322 |
assert cl.claims == payload |
| 323 |
assert cl.username == "abc123" |
| 324 |
|
| 325 |
|
| 326 |
@pytest.mark.parametrize( |
| 327 |
("since_expired", "expected_sleep_hours"), |
| 328 |
[ |
| 329 |
(timedelta(hours=1), 3), |
| 330 |
(timedelta(days=1), 12), |
| 331 |
(timedelta(days=8), 24), |
| 332 |
(timedelta(days=31), 24), |
| 333 |
(timedelta(days=180), 96), |
| 334 |
], |
| 335 |
) |
| 336 |
async def test_subscription_reconnection_handler_renews_and_starts( |
| 337 |
cl: cloud.Cloud, |
| 338 |
since_expired: timedelta, |
| 339 |
expected_sleep_hours: int, |
| 340 |
caplog: pytest.LogCaptureFixture, |
| 341 |
): |
| 342 |
"""Test the subscription expired handler.""" |
| 343 |
basedate = utcnow() |
| 344 |
_decode_claims_mocker = Mock( |
| 345 |
return_value={ |
| 346 |
"custom:sub-exp": (basedate - since_expired).strftime("%Y-%m-%d") |
| 347 |
}, |
| 348 |
) |
| 349 |
|
| 350 |
async def async_renew_access_token(*args, **kwargs): |
| 351 |
_decode_claims_mocker.return_value = { |
| 352 |
"custom:sub-exp": basedate.strftime("%Y-%m-%d"), |
| 353 |
} |
| 354 |
|
| 355 |
with ( |
| 356 |
patch("hass_nabucasa.Cloud.initialize", AsyncMock()) as _initialize_mocker, |
| 357 |
patch( |
| 358 |
"hass_nabucasa.CognitoAuth.async_renew_access_token", |
| 359 |
side_effect=async_renew_access_token, |
| 360 |
), |
| 361 |
patch("hass_nabucasa.asyncio.sleep", AsyncMock()) as sleep_mock, |
| 362 |
patch( |
| 363 |
"hass_nabucasa.Cloud._decode_claims", |
| 364 |
_decode_claims_mocker, |
| 365 |
), |
| 366 |
patch( |
| 367 |
"hass_nabucasa.Cloud.is_logged_in", |
| 368 |
return_value=True, |
| 369 |
), |
| 370 |
): |
| 371 |
await cl._subscription_reconnection_handler( |
| 372 |
SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED |
| 373 |
) |
| 374 |
|
| 375 |
sleep_mock.assert_called_with(expected_sleep_hours * 60 * 60) |
| 376 |
_initialize_mocker.assert_awaited_once() |
| 377 |
assert "Stopping subscription reconnection handler" in caplog.text |
| 378 |
|
| 379 |
|
| 380 |
async def test_subscription_reconnection_handler_aborts( |
| 381 |
cl: cloud.Cloud, |
| 382 |
caplog: pytest.LogCaptureFixture, |
| 383 |
): |
| 384 |
"""Test the subscription expired handler abort.""" |
| 385 |
basedate = utcnow() |
| 386 |
|
| 387 |
with ( |
| 388 |
patch("hass_nabucasa.Cloud._start", AsyncMock()) as start_mock, |
| 389 |
patch("hass_nabucasa.remote.RemoteUI.start", AsyncMock()) as remote_start_mock, |
| 390 |
patch("hass_nabucasa.asyncio.sleep", AsyncMock()) as sleep_mock, |
| 391 |
patch( |
| 392 |
"hass_nabucasa.Cloud._decode_claims", |
| 393 |
return_value={ |
| 394 |
"custom:sub-exp": (basedate - timedelta(days=450)).strftime("%Y-%m-%d") |
| 395 |
}, |
| 396 |
), |
| 397 |
): |
| 398 |
await cl._subscription_reconnection_handler( |
| 399 |
SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED |
| 400 |
) |
| 401 |
|
| 402 |
sleep_mock.assert_not_awaited() |
| 403 |
sleep_mock.assert_not_called() |
| 404 |
start_mock.assert_not_awaited() |
| 405 |
start_mock.assert_not_called() |
| 406 |
remote_start_mock.assert_not_awaited() |
| 407 |
remote_start_mock.assert_not_called() |
| 408 |
assert "Stopping subscription reconnection handler" in caplog.text |
| 409 |
|
| 410 |
|
| 411 |
async def test_subscription_reconnect_for_no_subscription( |
| 412 |
cl: cloud.Cloud, |
| 413 |
caplog: pytest.LogCaptureFixture, |
| 414 |
): |
| 415 |
"""Test the subscription expired handler for no subscription.""" |
| 416 |
cl._on_start.clear() |
| 417 |
cl._on_stop.clear() |
| 418 |
|
| 419 |
info_file = MagicMock( |
| 420 |
read_text=Mock( |
| 421 |
return_value=json.dumps( |
| 422 |
{ |
| 423 |
"id_token": "test-id-token", |
| 424 |
"access_token": "test-access-token", |
| 425 |
"refresh_token": "test-refresh-token", |
| 426 |
}, |
| 427 |
), |
| 428 |
), |
| 429 |
exists=Mock(return_value=True), |
| 430 |
) |
| 431 |
|
| 432 |
cl.iot = MagicMock() |
| 433 |
cl.iot.connect = AsyncMock() |
| 434 |
|
| 435 |
cl.remote = MagicMock() |
| 436 |
cl.remote.connect = AsyncMock() |
| 437 |
|
| 438 |
start_done_event = asyncio.Event() |
| 439 |
|
| 440 |
async def start_done(): |
| 441 |
start_done_event.set() |
| 442 |
|
| 443 |
cl._on_start.extend([cl.iot.connect, cl.remote.connect]) |
| 444 |
cl.register_on_initialized(start_done) |
| 445 |
|
| 446 |
def subscription_info_mock(billing_plan_type): |
| 447 |
return {"billing_plan_type": billing_plan_type} |
| 448 |
|
| 449 |
with ( |
| 450 |
patch( |
| 451 |
"hass_nabucasa.Cloud._decode_claims", |
| 452 |
return_value={"custom:sub-exp": "2080-01-01"}, |
| 453 |
), |
| 454 |
patch( |
| 455 |
"hass_nabucasa.Cloud.user_info_path", |
| 456 |
new_callable=PropertyMock(return_value=info_file), |
| 457 |
), |
| 458 |
patch("hass_nabucasa.auth.CognitoAuth.async_check_token"), |
| 459 |
patch( |
| 460 |
"hass_nabucasa.CognitoAuth.async_renew_access_token", |
| 461 |
), |
| 462 |
patch("hass_nabucasa.asyncio.sleep", AsyncMock()), |
| 463 |
patch( |
| 464 |
"hass_nabucasa.PaymentsApi.subscription_info", |
| 465 |
side_effect=[ |
| 466 |
subscription_info_mock("no_subscription"), |
| 467 |
subscription_info_mock("mock-plan"), |
| 468 |
], |
| 469 |
), |
| 470 |
): |
| 471 |
await cl.initialize() |
| 472 |
await start_done_event.wait() |
| 473 |
|
| 474 |
assert "No subscription found" in caplog.text |
| 475 |
assert "Stopping subscription reconnection handler" in caplog.text |
| 476 |
|
| 477 |
|
| 478 |
async def test_subscription_reconnection_handler_connection_error( |
| 479 |
cl: cloud.Cloud, |
| 480 |
caplog: pytest.LogCaptureFixture, |
| 481 |
): |
| 482 |
"""Test the subscription reconnection handler for connection errors.""" |
| 483 |
basedate = utcnow() |
| 484 |
|
| 485 |
with ( |
| 486 |
patch("hass_nabucasa.Cloud.initialize", AsyncMock()) as _initialize_mocker, |
| 487 |
patch( |
| 488 |
"hass_nabucasa.CognitoAuth.async_renew_access_token", |
| 489 |
AsyncMock(), |
| 490 |
), |
| 491 |
patch("hass_nabucasa.asyncio.sleep", AsyncMock()) as sleep_mock, |
| 492 |
patch( |
| 493 |
"hass_nabucasa.Cloud._decode_claims", |
| 494 |
return_value={"custom:sub-exp": basedate.strftime("%Y-%m-%d")}, |
| 495 |
), |
| 496 |
patch( |
| 497 |
"hass_nabucasa.Cloud.is_logged_in", |
| 498 |
return_value=True, |
| 499 |
), |
| 500 |
patch("hass_nabucasa.random.uniform", return_value=0.05) as random_mock, |
| 501 |
): |
| 502 |
await cl._subscription_reconnection_handler( |
| 503 |
SubscriptionReconnectionReason.CONNECTION_ERROR |
| 504 |
) |
| 505 |
|
| 506 |
random_mock.assert_called_with(0.01, 0.09) |
| 507 |
|
| 508 |
call_args = sleep_mock.call_args[0][0] |
| 509 |
assert abs(call_args - 216) < 0.1 |
| 510 |
_initialize_mocker.assert_awaited_once() |
| 511 |
assert "Stopping subscription reconnection handler" in caplog.text |
| 512 |
assert "Could not establish connection (attempt 1)" in caplog.text |
| 513 |
assert "waiting 3m:36s before retrying" in caplog.text |