Debian Codegraph @

tests/test_api.py

raw
1 """Test the base API module."""
2
3 from __future__ import annotations
4
5 import logging
6 from typing import TYPE_CHECKING
7 from unittest.mock import Mock, patch
8
9 import pytest
10 import voluptuous as vol
11
12 from hass_nabucasa.api import (
13 ALLOW_EMPTY_RESPONSE,
14 ApiBase,
15 CloudApiError,
16 CloudApiInvalidResponseError,
17 CloudApiNonRetryableError,
18 CloudApiRawResponse,
19 api_exception_handler,
20 )
21
22 if TYPE_CHECKING:
23 from hass_nabucasa import Cloud
24 from tests.utils.aiohttp import AiohttpClientMocker
25
26
27 class CustomException(CloudApiError):
28 """Custom exception for testing."""
29
30
31 @pytest.fixture(autouse=True)
32 def add_test_api_action_to_service_discovery():
33 """Add test_api_action for this module's tests."""
34 with (
35 patch(
36 "hass_nabucasa.service_discovery.VALID_ACTION_NAMES",
37 frozenset(["test_api_action"]),
38 ),
39 patch(
40 "hass_nabucasa.service_discovery.ServiceDiscovery._get_service_action_url",
41 return_value="https://example.com/test/{param}/action",
42 ),
43 ):
44 yield
45
46
47 @pytest.mark.parametrize(
48 "exception,expected",
49 [
50 (CloudApiError("Oh no!"), CloudApiError),
51 (CloudApiNonRetryableError("Oh no!", code="616"), CloudApiNonRetryableError),
52 (CustomException("Oh no!"), CustomException),
53 (KeyError("stt"), CustomException),
54 ],
55 )
56 async def test_raising_exception(exception, expected) -> None:
57 """Test raising a custom exception."""
58
59 @api_exception_handler(CustomException)
60 async def mock_func() -> None:
61 raise exception
62
63 with pytest.raises(expected):
64 await mock_func()
65
66
67 class AwesomeApiClass(ApiBase):
68 """Test API implementation."""
69
70 @property
71 def hostname(self) -> str:
72 """Get the hostname."""
73 return "example.com"
74
75
76 @pytest.mark.parametrize(
77 "method",
78 ALLOW_EMPTY_RESPONSE,
79 )
80 async def test_empty_response_handling_allowed_methods(
81 aioclient_mock: AiohttpClientMocker,
82 cloud: Cloud,
83 method: str,
84 ) -> None:
85 """Test empty response handling for methods that allow empty responses."""
86 test_api = AwesomeApiClass(cloud)
87
88 aioclient_mock.request(
89 method.lower(),
90 "https://example.com/test",
91 text="",
92 status=200,
93 )
94
95 result = await test_api._call_cloud_api(
96 path="/test",
97 method=method,
98 skip_token_check=True,
99 )
100 assert result is None
101
102
103 @pytest.mark.parametrize(
104 "method",
105 ["GET", "PUT", "PATCH", "OPTIONS"],
106 )
107 async def test_empty_response_handling_disallowed_methods(
108 aioclient_mock: AiohttpClientMocker,
109 cloud: Cloud,
110 method: str,
111 ) -> None:
112 """Test empty response handling for methods that disallow empty responses."""
113 test_api = AwesomeApiClass(cloud)
114
115 aioclient_mock.request(
116 method.lower(),
117 "https://example.com/test",
118 text="",
119 status=200,
120 )
121
122 with pytest.raises(CloudApiError, match="Failed to parse API response"):
123 await test_api._call_cloud_api(
124 path="/test",
125 method=method,
126 skip_token_check=True,
127 )
128
129
130 async def test_pre_request_log_handler_debug_enabled(
131 aioclient_mock: AiohttpClientMocker,
132 cloud: Cloud,
133 caplog: pytest.LogCaptureFixture,
134 ) -> None:
135 """Test pre-request log handler when DEBUG logging is enabled."""
136 test_api = AwesomeApiClass(cloud)
137
138 aioclient_mock.get(
139 "https://example.com/test",
140 json={"result": "success"},
141 status=200,
142 )
143
144 with caplog.at_level(logging.DEBUG, logger="hass_nabucasa.api"):
145 await test_api._call_cloud_api(
146 path="/test",
147 method="GET",
148 skip_token_check=True,
149 )
150
151 assert "Sending GET request to example.com/test" in caplog.text
152
153
154 async def test_pre_request_log_handler_debug_disabled(
155 aioclient_mock: AiohttpClientMocker,
156 cloud: Cloud,
157 caplog: pytest.LogCaptureFixture,
158 ) -> None:
159 """Test pre-request log handler when DEBUG logging is disabled."""
160 test_api = AwesomeApiClass(cloud)
161
162 aioclient_mock.get(
163 "https://example.com/test",
164 json={"result": "success"},
165 status=200,
166 )
167
168 with caplog.at_level(logging.INFO, logger="hass_nabucasa.api"):
169 await test_api._call_cloud_api(
170 path="/test",
171 method="GET",
172 skip_token_check=True,
173 )
174
175 assert "Sending GET request to example.com/test" not in caplog.text
176
177
178 async def test_pre_request_log_handler_with_external_hostname(
179 aioclient_mock: AiohttpClientMocker,
180 cloud: Cloud,
181 caplog: pytest.LogCaptureFixture,
182 ) -> None:
183 """Test pre-request log handler with external hostname (should not show path)."""
184 test_api = AwesomeApiClass(cloud)
185
186 aioclient_mock.get(
187 "https://external.com/test",
188 json={"result": "success"},
189 status=200,
190 )
191
192 with caplog.at_level(logging.DEBUG, logger="hass_nabucasa.api"):
193 await test_api._call_raw_api(
194 method="GET",
195 url="https://external.com/test",
196 client_timeout=Mock(),
197 headers={},
198 )
199
200 assert "Sending GET request to external.com" in caplog.text
201
202
203 async def test_raw_response_success(
204 aioclient_mock: AiohttpClientMocker,
205 cloud: Cloud,
206 ) -> None:
207 """Test raw_response parameter returns CloudApiRawResponse."""
208 test_api = AwesomeApiClass(cloud)
209
210 aioclient_mock.get(
211 "https://example.com/test",
212 json={"result": "success"},
213 status=200,
214 )
215
216 result = await test_api._call_cloud_api(
217 path="/test",
218 method="GET",
219 raw_response=True,
220 )
221
222 assert isinstance(result, CloudApiRawResponse)
223 assert result.data == {"result": "success"}
224 assert result.response.status == 200
225
226
227 async def test_raw_response_error_handling(
228 aioclient_mock: AiohttpClientMocker,
229 cloud: Cloud,
230 ) -> None:
231 """Test raw_response parameter with error status codes."""
232 test_api = AwesomeApiClass(cloud)
233
234 aioclient_mock.get(
235 "https://example.com/test",
236 json={"error": "Not found"},
237 status=404,
238 )
239
240 result = await test_api._call_cloud_api(
241 path="/test",
242 method="GET",
243 raw_response=True,
244 )
245
246 assert isinstance(result, CloudApiRawResponse)
247 assert result.data == {"error": "Not found"}
248 assert result.response.status == 404
249
250
251 async def test_raw_response_with_empty_data(
252 aioclient_mock: AiohttpClientMocker,
253 cloud: Cloud,
254 ) -> None:
255 """Test raw_response parameter with empty response data."""
256 test_api = AwesomeApiClass(cloud)
257
258 aioclient_mock.post(
259 "https://example.com/test",
260 text="",
261 status=200,
262 )
263
264 result = await test_api._call_cloud_api(
265 path="/test",
266 method="POST",
267 raw_response=True,
268 )
269
270 assert isinstance(result, CloudApiRawResponse)
271 assert result.data is None
272 assert result.response.status == 200
273
274
275 async def test_raw_response_with_json_data(
276 aioclient_mock: AiohttpClientMocker,
277 cloud: Cloud,
278 ) -> None:
279 """Test raw_response parameter with JSON response data."""
280 test_api = AwesomeApiClass(cloud)
281
282 test_data = {"message": "Hello", "count": 42}
283 aioclient_mock.put(
284 "https://example.com/test",
285 json=test_data,
286 status=201,
287 )
288
289 result = await test_api._call_cloud_api(
290 path="/test",
291 method="PUT",
292 raw_response=True,
293 )
294
295 assert isinstance(result, CloudApiRawResponse)
296 assert result.data == test_data
297 assert result.response.status == 201
298
299
300 @pytest.mark.parametrize(
301 "params,query_string,params_in_log",
302 [
303 [{"param": "value"}, "param=value", "param=***"],
304 [
305 {"param": "value", "param2": "value2"},
306 "param=value&param2=value2",
307 "param=***&param2=***",
308 ],
309 [{"param": "True"}, "param=True", "param=True"],
310 [{"param": "false"}, "param=false", "param=false"],
311 [
312 {"param": "value", "param2": "true", "param3": "value3", "param4": "false"},
313 "param=value&param2=true&param3=value3&param4=false",
314 "param=***&param2=true&param3=***&param4=false",
315 ],
316 ],
317 )
318 async def test_raw_response_with_params(
319 aioclient_mock: AiohttpClientMocker,
320 cloud: Cloud,
321 params: dict,
322 query_string: str,
323 params_in_log: str,
324 caplog: pytest.LogCaptureFixture,
325 ) -> None:
326 """Test raw_response parameter with JSON response data."""
327 test_api = AwesomeApiClass(cloud)
328
329 test_data = {"message": "Hello", "count": 42}
330 aioclient_mock.get(
331 f"https://example.com/test?{query_string}",
332 json=test_data,
333 status=200,
334 )
335
336 result = await test_api._call_cloud_api(
337 path="/test",
338 method="GET",
339 raw_response=True,
340 params=params,
341 )
342
343 assert isinstance(result, CloudApiRawResponse)
344 assert result.data == test_data
345 assert result.response.status == 200
346 assert (
347 f"Response for get from example.com/test?{params_in_log} (200)" in caplog.text
348 )
349
350
351 def test_cloud_api_raw_response_dataclass():
352 """Test CloudApiRawResponse dataclass structure."""
353 mock_response = Mock()
354 mock_response.status = 200
355 test_data = {"test": "data"}
356
357 raw_response = CloudApiRawResponse(response=mock_response, data=test_data)
358
359 assert raw_response.response == mock_response
360 assert raw_response.data == test_data
361 assert raw_response.response.status == 200
362
363
364 def test_cloud_api_raw_response_dataclass_default_data():
365 """Test CloudApiRawResponse dataclass with default data."""
366 mock_response = Mock()
367 mock_response.status = 204
368
369 raw_response = CloudApiRawResponse(response=mock_response)
370
371 assert raw_response.response == mock_response
372 assert raw_response.data is None
373 assert raw_response.response.status == 204
374
375
376 async def test_call_cloud_api_with_action_parameter(
377 aioclient_mock: AiohttpClientMocker,
378 cloud: Cloud,
379 ) -> None:
380 """Test _call_cloud_api with action parameter."""
381 test_api = AwesomeApiClass(cloud)
382
383 aioclient_mock.get(
384 "https://example.com/test/value/action",
385 json={"result": "success"},
386 status=200,
387 )
388
389 result = await test_api._call_cloud_api(
390 action="test_api_action",
391 action_values={"param": "value"},
392 method="GET",
393 )
394
395 assert result == {"result": "success"}
396
397
398 async def test_call_cloud_api_with_path_parameter(
399 aioclient_mock: AiohttpClientMocker,
400 cloud: Cloud,
401 ) -> None:
402 """Test _call_cloud_api with path parameter."""
403 test_api = AwesomeApiClass(cloud)
404
405 aioclient_mock.get(
406 "https://example.com/test",
407 json={"result": "success"},
408 status=200,
409 )
410
411 result = await test_api._call_cloud_api(
412 path="/test",
413 method="GET",
414 )
415
416 assert result == {"result": "success"}
417
418
419 async def test_call_cloud_api_action_takes_precedence_over_path(
420 aioclient_mock: AiohttpClientMocker,
421 cloud: Cloud,
422 ) -> None:
423 """Test that action parameter takes precedence over path parameter."""
424 test_api = AwesomeApiClass(cloud)
425
426 aioclient_mock.get(
427 "https://example.com/test/value/action",
428 json={"result": "from action"},
429 status=200,
430 )
431
432 result = await test_api._call_cloud_api(
433 action="test_api_action",
434 action_values={"param": "value"},
435 path="/path-endpoint",
436 method="GET",
437 )
438
439 assert result == {"result": "from action"}
440
441
442 async def test_call_cloud_api_requires_action_or_path(
443 aioclient_mock: AiohttpClientMocker,
444 cloud: Cloud,
445 ) -> None:
446 """Test that _call_cloud_api requires either action or path parameter."""
447 test_api = AwesomeApiClass(cloud)
448
449 with pytest.raises(
450 CloudApiError, match="Either 'action' or 'path' parameter must be provided"
451 ):
452 await test_api._call_cloud_api(method="GET")
453
454
455 async def test_call_cloud_api_with_schema_validation_success(
456 aioclient_mock: AiohttpClientMocker,
457 cloud: Cloud,
458 ) -> None:
459 """Test _call_cloud_api with schema validation (valid data)."""
460 test_api = AwesomeApiClass(cloud)
461
462 test_schema = vol.Schema(
463 {
464 vol.Required("name"): str,
465 vol.Required("count"): int,
466 }
467 )
468
469 aioclient_mock.get(
470 "https://example.com/test",
471 json={"name": "test", "count": 42},
472 status=200,
473 )
474
475 result = await test_api._call_cloud_api(
476 path="/test",
477 method="GET",
478 schema=test_schema,
479 )
480
481 assert result == {"name": "test", "count": 42}
482
483
484 async def test_call_cloud_api_with_schema_validation_failure(
485 aioclient_mock: AiohttpClientMocker,
486 cloud: Cloud,
487 ) -> None:
488 """Test _call_cloud_api with schema validation (invalid data)."""
489 test_api = AwesomeApiClass(cloud)
490
491 test_schema = vol.Schema(
492 {
493 vol.Required("name"): str,
494 vol.Required("count"): int,
495 }
496 )
497
498 aioclient_mock.get(
499 "https://example.com/test",
500 json={"name": "test", "count": "not-a-number"},
501 status=200,
502 )
503
504 with pytest.raises(CloudApiInvalidResponseError, match="Invalid response"):
505 await test_api._call_cloud_api(
506 path="/test",
507 method="GET",
508 schema=test_schema,
509 )
510
511
512 async def test_call_cloud_api_with_schema_validation_missing_field(
513 aioclient_mock: AiohttpClientMocker,
514 cloud: Cloud,
515 ) -> None:
516 """Test _call_cloud_api with schema validation (missing required field)."""
517 test_api = AwesomeApiClass(cloud)
518
519 test_schema = vol.Schema(
520 {
521 vol.Required("name"): str,
522 vol.Required("count"): int,
523 }
524 )
525
526 aioclient_mock.get(
527 "https://example.com/test",
528 json={"name": "test"},
529 status=200,
530 )
531
532 with pytest.raises(CloudApiInvalidResponseError, match="Invalid response"):
533 await test_api._call_cloud_api(
534 path="/test",
535 method="GET",
536 schema=test_schema,
537 )
538
539
540 async def test_call_cloud_api_schema_validation_with_coercion(
541 aioclient_mock: AiohttpClientMocker,
542 cloud: Cloud,
543 ) -> None:
544 """Test _call_cloud_api with schema that coerces data types."""
545 test_api = AwesomeApiClass(cloud)
546
547 test_schema = vol.Schema(
548 {
549 vol.Required("value"): vol.Coerce(int),
550 }
551 )
552
553 aioclient_mock.get(
554 "https://example.com/test",
555 json={"value": "123"},
556 status=200,
557 )
558
559 result = await test_api._call_cloud_api(
560 path="/test",
561 method="GET",
562 schema=test_schema,
563 )
564
565 assert result == {"value": 123}
566
567
568 async def test_action_url_via_service_discovery(
569 aioclient_mock: AiohttpClientMocker,
570 cloud: Cloud,
571 ) -> None:
572 """Test action_url method via service discovery."""
573 url = cloud.service_discovery.action_url("test_api_action", param="value")
574
575 assert isinstance(url, str)
576 assert url == "https://example.com/test/value/action"
577
578
579 async def test_call_cloud_api_with_action_values(
580 aioclient_mock: AiohttpClientMocker,
581 cloud: Cloud,
582 ) -> None:
583 """Test _call_cloud_api with action_values for format parameters."""
584 test_api = AwesomeApiClass(cloud)
585
586 # Use a context manager to override the patched method for this test
587 with patch(
588 "hass_nabucasa.service_discovery.ServiceDiscovery._get_service_action_url",
589 return_value="https://example.com/test/{param}/details",
590 ):
591 aioclient_mock.get(
592 "https://example.com/test/value/details",
593 json={"result": "success"},
594 status=200,
595 )
596
597 result = await test_api._call_cloud_api(
598 action="test_api_action",
599 action_values={"param": "value"},
600 method="GET",
601 )
602
603 assert result == {"result": "success"}
604
605
606 async def test_hostname_property_default(
607 aioclient_mock: AiohttpClientMocker,
608 cloud: Cloud,
609 ) -> None:
610 """Test that hostname property defaults to None."""
611 test_api = ApiBase(cloud)
612
613 assert test_api.hostname is None
614
615
616 async def test_hostname_property_override(
617 aioclient_mock: AiohttpClientMocker,
618 cloud: Cloud,
619 ) -> None:
620 """Test that hostname property can be overridden."""
621 test_api = AwesomeApiClass(cloud)
622
623 assert test_api.hostname == "example.com"