Debian Codegraph @

tests/test_bridge_api.py

raw
1 # Copyright 2023 Simone Chemelli and contributors
2 # SPDX-License-Identifier: Apache-2.0
3
4 """Tests for Comelit serial bridge API."""
5
6 from __future__ import annotations
7
8 import asyncio
9 from datetime import UTC, datetime
10 from http import HTTPStatus
11 from typing import TYPE_CHECKING
12 from unittest.mock import AsyncMock
13
14 import pytest
15
16 from aiocomelit.const import BRIDGE, CLIMATE, COVER, LIGHT, OTHER, SCENARIO
17 from aiocomelit.devices.bridge import ComeliteSerialBridgeApi
18 from aiocomelit.exceptions import (
19 CannotAuthenticate,
20 CannotConnect,
21 CannotRetrieveData,
22 DeviceStorageFailureError,
23 )
24 from tests.conftest import (
25 call_private_async,
26 make_get_page_result_mock,
27 set_private_attr,
28 setup_api,
29 )
30
31 if TYPE_CHECKING:
32 from collections.abc import Awaitable, Callable
33
34 from aiohttp import ClientSession
35
36 SCENARIO_COUNT = 3
37
38 _EMPTY_CLIMA_PAYLOAD: dict[str, object] = {
39 "num": 1,
40 "desc": [],
41 "status": [0],
42 "val": [0],
43 "protected": [0],
44 "env": [0],
45 "env_desc": [""],
46 }
47 _EMPTY_DEVICE_PAYLOAD: dict[str, object] = {
48 "num": 0,
49 "desc": [],
50 "status": [],
51 "val": [],
52 "protected": [],
53 "env": [],
54 "env_desc": [""],
55 }
56
57
58 async def test_bridge_login_delegates_to_common(mock_session: ClientSession) -> None:
59 """Test bridge login delegates to common internal login."""
60 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
61 login_mock = AsyncMock(return_value=True)
62 set_private_attr(api, "_login", login_mock)
63
64 assert await api.login() is True
65 login_mock.assert_awaited_once_with({"dom": "1234"}, BRIDGE)
66
67
68 @pytest.mark.parametrize(
69 ("dev_type", "status", "expected"),
70 [
71 (COVER, 0, "stopped"),
72 (COVER, 1, "opening"),
73 (COVER, 2, "closing"),
74 (LIGHT, 1, "on"),
75 (LIGHT, 0, "off"),
76 ],
77 )
78 async def test_translate_device_status(
79 mock_session: ClientSession,
80 dev_type: str,
81 status: int,
82 expected: str,
83 ) -> None:
84 """Test device status translation for cover and non-cover devices."""
85 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
86 method: Callable[[str, int], Awaitable[str]] = call_private_async(
87 api, "_translate_device_status"
88 )
89 assert await method(dev_type, status) == expected
90
91
92 async def test_set_thermo_humi_status_waits_and_scales(
93 mock_session: ClientSession,
94 ) -> None:
95 """Test thermo/humidity helper queueing and value scaling."""
96 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
97 set_private_attr(api, "_last_clima_command", datetime.now(tz=UTC))
98 sleep_mock = AsyncMock()
99 get_mock = AsyncMock(return_value=(HTTPStatus.OK, {}))
100 set_private_attr(api, "_sleep_between_call", sleep_mock)
101 set_private_attr(api, "_get_page_result", get_mock)
102
103 result = await api.set_clima_status(3, "set", 22.5)
104
105 assert result is True
106 sleep_mock.assert_awaited_once()
107 get_mock.assert_awaited_once()
108 assert get_mock.await_args is not None
109 called_query = get_mock.await_args.kwargs["query"]
110 assert called_query["clima"] == 3
111 assert called_query["thermo"] == "set"
112 assert called_query["val"] == 225
113
114
115 async def test_set_thermo_humi_status_releases_semaphore_on_error(
116 mock_session: ClientSession,
117 ) -> None:
118 """Test the semaphore is released even if the HTTP call raises."""
119 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
120 set_private_attr(api, "_sleep_between_call", AsyncMock())
121 set_private_attr(
122 api, "_get_page_result", AsyncMock(side_effect=CannotConnect("boom"))
123 )
124
125 with pytest.raises(CannotConnect):
126 await api.set_clima_status(1, "set", 20.0)
127
128 set_private_attr(
129 api, "_get_page_result", AsyncMock(return_value=(HTTPStatus.OK, {}))
130 )
131
132 # A short timeout turns a still-held semaphore into a clean failure
133 # instead of an indefinite hang.
134 result = await asyncio.wait_for(api.set_clima_status(1, "set", 21.0), timeout=1)
135
136 assert result is True
137
138
139 async def test_set_clima_and_humidity_wrappers(mock_session: ClientSession) -> None:
140 """Test climate/humidity wrapper methods delegate correctly."""
141 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
142 thermo_humi_mock = AsyncMock(return_value=True)
143 set_private_attr(api, "_set_thermo_humi_status", thermo_humi_mock)
144
145 assert await api.set_clima_status(1, "set", 19.0) is True
146 assert await api.set_humidity_status(2, "set", 61.0) is True
147
148 assert thermo_humi_mock.await_args_list[0].args == (1, "thermo", "set", 19.0)
149 assert thermo_humi_mock.await_args_list[1].args == (2, "humi", "set", 61.0)
150
151
152 @pytest.mark.parametrize(
153 ("action", "expected_key", "expected_value", "status_code", "expected_result"),
154 [
155 (1, "num1", 2, HTTPStatus.OK, True),
156 (0, "num0", 2, HTTPStatus.INTERNAL_SERVER_ERROR, False),
157 ],
158 )
159 async def test_set_device_status(
160 mock_session: ClientSession,
161 action: int,
162 expected_key: str,
163 expected_value: int,
164 status_code: HTTPStatus,
165 expected_result: bool,
166 ) -> None:
167 """Test set_device_status for on/off actions and response handling."""
168 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
169 get_mock = AsyncMock(return_value=(status_code, {}))
170 set_private_attr(api, "_get_page_result", get_mock)
171
172 assert await api.set_device_status(LIGHT, 2, action) is expected_result
173 call_args = get_mock.await_args
174 assert call_args is not None
175 assert call_args.kwargs["query"][expected_key] == expected_value
176
177
178 async def test_get_device_status(mock_session: ClientSession) -> None:
179 """Test reading a single device status index."""
180 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
181 set_private_attr(
182 api,
183 "_get_page_result",
184 AsyncMock(return_value=(HTTPStatus.OK, {"status": [0, 1, 0]})),
185 )
186
187 assert await api.get_device_status(LIGHT, 1) == 1
188
189
190 @pytest.mark.parametrize(
191 ("counter_payload", "expected_power"),
192 [
193 ({"instant": ["1 kW"], "logged": 1}, 1000.0),
194 ({"logged": 1}, 0.0),
195 ],
196 )
197 async def test_get_all_devices_with_real_fixtures(
198 mock_session: ClientSession,
199 fixture_loader: Callable[[str], dict[str, object]],
200 counter_payload: dict[str, object],
201 expected_power: float,
202 ) -> None:
203 """Test full device retrieval and power parsing from fixture payloads."""
204 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
205
206 responses: dict[str, dict[str, object]] = {
207 "user/icon_desc.json?type=clima": fixture_loader("bridge/clima"),
208 "user/icon_desc.json?type=shutter": fixture_loader("bridge/shutter"),
209 "user/icon_desc.json?type=light": fixture_loader("bridge/light"),
210 "user/icon_desc.json?type=irrigation": fixture_loader("bridge/irrigation"),
211 "user/icon_desc.json?type=other": fixture_loader("bridge/other"),
212 "user/icon_desc.json?type=scenario": fixture_loader("bridge/scenario"),
213 "user/counter.json": counter_payload,
214 }
215
216 set_private_attr(
217 api,
218 "_get_page_result",
219 AsyncMock(side_effect=make_get_page_result_mock(responses)),
220 )
221 devices = await api.get_all_devices()
222
223 assert CLIMATE in devices
224 assert SCENARIO in devices
225 assert len(devices[SCENARIO]) == SCENARIO_COUNT
226 assert devices[OTHER][0].power == pytest.approx(expected_power)
227 assert bool(object.__getattribute__(api, "_initialized")) is True
228
229
230 async def test_get_all_devices_empty_payload_raises_storage_error(
231 mock_session: ClientSession,
232 ) -> None:
233 """Test empty payload handling while loading all devices."""
234 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
235 set_private_attr(
236 api, "_get_page_result", AsyncMock(return_value=(HTTPStatus.OK, {}))
237 )
238
239 with pytest.raises(DeviceStorageFailureError):
240 await api.get_all_devices()
241
242
243 async def test_get_all_devices_empty_desc_raises_when_not_initialized(
244 mock_session: ClientSession,
245 ) -> None:
246 """Test empty climate descriptions raise when bridge is not initialized."""
247 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
248 set_private_attr(api, "_initialized", False)
249 set_private_attr(
250 api,
251 "_get_page_result",
252 AsyncMock(
253 side_effect=make_get_page_result_mock(
254 {"user/icon_desc.json?type=clima": _EMPTY_CLIMA_PAYLOAD},
255 default=_EMPTY_DEVICE_PAYLOAD,
256 )
257 ),
258 )
259
260 with pytest.raises(CannotRetrieveData):
261 await api.get_all_devices()
262
263
264 async def test_get_all_devices_empty_desc_skips_climate_when_initialized(
265 mock_session: ClientSession,
266 ) -> None:
267 """Test empty climate descriptions are skipped once bridge is initialized."""
268 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
269 set_private_attr(api, "_initialized", True)
270 set_private_attr(
271 api,
272 "_get_page_result",
273 AsyncMock(
274 side_effect=make_get_page_result_mock(
275 {"user/icon_desc.json?type=clima": _EMPTY_CLIMA_PAYLOAD},
276 default=_EMPTY_DEVICE_PAYLOAD,
277 )
278 ),
279 )
280
281 devices = await api.get_all_devices()
282 assert CLIMATE not in devices
283
284
285 @pytest.mark.parametrize(
286 ("vedo_pin", "login_side_effect", "get_side_effect", "expected"),
287 [
288 ("1234", None, (HTTPStatus.OK, {"present": [1]}), True),
289 ("9999", None, (HTTPStatus.OK, {"present": [1]}), True),
290 ("9999", CannotAuthenticate(), (HTTPStatus.OK, {"present": [1]}), False),
291 ("1234", None, CannotRetrieveData(), False),
292 ],
293 )
294 async def test_vedo_enabled_paths(
295 mock_session: ClientSession,
296 vedo_pin: str,
297 login_side_effect: Exception | None,
298 get_side_effect: tuple[int, dict[str, object]] | Exception,
299 expected: bool,
300 ) -> None:
301 """Test VEDO feature availability checks for success and failure cases."""
302 api = setup_api(ComeliteSerialBridgeApi, "127.0.0.1", 80, "1234", mock_session)
303
304 login_mock = AsyncMock(return_value=True)
305 if login_side_effect is not None:
306 login_mock = AsyncMock(side_effect=login_side_effect)
307 set_private_attr(api, "_login", login_mock)
308
309 if isinstance(get_side_effect, Exception):
310 set_private_attr(
311 api,
312 "_get_page_result",
313 AsyncMock(side_effect=get_side_effect),
314 )
315 else:
316 set_private_attr(
317 api,
318 "_get_page_result",
319 AsyncMock(return_value=get_side_effect),
320 )
321
322 assert await api.vedo_enabled(vedo_pin) is expected
323
324 if vedo_pin == "9999" and login_side_effect is None:
325 login_mock.assert_awaited_once_with({"alm": "9999"}, "Vedo system")