Debian Codegraph @

tests/conftest.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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 yield mock_session
59
60
61 @pytest.fixture
62 async def cloud_mock(loop, aioclient_mock, tmp_path):
63 """Yield a simple cloud mock."""
64 cloud = MagicMock(name="Mock Cloud", is_logged_in=True)
65
66 def _executor(call, *args):
67 """Run executor."""
68 return loop.run_in_executor(None, call, *args)
69
70 cloud.run_executor = _executor
71
72 cloud.websession = aioclient_mock.create_session(loop)
73 cloud.client = MockClient(tmp_path, loop, cloud.websession)
74
75 async def update_token(
76 id_token,
77 access_token,
78 refresh_token=None,
79 ):
80 cloud.id_token = id_token
81 cloud.access_token = access_token
82 if refresh_token is not None:
83 cloud.refresh_token = refresh_token
84
85 cloud.update_token = MagicMock(side_effect=update_token)
86 cloud.ensure_not_connected = AsyncMock()
87
88 yield cloud
89
90 await cloud.websession.close()
91
92
93 @pytest.fixture
94 def auth_cloud_mock(cloud_mock):
95 """Return an authenticated cloud instance."""
96 cloud_mock.accounts = MagicMock(
97 instance_resolve_dns_cname=AsyncMock(),
98 )
99 cloud_mock.auth.async_check_token.side_effect = AsyncMock()
100 cloud_mock.subscription_expired = False
101 cloud_mock.instance = MagicMock(
102 resolve_dns_cname=AsyncMock(),
103 register=AsyncMock(),
104 snitun_token=AsyncMock(),
105 connection=AsyncMock(),
106 create_dns_challenge_record=AsyncMock(),
107 cleanup_dns_challenge_record=AsyncMock(),
108 )
109 cloud_mock.events = MagicMock(
110 publish=AsyncMock(),
111 )
112 return cloud_mock
113
114
115 @pytest.fixture
116 def cloud_client(cloud_mock: MagicMock) -> MockClient:
117 """Return cloud client impl."""
118 return cast("MockClient", cloud_mock.client)
119
120
121 @pytest.fixture
122 async def cloud(
123 aioclient_mock: AiohttpClientMocker,
124 loop: asyncio.AbstractEventLoop,
125 tmp_path: Path,
126 ) -> AsyncGenerator[hass_nabucasa.Cloud, Any]:
127 """Create a cloud fixture."""
128 client_session = aioclient_mock.create_session(loop)
129 client = MockClient(tmp_path, loop, client_session)
130
131 cloud_dir = tmp_path / ".cloud"
132 cloud_dir.mkdir(exist_ok=True)
133
134 with (
135 patch("pathlib.Path.chmod"),
136 patch("pathlib.Path.read_text", return_value=""),
137 patch("pathlib.Path.write_bytes"),
138 patch("pathlib.Path.write_text"),
139 patch("shutil.rmtree"),
140 ):
141 cloud = hass_nabucasa.Cloud(
142 client,
143 "development",
144 cognito_client_id="abc123",
145 region="xx-earth-616",
146 api_server="api.example.com",
147 account_link_server="account-link.example.com",
148 acme_server="acme.example.com",
149 relayer_server="relayer.example.com",
150 remotestate_server="remotestate.example.com",
151 )
152
153 fake_secret = "fake-test-secret"
154
155 id_token_claims = {
156 "cognito:username": "[email protected]",
157 "custom:sub-exp": "2019-09-17",
158 "iat": 1537185600,
159 "exp": 1537185600 + (365 * 24 * 60 * 60),
160 "token_use": "id",
161 }
162
163 access_token_claims = {
164 "client_id": "test-client-id",
165 "username": "[email protected]",
166 "token_use": "access",
167 "scope": "aws.cognito.signin.user.admin",
168 "iat": 1537185600,
169 "exp": 1537185600 + 3600,
170 }
171
172 refresh_token_claims = {
173 "client_id": "test-client-id",
174 "username": "[email protected]",
175 "token_use": "refresh",
176 "iat": 1537185600,
177 "exp": 1537185600 + (30 * 24 * 60 * 60),
178 }
179
180 id_token = jwt.encode(id_token_claims, fake_secret, algorithm="HS256")
181 access_token = jwt.encode(access_token_claims, fake_secret, algorithm="HS256")
182 refresh_token = jwt.encode(refresh_token_claims, fake_secret, algorithm="HS256")
183 renewed_id_token = jwt.encode(id_token_claims, fake_secret, algorithm="HS256")
184 renewed_access_token = jwt.encode(
185 access_token_claims, fake_secret, algorithm="HS256"
186 )
187
188 mock_cognito = MagicMock()
189 mock_cognito.id_token = renewed_id_token
190 mock_cognito.access_token = renewed_access_token
191 cloud.auth._create_cognito_client = MagicMock(return_value=mock_cognito)
192
193 cloud.auth.async_check_token = AsyncMock()
194
195 cloud.id_token = id_token
196 cloud.access_token = access_token
197 cloud.refresh_token = refresh_token
198
199 yield cloud
200 await client_session.close()
201
202
203 @pytest.fixture
204 def mock_cognito():
205 """Mock warrant."""
206 with patch("hass_nabucasa.auth.CognitoAuth._create_cognito_client") as mock_cog:
207 yield mock_cog()
208
209
210 @pytest.fixture
211 def mock_iot_client(cloud_mock):
212 """Mock a base IoT client."""
213
214 class Client(MagicMock):
215 """Websocket client mock."""
216
217 closed = PropertyMock(return_value=False)
218
219 def auto_close(self, msg_count=1):
220 """If the client should disconnect itself after 1 message."""
221 Client.closed = PropertyMock(side_effect=msg_count * [False] + [True])
222
223 async def close(self):
224 """Close the client."""
225
226 client = Client()
227 websession = MagicMock()
228
229 # Trigger cancelled error to avoid reconnect.
230 org_websession = cloud_mock.websession
231 with patch(
232 "hass_nabucasa.iot_base.BaseIoT._wait_retry",
233 side_effect=asyncio.CancelledError,
234 ):
235 websession.ws_connect.side_effect = AsyncMock(return_value=client)
236 cloud_mock.websession = websession
237 yield client
238
239 cloud_mock.websession = org_websession
240
241
242 class DisconnectMockServer(Exception):
243 """Disconnect the mock server."""
244
245
246 @pytest.fixture
247 async def ws_server(aiohttp_client):
248 """Create a mock WS server to connect to and returns a connected client."""
249
250 async def create_client_to_server(handle_server_msg):
251 """Create a websocket server."""
252 logger = logging.getLogger(f"{__name__}.ws_server")
253
254 async def websocket_handler(request):
255 ws = web.WebSocketResponse()
256 await ws.prepare(request)
257 # Send a message to trigger IoTBase with
258 # `mark_connected_after_first_message`
259 await ws.send_json({"msgid": 0, "handler": "hello"})
260
261 async for msg in ws:
262 logger.debug("Received msg: %s", msg)
263 try:
264 resp = await handle_server_msg(msg)
265 if resp is not None:
266 logger.debug("Sending msg: %s", msg)
267 await ws.send_json(resp)
268 except DisconnectMockServer:
269 logger.debug("Closing connection (via DisconnectMockServer)")
270 await ws.close()
271
272 return ws
273
274 app = web.Application()
275 app.add_routes([web.get("/ws", websocket_handler)])
276 client = await aiohttp_client(app)
277 return await client.ws_connect("/ws")
278
279 return create_client_to_server
280
281
282 @pytest.fixture
283 def cloud_with_expired_subscription(cloud: hass_nabucasa.Cloud):
284 """Return a cloud instance with expired subscription."""
285 with patch(
286 "hass_nabucasa.Cloud.subscription_expired",
287 new_callable=PropertyMock,
288 return_value=True,
289 ):
290 yield cloud