Debian Codegraph @

tests/test_iot_base.py

raw
1 """Test the cloud.iot_base module."""
2
3 from unittest.mock import AsyncMock, MagicMock, Mock
4
5 from aiohttp import WSMessage, WSMsgType, client_exceptions
6 import pytest
7
8 from hass_nabucasa import CloudError, iot_base
9
10
11 class MockIoT(iot_base.BaseIoT):
12 """Mock class for IoT."""
13
14 def __init__(self, cloud, require_subscription=True) -> None:
15 """Initialize test IoT class."""
16 super().__init__(cloud)
17 self.received = []
18 self._require_subscription = require_subscription
19
20 @property
21 def package_name(self) -> str:
22 """Return package name for logging."""
23 return __name__
24
25 @property
26 def ws_server_url(self) -> str:
27 """Server to connect to."""
28 return "http://example.com"
29
30 @property
31 def require_subscription(self) -> bool:
32 """If the server requires a valid subscription."""
33 return self._require_subscription
34
35 def async_handle_message(self, msg) -> None:
36 """Handle incoming message.
37
38 Run all async tasks in a wrapper to log appropriately.
39 """
40
41
42 @pytest.fixture
43 def cloud_mock_iot(auth_cloud_mock):
44 """Mock cloud class."""
45 auth_cloud_mock.subscription_expired = False
46 return auth_cloud_mock
47
48
49 @pytest.mark.parametrize(
50 "require_first_message,messages,disconnect_reason",
51 [
52 (
53 False,
54 [
55 WSMessage(
56 type=WSMsgType.CLOSING,
57 data=4002,
58 extra="Another instance connected",
59 ),
60 ],
61 iot_base.DisconnectReason(
62 True,
63 "Connection closed: Closed by server. "
64 "Another instance connected (4002)",
65 ),
66 ),
67 (
68 True,
69 [
70 WSMessage(
71 type=WSMsgType.CLOSING,
72 data=4002,
73 extra="Another instance connected",
74 ),
75 ],
76 iot_base.DisconnectReason(
77 False,
78 "Connection closed: Closed by server. "
79 "Another instance connected (4002)",
80 ),
81 ),
82 (
83 True,
84 [
85 WSMessage(
86 type=WSMsgType.TEXT,
87 data='{"msgid": "1", "handler": "system"}',
88 extra=None,
89 ),
90 WSMessage(
91 type=WSMsgType.CLOSING,
92 data=4002,
93 extra="Another instance connected",
94 ),
95 ],
96 iot_base.DisconnectReason(
97 True,
98 "Connection closed: Closed by server. "
99 "Another instance connected (4002)",
100 ),
101 ),
102 ],
103 )
104 async def test_cloud_getting_disconnected_by_server(
105 mock_iot_client,
106 caplog,
107 cloud_mock_iot,
108 require_first_message,
109 messages,
110 disconnect_reason,
111 ):
112 """Test server disconnecting instance."""
113 conn = MockIoT(cloud_mock_iot)
114 conn.mark_connected_after_first_message = require_first_message
115 mock_iot_client.receive = AsyncMock(side_effect=messages)
116
117 await conn.connect()
118
119 assert "Connection closed" in caplog.text
120 assert conn.last_disconnect_reason == disconnect_reason
121
122
123 async def test_cloud_receiving_bytes(mock_iot_client, caplog, cloud_mock_iot):
124 """Test server disconnecting instance."""
125 conn = MockIoT(cloud_mock_iot)
126 mock_iot_client.receive = AsyncMock(return_value=MagicMock(type=WSMsgType.BINARY))
127
128 await conn.connect()
129
130 assert "Connection closed: Received non-Text message" in caplog.text
131
132
133 async def test_cloud_sending_invalid_json(mock_iot_client, caplog, cloud_mock_iot):
134 """Test cloud sending invalid JSON."""
135 conn = MockIoT(cloud_mock_iot)
136 mock_iot_client.receive = AsyncMock(
137 return_value=MagicMock(
138 type=WSMsgType.TEXT,
139 json=MagicMock(side_effect=ValueError),
140 ),
141 )
142
143 await conn.connect()
144
145 assert "Connection closed: Received invalid JSON." in caplog.text
146
147
148 async def test_cloud_check_token_raising(mock_iot_client, caplog, cloud_mock_iot):
149 """Test cloud unable to check token."""
150 conn = MockIoT(cloud_mock_iot)
151 cloud_mock_iot.auth.async_check_token.side_effect = CloudError("BLA")
152
153 await conn.connect()
154
155 assert "Unable to connect due to token refresh failure: BLA" in caplog.text
156
157
158 async def test_cloud_connect_invalid_auth(mock_iot_client, caplog, cloud_mock_iot):
159 """Test invalid auth detected by server."""
160 conn = MockIoT(cloud_mock_iot)
161 request_info = Mock(real_url="http://example.com")
162 mock_iot_client.receive.side_effect = client_exceptions.WSServerHandshakeError(
163 request_info=request_info,
164 history=None,
165 status=401,
166 )
167
168 await conn.connect()
169
170 assert "Connection closed: Invalid auth." in caplog.text
171
172
173 async def test_cloud_unable_to_connect(
174 cloud_mock,
175 caplog,
176 cloud_mock_iot,
177 mock_iot_client,
178 ):
179 """Test unable to connect error."""
180 conn = MockIoT(cloud_mock_iot)
181 cloud_mock.websession.ws_connect.side_effect = client_exceptions.ClientError(
182 "SSL Verification failed",
183 )
184 await conn.connect()
185 assert conn.last_disconnect_reason == iot_base.DisconnectReason(
186 False,
187 "Unable to connect: SSL Verification failed",
188 )
189 assert "Unable to connect:" in caplog.text
190
191
192 async def test_cloud_connection_reset_exception(
193 mock_iot_client,
194 caplog,
195 cloud_mock_iot,
196 ):
197 """Test connection reset exception."""
198 conn = MockIoT(cloud_mock_iot)
199 mock_iot_client.receive.side_effect = ConnectionResetError(
200 "Cannot write to closing transport",
201 )
202
203 await conn.connect()
204
205 assert conn.last_disconnect_reason == iot_base.DisconnectReason(
206 False,
207 "Connection closed: Cannot write to closing transport",
208 )
209 assert "Cannot write to closing transport" in caplog.text
210
211
212 async def test_cloud_random_exception(mock_iot_client, caplog, cloud_mock_iot):
213 """Test random exception."""
214 conn = MockIoT(cloud_mock_iot)
215 mock_iot_client.receive.side_effect = Exception
216
217 await conn.connect()
218
219 assert "Unexpected error" in caplog.text
220
221
222 async def test_refresh_token_before_expiration_fails(auth_cloud_mock):
223 """Test that we don't connect if token is expired."""
224 auth_cloud_mock.subscription_expired = True
225 conn = MockIoT(auth_cloud_mock)
226
227 await conn.connect()
228
229 assert len(auth_cloud_mock.auth.async_check_token.mock_calls) == 1
230 assert len(auth_cloud_mock.client.mock_user) == 1
231
232
233 async def test_send_message_not_connected(cloud_mock_iot):
234 """Test sending a message that expects no answer."""
235 cloud_iot = MockIoT(cloud_mock_iot)
236
237 with pytest.raises(iot_base.NotConnected):
238 await cloud_iot.async_send_json_message({"msg": "yo"})