Debian Codegraph @

tests/test_utils.py

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