Debian Codegraph @

tests/test_instance_api.py

raw
1 """Tests for Instance API."""
2
3 import re
4 from typing import Any
5
6 from aiohttp import ClientError
7 import pytest
8 from syrupy import SnapshotAssertion
9
10 from hass_nabucasa import Cloud
11 from hass_nabucasa.instance_api import (
12 InstanceApiError,
13 )
14 from tests.common import extract_log_messages
15 from tests.utils.aiohttp import AiohttpClientMocker
16
17 API_HOSTNAME = "example.com"
18
19
20 @pytest.mark.parametrize(
21 "exception,mockargs,exception_msg",
22 [
23 [
24 InstanceApiError,
25 {"status": 500, "text": "Internal Server Error"},
26 "Failed to parse API response",
27 ],
28 [
29 InstanceApiError,
30 {"status": 429, "text": "Too fast"},
31 "Failed to parse API response",
32 ],
33 [
34 InstanceApiError,
35 {"exc": TimeoutError()},
36 "Timeout reached while calling API",
37 ],
38 [
39 InstanceApiError,
40 {"exc": ClientError("boom!")},
41 "Failed to fetch: boom!",
42 ],
43 [
44 InstanceApiError,
45 {"exc": Exception("boom!")},
46 "Unexpected error while calling API: boom!",
47 ],
48 ],
49 ids=["500-error", "429-error", "timeout", "client-error", "unexpected-error"],
50 )
51 async def test_connection_endpoint_problems(
52 aioclient_mock: AiohttpClientMocker,
53 cloud: Cloud,
54 exception: Exception,
55 mockargs: dict[str, Any],
56 snapshot: SnapshotAssertion,
57 exception_msg: str,
58 caplog: pytest.LogCaptureFixture,
59 ):
60 """Test problems with connection endpoint."""
61 aioclient_mock.get(
62 f"https://{cloud.api_server}/instance/connection",
63 **mockargs,
64 )
65
66 with pytest.raises(exception, match=re.escape(exception_msg)):
67 await cloud.instance.connection()
68
69 assert snapshot == extract_log_messages(caplog)
70
71
72 @pytest.mark.parametrize(
73 "exception,mockargs,exception_msg",
74 [
75 [
76 InstanceApiError,
77 {"status": 500, "text": "Internal Server Error"},
78 "Failed to fetch: (500) ",
79 ],
80 [
81 InstanceApiError,
82 {"status": 429, "text": "Too fast"},
83 "Failed to fetch: (429) ",
84 ],
85 [
86 InstanceApiError,
87 {"exc": TimeoutError()},
88 "Timeout reached while calling API",
89 ],
90 [
91 InstanceApiError,
92 {"exc": ClientError("boom!")},
93 "Failed to fetch: boom!",
94 ],
95 [
96 InstanceApiError,
97 {"exc": Exception("boom!")},
98 "Unexpected error while calling API: boom!",
99 ],
100 ],
101 ids=["500-error", "429-error", "timeout", "client-error", "unexpected-error"],
102 )
103 async def test_cleanup_dns_challenge_record_endpoint_problems(
104 aioclient_mock: AiohttpClientMocker,
105 cloud: Cloud,
106 exception: Exception,
107 mockargs: dict[str, Any],
108 snapshot: SnapshotAssertion,
109 exception_msg: str,
110 caplog: pytest.LogCaptureFixture,
111 ):
112 """Test problems with cleanup_dns_challenge_record endpoint."""
113 aioclient_mock.post(
114 f"https://{cloud.api_server}/instance/dns_challenge_cleanup",
115 **mockargs,
116 )
117
118 with pytest.raises(exception, match=re.escape(exception_msg)):
119 await cloud.instance.cleanup_dns_challenge_record(value="challenge-value")
120
121 assert snapshot == extract_log_messages(caplog)
122
123
124 @pytest.mark.parametrize(
125 "exception,mockargs,exception_msg",
126 [
127 [
128 InstanceApiError,
129 {"status": 500, "text": "Internal Server Error"},
130 "Failed to fetch: (500) ",
131 ],
132 [
133 InstanceApiError,
134 {"status": 429, "text": "Too fast"},
135 "Failed to fetch: (429) ",
136 ],
137 [
138 InstanceApiError,
139 {"exc": TimeoutError()},
140 "Timeout reached while calling API",
141 ],
142 [
143 InstanceApiError,
144 {"exc": ClientError("boom!")},
145 "Failed to fetch: boom!",
146 ],
147 [
148 InstanceApiError,
149 {"exc": Exception("boom!")},
150 "Unexpected error while calling API: boom!",
151 ],
152 ],
153 ids=["500-error", "429-error", "timeout", "client-error", "unexpected-error"],
154 )
155 async def test_create_dns_challenge_record_endpoint_problems(
156 aioclient_mock: AiohttpClientMocker,
157 cloud: Cloud,
158 exception: Exception,
159 mockargs: dict[str, Any],
160 snapshot: SnapshotAssertion,
161 exception_msg: str,
162 caplog: pytest.LogCaptureFixture,
163 ):
164 """Test problems with create_dns_challenge_record endpoint."""
165 aioclient_mock.post(
166 f"https://{cloud.api_server}/instance/dns_challenge_txt",
167 **mockargs,
168 )
169
170 with pytest.raises(exception, match=re.escape(exception_msg)):
171 await cloud.instance.create_dns_challenge_record(value="challenge-value")
172
173 assert snapshot == extract_log_messages(caplog)
174
175
176 async def test_connection_endpoint_success(
177 aioclient_mock: AiohttpClientMocker,
178 cloud: Cloud,
179 caplog: pytest.LogCaptureFixture,
180 snapshot: SnapshotAssertion,
181 ):
182 """Test successful connection endpoint."""
183 expected_result = {"connected": True, "details": {}}
184
185 aioclient_mock.get(
186 f"https://{cloud.api_server}/instance/connection",
187 json=expected_result,
188 )
189
190 result = await cloud.instance.connection()
191
192 assert result == expected_result
193 assert snapshot == extract_log_messages(caplog)
194
195
196 async def test_cleanup_dns_challenge_record_endpoint_success(
197 aioclient_mock: AiohttpClientMocker,
198 cloud: Cloud,
199 caplog: pytest.LogCaptureFixture,
200 snapshot: SnapshotAssertion,
201 ):
202 """Test successful cleanup_dns_challenge_record endpoint."""
203 aioclient_mock.post(
204 f"https://{cloud.api_server}/instance/dns_challenge_cleanup",
205 json={},
206 )
207
208 result = await cloud.instance.cleanup_dns_challenge_record(value="challenge-value")
209
210 assert result is None
211 assert snapshot == extract_log_messages(caplog)
212
213
214 async def test_create_dns_challenge_record_endpoint_success(
215 aioclient_mock: AiohttpClientMocker,
216 cloud: Cloud,
217 caplog: pytest.LogCaptureFixture,
218 snapshot: SnapshotAssertion,
219 ):
220 """Test successful create_dns_challenge_record endpoint."""
221 aioclient_mock.post(
222 f"https://{cloud.api_server}/instance/dns_challenge_txt",
223 json={},
224 )
225
226 result = await cloud.instance.create_dns_challenge_record(value="challenge-value")
227
228 assert result is None
229 assert snapshot == extract_log_messages(caplog)
230
231
232 async def test_ping_targets_endpoint_success(
233 aioclient_mock: AiohttpClientMocker,
234 cloud: Cloud,
235 caplog: pytest.LogCaptureFixture,
236 snapshot: SnapshotAssertion,
237 ):
238 """Test successful ping_targets endpoint."""
239 expected_result = {
240 "targets": [
241 {"ip": "1.2.3.4", "location": "us-east"},
242 {"ip": "5.6.7.8", "location": "eu-west"},
243 ],
244 "timeout": 3000,
245 "count": 2,
246 }
247
248 aioclient_mock.get(
249 f"https://{cloud.api_server}/instance/remote_ping_targets",
250 json=expected_result,
251 )
252
253 result = await cloud.instance.ping_targets()
254
255 assert result == expected_result
256 assert snapshot == extract_log_messages(caplog)
257
258
259 @pytest.mark.parametrize(
260 "exception,mockargs,exception_msg",
261 [
262 [
263 InstanceApiError,
264 {"status": 500, "text": "Internal Server Error"},
265 "Failed to parse API response",
266 ],
267 [
268 InstanceApiError,
269 {"exc": TimeoutError()},
270 "Timeout reached while calling API",
271 ],
272 [
273 InstanceApiError,
274 {"exc": ClientError("boom!")},
275 "Failed to fetch: boom!",
276 ],
277 ],
278 ids=["500-error", "timeout", "client-error"],
279 )
280 async def test_ping_targets_endpoint_problems(
281 aioclient_mock: AiohttpClientMocker,
282 cloud: Cloud,
283 exception: Exception,
284 mockargs: dict[str, Any],
285 snapshot: SnapshotAssertion,
286 exception_msg: str,
287 caplog: pytest.LogCaptureFixture,
288 ):
289 """Test problems with ping_targets endpoint."""
290 aioclient_mock.get(
291 f"https://{cloud.api_server}/instance/remote_ping_targets",
292 **mockargs,
293 )
294
295 with pytest.raises(exception, match=re.escape(exception_msg)):
296 await cloud.instance.ping_targets()
297
298 assert snapshot == extract_log_messages(caplog)
299
300
301 async def test_register_with_ping_result(
302 aioclient_mock: AiohttpClientMocker,
303 cloud: Cloud,
304 ):
305 """Test register endpoint with ping_result."""
306 aioclient_mock.post(
307 f"https://{cloud.api_server}/instance/register",
308 json={
309 "domain": "test.dui.nabu.casa",
310 "email": "[email protected]",
311 "server": "rest-remote.nabu.casa",
312 },
313 )
314
315 ping_result = [
316 {"ip": "1.2.3.4", "avg": 10.5},
317 {"ip": "5.6.7.8", "avg": 20.3},
318 ]
319
320 result = await cloud.instance.register(ping_result=ping_result)
321
322 assert result["domain"] == "test.dui.nabu.casa"
323 assert result["server"] == "rest-remote.nabu.casa"
324
325 # Verify the request body contained ping_result
326 register_calls = [
327 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
328 ]
329 assert len(register_calls) == 1
330 assert register_calls[0][2] == {"ping_result": ping_result}
331
332
333 async def test_register_without_ping_result(
334 aioclient_mock: AiohttpClientMocker,
335 cloud: Cloud,
336 ):
337 """Test register endpoint without ping_result (backward compatible)."""
338 aioclient_mock.post(
339 f"https://{cloud.api_server}/instance/register",
340 json={
341 "domain": "test.dui.nabu.casa",
342 "email": "[email protected]",
343 "server": "rest-remote.nabu.casa",
344 },
345 )
346
347 result = await cloud.instance.register()
348
349 assert result["domain"] == "test.dui.nabu.casa"
350
351 # Verify no jsondata was sent
352 register_calls = [
353 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
354 ]
355 assert len(register_calls) == 1
356 assert register_calls[0][2] is None