Debian Codegraph @

tests/test_iot.py

raw
1 """Test the cloud.iot module."""
2
3 import asyncio
4 from unittest.mock import AsyncMock, MagicMock, Mock, call, patch
5
6 from aiohttp import WSMsgType
7 import pytest
8
9 from hass_nabucasa import iot, iot_base
10
11
12 @pytest.fixture
13 def cloud_mock_iot(auth_cloud_mock):
14 """Mock cloud class."""
15 auth_cloud_mock.subscription_expired = False
16 return auth_cloud_mock
17
18
19 def mock_handler_message(conn, mock_iot_client, msg):
20 """Send a message to a handler."""
21 handler_respond_set = asyncio.Event()
22
23 messages = [
24 msg,
25 MagicMock(
26 type=WSMsgType.CLOSE,
27 ),
28 ]
29
30 async def receive_mock(_timeout):
31 if len(messages) == 1:
32 await handler_respond_set.wait()
33
34 return messages.pop(0)
35
36 mock_iot_client.receive = receive_mock
37 mock_iot_client.send_json = AsyncMock(
38 side_effect=lambda _: handler_respond_set.set(),
39 )
40
41
42 @pytest.mark.parametrize(
43 "message",
44 (
45 {
46 "msgid": "test-msg-id",
47 "handler": "test-handler",
48 "payload": "test-payload",
49 },
50 {
51 "msgid": "test-msg-id",
52 "handler": "test-handler",
53 },
54 ),
55 )
56 async def test_cloud_calling_handler(mock_iot_client, cloud_mock_iot, message):
57 """Test we call handle message with correct info."""
58 conn = iot.CloudIoT(cloud_mock_iot)
59 mock_handler_message(
60 conn,
61 mock_iot_client,
62 MagicMock(
63 type=WSMsgType.text,
64 json=MagicMock(return_value=message),
65 ),
66 )
67
68 mock_handler = AsyncMock(return_value="response")
69
70 with patch.dict(iot.HANDLERS, {"test-handler": mock_handler}, clear=True):
71 await conn.connect()
72
73 # Check that we sent message to handler correctly
74 assert len(mock_handler.mock_calls) == 1
75 cloud, payload = mock_handler.mock_calls[0][1]
76
77 assert cloud is cloud_mock_iot
78 assert payload == message.get("payload")
79
80 # Check that we forwarded response from handler to cloud
81 assert len(mock_iot_client.send_json.mock_calls) == 1
82 assert mock_iot_client.send_json.mock_calls[0][1][0] == {
83 "msgid": "test-msg-id",
84 "payload": "response",
85 }
86
87 # Verify events were published (connected and disconnected)
88 assert cloud_mock_iot.events.publish.call_count == 2
89 # First call: RelayerConnectedEvent
90 first_event = cloud_mock_iot.events.publish.call_args_list[0][1]["event"]
91 assert first_event.type == "relayer_connected"
92 # Second call: RelayerDisconnectedEvent
93 second_event = cloud_mock_iot.events.publish.call_args_list[1][1]["event"]
94 assert second_event.type == "relayer_disconnected"
95 assert second_event.reason is not None
96 assert second_event.reason.clean is True
97
98
99 async def test_connection_msg_for_unknown_handler(mock_iot_client, cloud_mock_iot):
100 """Test a msg for an unknown handler."""
101 conn = iot.CloudIoT(cloud_mock_iot)
102 mock_handler_message(
103 conn,
104 mock_iot_client,
105 MagicMock(
106 type=WSMsgType.text,
107 json=MagicMock(
108 return_value={
109 "msgid": "test-msg-id",
110 "handler": "non-existing-test-handler",
111 "payload": "test-payload",
112 },
113 ),
114 ),
115 )
116
117 await conn.connect()
118
119 # Check that we sent the correct error
120 assert len(mock_iot_client.send_json.mock_calls) == 1
121 assert mock_iot_client.send_json.mock_calls[0][1][0] == {
122 "msgid": "test-msg-id",
123 "error": "unknown-handler",
124 }
125
126
127 async def test_connection_msg_for_handler_raising_handler_error(
128 mock_iot_client,
129 cloud_mock_iot,
130 ):
131 """Test we sent error when handler raises HandlerError exception."""
132 conn = iot.CloudIoT(cloud_mock_iot)
133 mock_handler_message(
134 conn,
135 mock_iot_client,
136 MagicMock(
137 type=WSMsgType.text,
138 json=MagicMock(
139 return_value={
140 "msgid": "test-msg-id",
141 "handler": "test-handler",
142 "payload": "test-payload",
143 },
144 ),
145 ),
146 )
147
148 with patch.dict(
149 iot.HANDLERS,
150 {"test-handler": Mock(side_effect=iot.HandlerError("specific_error"))},
151 ):
152 await conn.connect()
153
154 # Check that we sent the correct error
155 assert len(mock_iot_client.send_json.mock_calls) == 1
156 assert mock_iot_client.send_json.mock_calls[0][1][0] == {
157 "msgid": "test-msg-id",
158 "error": "specific_error",
159 }
160
161
162 async def test_connection_msg_for_handler_raising(mock_iot_client, cloud_mock_iot):
163 """Test we sent error when handler raises exception."""
164 conn = iot.CloudIoT(cloud_mock_iot)
165 mock_handler_message(
166 conn,
167 mock_iot_client,
168 MagicMock(
169 type=WSMsgType.text,
170 json=MagicMock(
171 return_value={
172 "msgid": "test-msg-id",
173 "handler": "test-handler",
174 "payload": "test-payload",
175 },
176 ),
177 ),
178 )
179
180 with patch.dict(
181 iot.HANDLERS,
182 {"test-handler": Mock(side_effect=Exception("Broken"))},
183 ):
184 await conn.connect()
185
186 # Check that we sent the correct error
187 assert len(mock_iot_client.send_json.mock_calls) == 1
188 assert mock_iot_client.send_json.mock_calls[0][1][0] == {
189 "msgid": "test-msg-id",
190 "error": "exception",
191 }
192
193
194 async def test_handling_core_messages_logout(cloud_mock_iot):
195 """Test handling core messages."""
196 cloud_mock_iot.logout = AsyncMock()
197 await iot.async_handle_cloud(
198 cloud_mock_iot,
199 {"action": "logout", "reason": "Logged in at two places."},
200 )
201 assert len(cloud_mock_iot.logout.mock_calls) == 1
202
203
204 async def test_handler_alexa(cloud_mock):
205 """Test handler Alexa."""
206 cloud_mock.client.mock_return.append({"test": 5})
207 resp = await iot.async_handle_alexa(cloud_mock, {"test-discovery": True})
208
209 assert len(cloud_mock.client.mock_alexa) == 1
210 assert resp == {"test": 5}
211
212
213 async def test_handler_google(cloud_mock):
214 """Test handler Google."""
215 cloud_mock.client.mock_return.append({"test": 5})
216 resp = await iot.async_handle_google_actions(cloud_mock, {"test-discovery": True})
217
218 assert len(cloud_mock.client.mock_google) == 1
219 assert resp == {"test": 5}
220
221
222 async def test_handler_webhook(cloud_mock):
223 """Test handler Webhook."""
224 cloud_mock.client.mock_return.append({"test": 5})
225 resp = await iot.async_handle_webhook(cloud_mock, {"test-discovery": True})
226
227 assert len(cloud_mock.client.mock_webhooks) == 1
228 assert resp == {"test": 5}
229
230
231 async def test_handler_system(cloud_mock):
232 """Test handler system."""
233 cloud_mock.client.mock_return.append({"test": 5})
234 resp = await iot.async_handle_system(cloud_mock, {"test-discovery": True})
235
236 assert len(cloud_mock.client.mock_system) == 1
237 assert resp == {"test": 5}
238
239
240 async def test_handler_remote_sni(cloud_mock):
241 """Test handler Webhook."""
242 assert not cloud_mock.client.pref_should_connect
243 cloud_mock.remote.snitun_server = "1.1.1.1"
244 resp = await iot.async_handle_remote_sni(cloud_mock, {"ip_address": "8.8.8.8"})
245
246 assert cloud_mock.client.pref_should_connect
247 assert resp == {"server": "1.1.1.1"}
248
249
250 async def test_handler_remote_sni_action(cloud_mock):
251 """Test connection info."""
252 cloud_mock.client.mock_return.append({"test": 5})
253 resp = await iot.async_handle_connection_info(cloud_mock, {})
254 assert resp == {"test": 5}
255
256
257 async def test_send_message_no_answer(cloud_mock_iot):
258 """Test sending a message that expects no answer."""
259 cloud_iot = iot.CloudIoT(cloud_mock_iot)
260 cloud_iot.state = iot_base.STATE_CONNECTED
261 cloud_iot.client = MagicMock(send_json=AsyncMock())
262
263 await cloud_iot.async_send_message("webhook", {"msg": "yo"}, expect_answer=False)
264 assert not cloud_iot._response_handler
265 assert len(cloud_iot.client.send_json.mock_calls) == 1
266 msg = cloud_iot.client.send_json.mock_calls[0][1][0]
267 assert msg["handler"] == "webhook"
268 assert msg["payload"] == {"msg": "yo"}
269
270
271 async def test_send_message_answer(cloud_mock_iot):
272 """Test sending a message that expects an answer."""
273 cloud_iot = iot.CloudIoT(cloud_mock_iot)
274 cloud_iot.state = iot_base.STATE_CONNECTED
275 cloud_iot.client = MagicMock(send_json=AsyncMock())
276
277 uuid = 5
278
279 with patch("hass_nabucasa.iot.uuid.uuid4", return_value=MagicMock(hex=uuid)):
280 send_task = asyncio.create_task(
281 cloud_iot.async_send_message("webhook", {"msg": "yo"}),
282 )
283 await asyncio.sleep(0)
284
285 assert len(cloud_iot.client.send_json.mock_calls) == 1
286 assert len(cloud_iot._response_handler) == 1
287 msg = cloud_iot.client.send_json.mock_calls[0][1][0]
288 assert msg["handler"] == "webhook"
289 assert msg["payload"] == {"msg": "yo"}
290
291 cloud_iot._response_handler[uuid].set_result({"response": True})
292 response = await send_task
293 assert response == {"response": True}
294
295
296 async def test_handling_core_messages_user_notifcation(cloud_mock_iot):
297 """Test handling core messages."""
298 cloud_mock_iot.client.user_message = MagicMock()
299
300 await iot.async_handle_cloud(
301 cloud_mock_iot,
302 {"action": "user_notification", "title": "Test", "message": "My message"},
303 )
304 assert len(cloud_mock_iot.client.user_message.mock_calls) == 1
305
306
307 async def test_handling_core_messages_critical_user_notifcation(cloud_mock_iot):
308 """Test handling core messages."""
309 cloud_mock_iot.client.user_message = MagicMock()
310
311 await iot.async_handle_cloud(
312 cloud_mock_iot,
313 {
314 "action": "critical_user_notification",
315 "title": "Test",
316 "message": "My message",
317 },
318 )
319 assert len(cloud_mock_iot.client.user_message.mock_calls) == 1
320
321
322 async def test_handling_core_messages_remote_disconnect(cloud_mock_iot):
323 """Test handling core messages."""
324 cloud_mock_iot.remote.disconnect = AsyncMock()
325
326 await iot.async_handle_cloud(
327 cloud_mock_iot,
328 {"action": "disconnect_remote"},
329 )
330 assert len(cloud_mock_iot.remote.disconnect.mock_calls) == 1
331
332
333 async def test_handling_core_messages_evaluate_remote_security(cloud_mock_iot):
334 """Test handling core messages."""
335 cloud_mock_iot.remote.connect = AsyncMock()
336 cloud_mock_iot.remote.disconnect = AsyncMock()
337
338 with patch("hass_nabucasa.iot.random.randint", return_value=0):
339 await iot.async_handle_cloud(
340 cloud_mock_iot,
341 {"action": "evaluate_remote_security"},
342 )
343 await asyncio.sleep(0.1)
344
345 assert cloud_mock_iot.remote.disconnect.call_count == 1
346 assert cloud_mock_iot.remote.disconnect.call_args == call(clear_snitun_token=True)
347 assert cloud_mock_iot.remote.connect.call_count == 1