| 1 |
"""Set up some common test helper things.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from collections.abc import AsyncGenerator, Generator |
| 5 |
from datetime import datetime |
| 6 |
import json |
| 7 |
import logging |
| 8 |
from pathlib import Path |
| 9 |
from typing import Any, cast |
| 10 |
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch |
| 11 |
|
| 12 |
from aiohttp import web |
| 13 |
from freezegun import freeze_time |
| 14 |
import jwt |
| 15 |
import pytest |
| 16 |
|
| 17 |
import hass_nabucasa |
| 18 |
|
| 19 |
from .common import WELL_KNOWN_SERVICE_DISCOVERY_JSON, FreezeTimeFixture, MockClient |
| 20 |
from .utils.aiohttp import AiohttpClientMocker, mock_aiohttp_client |
| 21 |
|
| 22 |
logging.basicConfig(level=logging.DEBUG) |
| 23 |
|
| 24 |
|
| 25 |
@pytest.fixture |
| 26 |
def service_discovery_fixture_data(): |
| 27 |
"""Load service discovery fixture data from JSON file.""" |
| 28 |
with WELL_KNOWN_SERVICE_DISCOVERY_JSON.open() as f: |
| 29 |
return json.load(f) |
| 30 |
|
| 31 |
|
| 32 |
@pytest.fixture(autouse=True, name="frozen_time") |
| 33 |
def freeze_time_fixture() -> Generator[FreezeTimeFixture, Any]: |
| 34 |
"""Freeze time for all tests by default.""" |
| 35 |
original_timestamp = datetime.timestamp |
| 36 |
|
| 37 |
def consistent_timestamp(self): |
| 38 |
"""Return timestamp rounded to integer seconds for test consistency.""" |
| 39 |
return int(original_timestamp(self)) |
| 40 |
|
| 41 |
with ( |
| 42 |
freeze_time("2018-09-17 12:00:00", tick=True) as time_freezer, |
| 43 |
patch("datetime.datetime.timestamp", consistent_timestamp), |
| 44 |
): |
| 45 |
yield time_freezer |
| 46 |
|
| 47 |
|
| 48 |
@pytest.fixture(name="loop") |
| 49 |
async def loop_fixture(): |
| 50 |
"""Return the event loop.""" |
| 51 |
return asyncio.get_running_loop() |
| 52 |
|
| 53 |
|
| 54 |
@pytest.fixture |
| 55 |
async def aioclient_mock(loop): |
| 56 |
"""Fixture to mock aioclient calls.""" |
| 57 |
with mock_aiohttp_client(loop) as mock_session: |
| •58 |
try: |
| 59 |
yield mock_session |
| 60 |
finally: |
| 61 |
await mock_session.close_sessions() |
| 62 |
|
| 63 |
|
| 64 |
@pytest.fixture |
| 65 |
async def cloud_mock(loop, aioclient_mock, tmp_path): |
| 66 |
"""Yield a simple cloud mock.""" |
| 67 |
cloud = MagicMock(name="Mock Cloud", is_logged_in=True) |
| 68 |
|
| 69 |
def _executor(call, *args): |
| 70 |
"""Run executor.""" |
| 71 |
return loop.run_in_executor(None, call, *args) |
| 72 |
|
| 73 |
cloud.run_executor = _executor |
| 74 |
|
| 75 |
cloud.websession = aioclient_mock.create_session(loop) |
| 76 |
cloud.client = MockClient(tmp_path, loop, cloud.websession) |
| 77 |
|
| 78 |
async def update_token( |
| 79 |
id_token, |
| 80 |
access_token, |
| 81 |
refresh_token=None, |
| 82 |
): |
| 83 |
cloud.id_token = id_token |
| 84 |
cloud.access_token = access_token |
| 85 |
if refresh_token is not None: |
| 86 |
cloud.refresh_token = refresh_token |
| 87 |
|
| 88 |
cloud.update_token = MagicMock(side_effect=update_token) |
| 89 |
cloud.ensure_not_connected = AsyncMock() |
| 90 |
|
| 91 |
yield cloud |
| 92 |
|
| 93 |
await cloud.websession.close() |
| 94 |
|
| 95 |
|
| 96 |
@pytest.fixture |
| 97 |
def auth_cloud_mock(cloud_mock): |
| 98 |
"""Return an authenticated cloud instance.""" |
| 99 |
cloud_mock.accounts = MagicMock( |
| 100 |
instance_resolve_dns_cname=AsyncMock(), |
| 101 |
) |
| 102 |
cloud_mock.auth.async_check_token.side_effect = AsyncMock() |
| 103 |
cloud_mock.subscription_expired = False |
| 104 |
cloud_mock.instance = MagicMock( |
| 105 |
resolve_dns_cname=AsyncMock(), |
| 106 |
register=AsyncMock(), |
| 107 |
snitun_token=AsyncMock(), |
| 108 |
connection=AsyncMock(), |
| 109 |
create_dns_challenge_record=AsyncMock(), |
| 110 |
cleanup_dns_challenge_record=AsyncMock(), |
| 111 |
) |
| 112 |
cloud_mock.events = MagicMock( |
| 113 |
publish=AsyncMock(), |
| 114 |
) |
| 115 |
return cloud_mock |
| 116 |
|
| 117 |
|
| 118 |
@pytest.fixture |
| 119 |
def cloud_client(cloud_mock: MagicMock) -> MockClient: |
| 120 |
"""Return cloud client impl.""" |
| 121 |
return cast("MockClient", cloud_mock.client) |
| 122 |
|
| 123 |
|
| 124 |
@pytest.fixture |
| 125 |
async def cloud( |
| 126 |
aioclient_mock: AiohttpClientMocker, |
| 127 |
loop: asyncio.AbstractEventLoop, |
| 128 |
tmp_path: Path, |
| 129 |
) -> AsyncGenerator[hass_nabucasa.Cloud, Any]: |
| 130 |
"""Create a cloud fixture.""" |
| 131 |
client_session = aioclient_mock.create_session(loop) |
| 132 |
client = MockClient(tmp_path, loop, client_session) |
| 133 |
|
| 134 |
cloud_dir = tmp_path / ".cloud" |
| 135 |
cloud_dir.mkdir(exist_ok=True) |
| 136 |
|
| 137 |
with ( |
| 138 |
patch("pathlib.Path.chmod"), |
| 139 |
patch("pathlib.Path.read_text", return_value=""), |
| 140 |
patch("pathlib.Path.write_bytes"), |
| 141 |
patch("pathlib.Path.write_text"), |
| 142 |
patch("shutil.rmtree"), |
| 143 |
): |
| 144 |
cloud = hass_nabucasa.Cloud( |
| 145 |
client, |
| 146 |
"development", |
| 147 |
cognito_client_id="abc123", |
| 148 |
region="xx-earth-616", |
| 149 |
api_server="api.example.com", |
| 150 |
account_link_server="account-link.example.com", |
| 151 |
acme_server="acme.example.com", |
| 152 |
relayer_server="relayer.example.com", |
| 153 |
remotestate_server="remotestate.example.com", |
| 154 |
) |
| 155 |
|
| 156 |
fake_secret = "fake-test-secret" |
| 157 |
|
| 158 |
id_token_claims = { |
| 159 |
"cognito:username": "[email protected]", |
| 160 |
"custom:sub-exp": "2019-09-17", |
| 161 |
"iat": 1537185600, |
| 162 |
"exp": 1537185600 + (365 * 24 * 60 * 60), |
| 163 |
"token_use": "id", |
| 164 |
} |
| 165 |
|
| 166 |
access_token_claims = { |
| 167 |
"client_id": "test-client-id", |
| 168 |
"username": "[email protected]", |
| 169 |
"token_use": "access", |
| 170 |
"scope": "aws.cognito.signin.user.admin", |
| 171 |
"iat": 1537185600, |
| 172 |
"exp": 1537185600 + 3600, |
| 173 |
} |
| 174 |
|
| 175 |
refresh_token_claims = { |
| 176 |
"client_id": "test-client-id", |
| 177 |
"username": "[email protected]", |
| 178 |
"token_use": "refresh", |
| 179 |
"iat": 1537185600, |
| 180 |
"exp": 1537185600 + (30 * 24 * 60 * 60), |
| 181 |
} |
| 182 |
|
| 183 |
id_token = jwt.encode(id_token_claims, fake_secret, algorithm="HS256") |
| 184 |
access_token = jwt.encode(access_token_claims, fake_secret, algorithm="HS256") |
| 185 |
refresh_token = jwt.encode(refresh_token_claims, fake_secret, algorithm="HS256") |
| 186 |
renewed_id_token = jwt.encode(id_token_claims, fake_secret, algorithm="HS256") |
| 187 |
renewed_access_token = jwt.encode( |
| 188 |
access_token_claims, fake_secret, algorithm="HS256" |
| 189 |
) |
| 190 |
|
| 191 |
mock_cognito = MagicMock() |
| 192 |
mock_cognito.id_token = renewed_id_token |
| 193 |
mock_cognito.access_token = renewed_access_token |
| 194 |
cloud.auth._create_cognito_client = MagicMock(return_value=mock_cognito) |
| 195 |
|
| 196 |
cloud.auth.async_check_token = AsyncMock() |
| 197 |
|
| 198 |
cloud.id_token = id_token |
| 199 |
cloud.access_token = access_token |
| 200 |
cloud.refresh_token = refresh_token |
| 201 |
|
| 202 |
yield cloud |
| 203 |
await client_session.close() |
| 204 |
|
| 205 |
|
| 206 |
@pytest.fixture |
| 207 |
def mock_cognito(): |
| 208 |
"""Mock warrant.""" |
| 209 |
with patch("hass_nabucasa.auth.CognitoAuth._create_cognito_client") as mock_cog: |
| 210 |
yield mock_cog() |
| 211 |
|
| 212 |
|
| 213 |
@pytest.fixture |
| 214 |
def mock_iot_client(cloud_mock): |
| 215 |
"""Mock a base IoT client.""" |
| 216 |
|
| 217 |
class Client(MagicMock): |
| 218 |
"""Websocket client mock.""" |
| 219 |
|
| 220 |
closed = PropertyMock(return_value=False) |
| 221 |
|
| 222 |
def auto_close(self, msg_count=1): |
| 223 |
"""If the client should disconnect itself after 1 message.""" |
| 224 |
Client.closed = PropertyMock(side_effect=msg_count * [False] + [True]) |
| 225 |
|
| 226 |
async def close(self): |
| 227 |
"""Close the client.""" |
| 228 |
|
| 229 |
client = Client() |
| 230 |
websession = MagicMock() |
| 231 |
|
| 232 |
# Trigger cancelled error to avoid reconnect. |
| 233 |
org_websession = cloud_mock.websession |
| 234 |
with patch( |
| 235 |
"hass_nabucasa.iot_base.BaseIoT._wait_retry", |
| 236 |
side_effect=asyncio.CancelledError, |
| 237 |
): |
| 238 |
websession.ws_connect.side_effect = AsyncMock(return_value=client) |
| 239 |
cloud_mock.websession = websession |
| 240 |
yield client |
| 241 |
|
| 242 |
cloud_mock.websession = org_websession |
| 243 |
|
| 244 |
|
| 245 |
class DisconnectMockServer(Exception): |
| 246 |
"""Disconnect the mock server.""" |
| 247 |
|
| 248 |
|
| 249 |
@pytest.fixture |
| 250 |
async def ws_server(aiohttp_client): |
| 251 |
"""Create a mock WS server to connect to and returns a connected client.""" |
| 252 |
|
| 253 |
async def create_client_to_server(handle_server_msg): |
| 254 |
"""Create a websocket server.""" |
| 255 |
logger = logging.getLogger(f"{__name__}.ws_server") |
| 256 |
|
| 257 |
async def websocket_handler(request): |
| 258 |
ws = web.WebSocketResponse() |
| 259 |
await ws.prepare(request) |
| 260 |
# Send a message to trigger IoTBase with |
| 261 |
# `mark_connected_after_first_message` |
| 262 |
await ws.send_json({"msgid": 0, "handler": "hello"}) |
| 263 |
|
| 264 |
async for msg in ws: |
| 265 |
logger.debug("Received msg: %s", msg) |
| 266 |
try: |
| 267 |
resp = await handle_server_msg(msg) |
| 268 |
if resp is not None: |
| 269 |
logger.debug("Sending msg: %s", msg) |
| 270 |
await ws.send_json(resp) |
| 271 |
except DisconnectMockServer: |
| 272 |
logger.debug("Closing connection (via DisconnectMockServer)") |
| 273 |
await ws.close() |
| 274 |
|
| 275 |
return ws |
| 276 |
|
| 277 |
app = web.Application() |
| 278 |
app.add_routes([web.get("/ws", websocket_handler)]) |
| 279 |
client = await aiohttp_client(app) |
| 280 |
return await client.ws_connect("/ws") |
| 281 |
|
| 282 |
return create_client_to_server |
| 283 |
|
| 284 |
|
| 285 |
@pytest.fixture |
| 286 |
def cloud_with_expired_subscription(cloud: hass_nabucasa.Cloud): |
| 287 |
"""Return a cloud instance with expired subscription.""" |
| 288 |
with patch( |
| 289 |
"hass_nabucasa.Cloud.subscription_expired", |
| 290 |
new_callable=PropertyMock, |
| 291 |
return_value=True, |
| 292 |
): |
| 293 |
yield cloud |