Debian Codegraph @

tests/test_utils.py

raw ◀ ▶
1 Debian patch touch this file
1 """Tests for hass_nabucasa utils."""
2
3 from unittest.mock import MagicMock, patch
4
5 from icmplib import Host, ICMPLibError, SocketPermissionError
6 import jwt
7 import pytest
8 from syrupy import SnapshotAssertion
9
10 from hass_nabucasa import utils
11
12
•13 def test_utc_from_timestamp_after_32bit_time_t() -> None:
14 """Test utc_from_timestamp handles timestamps after 2038 on 32-bit platforms."""
15 assert (
16 utils.utc_from_timestamp(9999999999).isoformat()
17 == "2286-11-20T17:46:39+00:00"
18 )
19
20
21 @pytest.mark.parametrize(
22 "input_str",
23 [
24 "2020-02-30",
25 "2019-02-29",
26 "2021-04-31",
27 "2023-06-31",
28 "2018-09-31",
29 "2015-11-31",
30 "2022-02-30",
31 "2020-04-31",
32 "2021-06-31",
33 "2017-09-31",
34 "2019-04-31",
35 "2023-11-31",
36 "2020-06-31",
37 "2016-02-30",
38 "2021-11-31",
39 "invalid",
40 "2023/12/12",
41 ],
42 )
43 def test_parse_date_with_invalid_dates(input_str):
44 """Test the parse_date util."""
45 assert utils.parse_date(input_str) is None
46
47
48 @pytest.mark.parametrize(
49 "input_str",
50 [
51 "2020-02-29",
52 "2019-03-15",
53 "2021-04-30",
54 "2023-06-15",
55 "2018-09-30",
56 "2015-12-25",
57 "2022-02-28",
58 "2020-07-04",
59 "2021-08-21",
60 "2017-10-31",
61 "2019-01-01",
62 "2023-11-30",
63 "2020-05-05",
64 "2016-12-12",
65 "2021-03-14",
66 ],
67 )
68 def test_parse_date_with_valid_dates(input_str):
69 """Test the parse_date util."""
70 assert utils.parse_date(input_str) is not None
71
72
73 def test_expiration_from_token():
74 """Test the expiration_from_token util."""
75 encoded = jwt.encode(
76 {
77 "exp": 1234567890,
78 "iat": 1234567890,
79 "sub": "user_id",
80 },
81 "secret",
82 algorithm="HS256",
83 )
84 assert utils.expiration_from_token(encoded) == 1234567890
85
86
87 def test_expiration_from_token_no_exp():
88 """Test the expiration_from_token util with no exp claim."""
89 encoded = jwt.encode(
90 {
91 "iat": 1234567890,
92 "sub": "user_id",
93 },
94 "secret",
95 algorithm="HS256",
96 )
97 assert utils.expiration_from_token(encoded) is None
98
99
100 def test_expiration_from_token_no_token():
101 """Test the expiration_from_token util with no token."""
102 assert utils.expiration_from_token(None) is None
103
104
105 @pytest.mark.parametrize(
106 "seconds,expected",
107 [
108 (0, "0s"),
109 (30, "30s"),
110 (59, "59s"),
111 (60, "1m"),
112 (90, "1m:30s"),
113 (125, "2m:5s"),
114 (3600, "1h"),
115 (3661, "1h:1m:1s"),
116 (3725, "1h:2m:5s"),
117 (7384, "2h:3m:4s"),
118 (43289, "12h:1m:29s"),
119 (86400, "1d"),
120 (86400.44, "1d"),
121 (86401, "1d:0h:0m:1s"),
122 (86460, "1d:0h:1m"),
123 (86461, "1d:0h:1m:1s"),
124 (90061, "1d:1h:1m:1s"),
125 (93784, "1d:2h:3m:4s"),
126 (172925, "2d:0h:2m:5s"),
127 (266543, "3d:2h:2m:23s"),
128 ],
129 )
130 def test_seconds_as_dhms(seconds, expected):
131 """Test the seconds_as_dhms util."""
132 assert utils.seconds_as_dhms(seconds) == expected
133
134
135 async def test_async_check_latency_no_addresses():
136 """Test async_check_latency with empty address list raises CheckLatencyError."""
137 with pytest.raises(utils.CheckLatencyError, match="No addresses provided"):
138 await utils.async_check_latency([])
139
140
141 async def test_async_check_latency_with_ip(snapshot: SnapshotAssertion):
142 """Test async_check_latency with an IP address."""
143 mock_host = MagicMock(
144 address="999.999.999.999",
145 is_alive=True,
146 avg_rtt=10.5,
147 max_rtt=15.0,
148 min_rtt=5.0,
149 spec=Host,
150 )
151
152 with patch(
153 "hass_nabucasa.utils.async_multiping",
154 return_value=[mock_host],
155 ):
156 result = await utils.async_check_latency(["999.999.999.999"])
157
158 assert result == snapshot
159
160
161 async def test_async_check_latency_multiple_addresses(snapshot: SnapshotAssertion):
162 """Test async_check_latency with multiple addresses sorted by latency."""
163 mock_host1 = MagicMock(
164 address="1.1.1.1",
165 is_alive=True,
166 avg_rtt=20.0,
167 max_rtt=25.0,
168 min_rtt=15.0,
169 spec=Host,
170 )
171 mock_host2 = MagicMock(
172 address="999.999.999.999",
173 is_alive=True,
174 avg_rtt=10.0,
175 max_rtt=15.0,
176 min_rtt=5.0,
177 spec=Host,
178 )
179 mock_host3 = MagicMock(
180 address="9.9.9.9",
181 is_alive=True,
182 avg_rtt=15.0,
183 max_rtt=20.0,
184 min_rtt=10.0,
185 spec=Host,
186 )
187
188 with patch(
189 "hass_nabucasa.utils.async_multiping",
190 return_value=[mock_host1, mock_host2, mock_host3],
191 ):
192 result = await utils.async_check_latency(
193 ["1.1.1.1", "999.999.999.999", "9.9.9.9"]
194 )
195
196 # Should be sorted by avg_rtt (fastest first)
197 assert sorted(result, key=lambda x: x["avg_rtt"]) == snapshot
198
199
200 async def test_async_check_latency_partial_unreachable(snapshot: SnapshotAssertion):
201 """Test async_check_latency when some hosts are unreachable."""
202 mock_host1 = MagicMock(
203 address="1.1.1.1",
204 is_alive=True,
205 avg_rtt=20.0,
206 max_rtt=25.0,
207 min_rtt=15.0,
208 spec=Host,
209 )
210 mock_host2 = MagicMock(
211 address="999.999.999.999",
212 is_alive=False,
213 avg_rtt=0.0,
214 max_rtt=0.0,
215 min_rtt=0.0,
216 spec=Host,
217 )
218 mock_host3 = MagicMock(
219 address="9.9.9.9",
220 is_alive=True,
221 avg_rtt=15.0,
222 max_rtt=20.0,
223 min_rtt=10.0,
224 spec=Host,
225 )
226
227 with patch(
228 "hass_nabucasa.utils.async_multiping",
229 return_value=[mock_host1, mock_host2, mock_host3],
230 ):
231 result = await utils.async_check_latency(
232 ["1.1.1.1", "999.999.999.999", "9.9.9.9"]
233 )
234
235 # Result should match the snapshot when some hosts are unreachable
236 assert result == snapshot
237
238
239 async def test_async_check_latency_socket_permission_error_retries():
240 """Test async_check_latency.
241
242 retries with privileged=False on SocketPermissionError.
243 """
244 mock_host = MagicMock(
245 address="999.999.999.999",
246 is_alive=True,
247 avg_rtt=10.5,
248 max_rtt=15.0,
249 min_rtt=5.0,
250 spec=Host,
251 )
252
253 with patch(
254 "hass_nabucasa.utils.async_multiping",
255 side_effect=[SocketPermissionError(privileged=True), [mock_host]],
256 ) as mock_multiping:
257 result = await utils.async_check_latency(["999.999.999.999"])
258
259 assert mock_multiping.call_count == 2
260 assert mock_multiping.call_args_list[0][1]["privileged"] is True
261 assert mock_multiping.call_args_list[1][1]["privileged"] is False
262 assert len(result) == 1
263 assert result[0]["address"] == "999.999.999.999"
264
265
266 async def test_async_check_latency_socket_permission_error_unprivileged():
267 """Test async_check_latency.
268
269 raises CheckLatencyInsufficientPrivileges when privileged=False.
270 """
271 with (
272 patch(
273 "hass_nabucasa.utils.async_multiping",
274 side_effect=SocketPermissionError(privileged=True),
275 ),
276 pytest.raises(utils.CheckLatencyInsufficientPrivileges),
277 ):
278 await utils.async_check_latency(["999.999.999.999"], privileged=False)
279
280
281 async def test_async_check_latency_socket_permission_error_retry_also_fails():
282 """Test async_check_latency.
283
284 raises CheckLatencyInsufficientPrivileges when retry also fails.
285 """
286 with (
287 patch(
288 "hass_nabucasa.utils.async_multiping",
289 side_effect=SocketPermissionError(privileged=True),
290 ),
291 pytest.raises(utils.CheckLatencyInsufficientPrivileges),
292 ):
293 await utils.async_check_latency(["999.999.999.999"])
294
295
296 async def test_async_check_latency_icmp_error():
297 """Test async_check_latency when ICMP ping fails raises CheckLatencyError."""
298 with (
299 patch(
300 "hass_nabucasa.utils.async_multiping",
301 side_effect=ICMPLibError("ICMP error"),
302 ),
303 pytest.raises(utils.CheckLatencyError, match="ICMP ping failed"),
304 ):
305 await utils.async_check_latency(["999.999.999.999"])
306
307
308 async def test_async_check_latency_all_unreachable():
309 """Test async_check_latency when all hosts are unreachable."""
310 mocked_results = [
311 MagicMock(
312 address="999.999.999.999",
313 is_alive=False,
314 avg_rtt=0.0,
315 max_rtt=0.0,
316 min_rtt=0.0,
317 spec=Host,
318 ),
319 MagicMock(
320 address="1.1.1.1",
321 is_alive=False,
322 avg_rtt=0.0,
323 max_rtt=0.0,
324 min_rtt=0.0,
325 spec=Host,
326 ),
327 ]
328
329 with (
330 patch(
331 "hass_nabucasa.utils.async_multiping",
332 return_value=mocked_results,
333 ),
334 ):
335 result = await utils.async_check_latency(["1.1.1.1", "999.999.999.999"])
336
337 assert len(result) == 2
338 assert not any(host["is_alive"] for host in result)