Debian Codegraph @

tests/test_sensor.py

raw symbols SCIP
1 """Blebox sensors tests."""
2
3 import json
4 import pytest
5
6 from blebox_uniapi.box_types import get_latest_api_level
7 from .conftest import CommonEntity, DefaultBoxTest, future_date, jmerge
8
9 TEMP_CELSIUS = "celsius"
10 DEVICE_CLASS_TEMPERATURE = "temperature class"
11
12
13 class BleBoxSensorEntity(CommonEntity):
14 """Home Assistant representation style of a BleBox sensor feature."""
15
16 @property
17 def state(self):
18 """Return the temperature."""
19 return self._feature.current
20
21 @property
22 def unit_of_measurement(self):
23 """Return the temperature unit."""
24 return {"celsius": TEMP_CELSIUS}[self._feature.unit]
25
26 @property
27 def device_class(self):
28 """Return the device class."""
29 types = {"temperature": DEVICE_CLASS_TEMPERATURE}
30 return types[self._feature.device_class]
31
32 @property
33 def native_value(self):
34 """Return the state."""
35 return self._feature.native_value
36
37
38 class TestTempSensor(DefaultBoxTest):
39 """Tests for sensors representing BleBox tempSensor."""
40
41 DEVCLASS = "sensors"
42 ENTITY_CLASS = BleBoxSensorEntity
43
44 DEV_INFO_PATH = "api/tempsensor/state"
45
46 DEVICE_INFO = json.loads(
47 """
48 {
49 "device": {
50 "deviceName": "My tempSensor",
51 "type": "tempSensor",
52 "fv": "0.176",
53 "hv": "0.6",
54 "apiLevel": "20180604",
55 "id": "1afe34db9437",
56 "ip": "172.100.123.4"
57 }
58 }
59 """
60 )
61
62 def patch_version(apiLevel):
63 """Generate a patch for a JSON state fixture."""
64 return f"""
65 {{ "device": {{ "apiLevel": {apiLevel} }} }}
66 """
67
68 DEVICE_INFO_FUTURE = jmerge(DEVICE_INFO, patch_version(future_date()))
69 DEVICE_INFO_LATEST = jmerge(
70 DEVICE_INFO, patch_version(get_latest_api_level("tempSensor"))
71 )
72 DEVICE_INFO_UNSUPPORTED = jmerge(DEVICE_INFO, patch_version(20180603))
73
74 DEVICE_INFO_UNSPECIFIED_API = json.loads(
75 """
76 {
77 "device": {
78 "deviceName": "My tempSensor",
79 "type": "tempSensor",
80 "fv": "0.176",
81 "hv": "0.6",
82 "id": "1afe34db9437",
83 "ip": "172.100.123.4"
84 }
85 }
86 """
87 )
88
89 STATE_DEFAULT = json.loads(
90 """
91 {
92 "tempSensor": {
93 "sensors": [
94 {
95 "type": "temperature",
96 "id": 0,
97 "value": 2518,
98 "trend": 3,
99 "state": 2,
100 "elapsedTimeS": 0
101 }
102 ]
103 }
104 }
105 """
106 )
107
108 DEVICE_EXTENDED_INFO_RAIN_AIR_TEMP = {}
109
110 DEVICE_MULTISENSOR = json.loads(
111 """
112 {
113 "multiSensor":
114 {
115 "sensors":
116 [
117 {
118 "type": "temperature",
119 "id": 0,
120 "name": "Temperature outside",
121 "iconSet": 2,
122 "value": 3606,
123 "trend": 2,
124 "state": 2,
125 "elapsedTimeS": -1
126 },
127 {
128 "type": "temperature",
129 "id": 1,
130 "name": "Temperature inside fence",
131 "iconSet": 3,
132 "value": 4712,
133 "trend": 3,
134 "state": 2,
135 "elapsedTimeS": -1
136 },
137 {
138 "type": "temperature",
139 "id": 2,
140 "name": "Underground -10 cm",
141 "iconSet": 2,
142 "value": 2050,
143 "trend": 3,
144 "state": 2,
145 "elapsedTimeS": -1
146 }
147 ]
148 }
149 }"""
150 )
151
152 DEVICE_MULTISENSOR_UPDATE = json.loads(
153 """
154 {
155 "multiSensor":
156 {
157 "sensors":
158 [
159 {
160 "type": "temperature",
161 "id": 0,
162 "name": "Temperature outside",
163 "iconSet": 2,
164 "value": 123,
165 "trend": 2,
166 "state": 2,
167 "elapsedTimeS": -1
168 },
169 {
170 "type": "temperature",
171 "id": 1,
172 "name": "Temperature inside fence",
173 "iconSet": 3,
174 "value": 213,
175 "trend": 3,
176 "state": 2,
177 "elapsedTimeS": -1
178 },
179 {
180 "type": "temperature",
181 "id": 2,
182 "name": "Underground -10 cm",
183 "iconSet": 2,
184 "value": 312,
185 "trend": 3,
186 "state": 2,
187 "elapsedTimeS": -1
188 }
189 ]
190 }
191 }"""
192 )
193 DEVICE_EXTENDED_INFO = DEVICE_MULTISENSOR
194 DEVICE_EXTENDED_INFO_PATH = "/state/extended"
195
196 DEVICE_INFO_MULTISENSOR = json.loads(
197 """
198 {
199 "device":
200 {
201 "deviceName": "Backyard - tempSensor PRO",
202 "type": "multiSensor",
203 "product": "tempSensorPro",
204 "hv": "tSP-1.0",
205 "fv": "0.1044",
206 "universe": 0,
207 "apiLevel": "20210413",
208 "categories":
209 [
210 4,
211 7
212 ],
213 "id": "42f5200ca102",
214 "ip": "172.0.0.1",
215 "availableFv": null
216 }
217 }
218 """
219 )
220
221 async def test_init(self, aioclient_mock):
222 """Test sensor default state."""
223
224 await self.allow_get_info(aioclient_mock)
225 entity = (await self.async_entities(aioclient_mock))[0]
226
227 assert entity.device_class == DEVICE_CLASS_TEMPERATURE
228 assert entity.unique_id == "BleBox-tempSensor-1afe34db9437-0.temperature"
229 assert entity.unit_of_measurement == TEMP_CELSIUS
230 assert entity.state is None
231 # assert entity.outdated is False
232
233 async def test_device_info(self, aioclient_mock):
234 await self.allow_get_info(aioclient_mock, self.DEVICE_INFO)
235 entity = (await self.async_entities(aioclient_mock))[0]
236 assert entity.device_info["name"] == "My tempSensor"
237 assert entity.device_info["mac"] == "1afe34db9437"
238 assert entity.device_info["manufacturer"] == "BleBox"
239 assert entity.device_info["model"] == "tempSensor"
240 assert entity.device_info["sw_version"] == "0.176"
241
242 async def test_update(self, aioclient_mock):
243 """Test sensor update."""
244
245 await self.allow_get_info(aioclient_mock)
246 entity = (await self.async_entities(aioclient_mock))[0]
247
248 self.allow_get_state(aioclient_mock, self.STATE_DEFAULT)
249 await entity.async_update()
250
251 # TODO: include product name?
252 assert entity.name == "My tempSensor (tempSensor#0.temperature)"
253 assert entity.state == 25.2
254 assert entity._feature.index is None
255 assert entity._feature.name is None
256
257 async def test_sensor_factory(self, aioclient_mock):
258 """Test sensor factory method class."""
259
260 self.DEVICE_EXTENDED_INFO = self.DEVICE_MULTISENSOR
261 self.STATE_DEFAULT = self.DEVICE_MULTISENSOR
262 self.DEVICE_INFO = self.DEVICE_INFO_MULTISENSOR
263 await self.allow_get_info(aioclient_mock)
264
265 entities = await self.async_entities(aioclient_mock)
266
267 assert len(entities) == 3
268 assert entities[0]._feature.index == 0
269 assert entities[0]._feature.name == "Temperature outside"
270 assert entities[1]._feature.index == 1
271 assert entities[1]._feature.name == "Temperature inside fence"
272 assert entities[2]._feature.index == 2
273 assert entities[2]._feature.name == "Underground -10 cm"
274
275 async def test_multisensor_update(self, aioclient_mock):
276 self.DEV_INFO_PATH = "state"
277 self.DEVICE_EXTENDED_INFO = self.DEVICE_MULTISENSOR
278 self.STATE_DEFAULT = self.DEVICE_MULTISENSOR
279 self.DEVICE_INFO = self.DEVICE_INFO_MULTISENSOR
280 # await self.allow_get_state(aioclient_mock)
281
282 entity = await self.updated(aioclient_mock, self.DEVICE_MULTISENSOR_UPDATE)
283
284 assert entity.native_value == 1.2
285
286 STATE_SENSOR_ERROR = json.loads(
287 """
288 {
289 "tempSensor": {
290 "sensors": [
291 {
292 "type": "temperature",
293 "id": 0,
294 "value": 18349,
295 "trend": 3,
296 "state": 3,
297 "elapsedTimeS": 0
298 }
299 ]
300 }
301 }
302 """
303 )
304
305 async def test_update_with_sensor_error_state_ignores_out_of_range_value(
306 self, aioclient_mock
307 ):
308 """Regression test: a broken probe must not prevent device setup."""
309
310 entity = await self.updated(aioclient_mock, self.STATE_SENSOR_ERROR)
311
312 assert entity.native_value is None
313 assert entity._feature.is_error is True
314
315 async def test_valid_state_trusts_out_of_nominal_range_value(self, aioclient_mock):
316 """state == 2 means the value is valid, even outside the nominal range."""
317
318 state = jmerge(
319 self.STATE_DEFAULT,
320 '{ "tempSensor": { "sensors": [ { "value": 18349, "state": 2 } ] } }',
321 )
322
323 entity = await self.updated(aioclient_mock, state)
324
325 assert entity._feature.is_error is False
326 assert entity.native_value == 183.5
327
328 async def test_initializing_state_reports_unknown_not_error(self, aioclient_mock):
329 """state == 1 (measurement in progress) must not surface a value or an error."""
330
331 state = jmerge(
332 self.STATE_DEFAULT,
333 '{ "tempSensor": { "sensors": [ { "value": 18349, "state": 1 } ] } }',
334 )
335
336 entity = await self.updated(aioclient_mock, state)
337
338 assert entity._feature.is_error is False
339 assert entity.native_value is None
340
341 async def test_update_recovers_after_sensor_error_clears(self, aioclient_mock):
342 """Entity value is restored once the sensor reports a valid state again."""
343
344 entity = await self.updated(aioclient_mock, self.STATE_SENSOR_ERROR)
345 assert entity._feature.is_error is True
346
347 product = entity._feature.product
348 product._update_last_data(self.STATE_DEFAULT)
349
350 assert entity._feature.is_error is False
351 assert entity.native_value == 25.2
352
353
354 class TestMultiSensorEnergy(DefaultBoxTest):
355 """Tests for multiSensor energy/current sensors (apiLevel 20230606)."""
356
357 DEVCLASS = "sensors"
358 ENTITY_CLASS = BleBoxSensorEntity
359
360 DEV_INFO_PATH = "state"
361
362 DEVICE_INFO = json.loads(
363 """
364 {
365 "device": {
366 "deviceName": "My multiSensor",
367 "type": "multiSensor",
368 "product": "energySensor",
369 "hv": "eS-1.0",
370 "fv": "0.1",
371 "universe": 0,
372 "apiLevel": "20230606",
373 "id": "aa00112233bb",
374 "ip": "172.0.0.1",
375 "availableFv": null
376 }
377 }
378 """
379 )
380
381 def patch_version(apiLevel):
382 return f'{{ "device": {{ "apiLevel": {apiLevel} }} }}'
383
384 DEVICE_INFO_FUTURE = jmerge(DEVICE_INFO, patch_version(future_date()))
385 DEVICE_INFO_LATEST = jmerge(
386 DEVICE_INFO, patch_version(get_latest_api_level("multiSensor"))
387 )
388 DEVICE_INFO_UNSUPPORTED = jmerge(DEVICE_INFO, patch_version(20180603))
389 DEVICE_INFO_UNSPECIFIED_API = None
390
391 STATE_DEFAULT = json.loads(
392 """
393 {
394 "multiSensor": {
395 "sensors": [
396 {"type": "current", "id": 0, "value": 1500},
397 {"type": "forwardActiveEnergy", "id": 1, "value": 5000},
398 {"type": "reverseActiveEnergy", "id": 2, "value": 3000}
399 ]
400 }
401 }
402 """
403 )
404
405 DEVICE_EXTENDED_INFO = STATE_DEFAULT
406 DEVICE_EXTENDED_INFO_PATH = "/state/extended"
407
408 @pytest.mark.parametrize(
409 "index,unit,value",
410 [
411 (0, "mA", 1500),
412 (1, "kWh", 5.0),
413 (2, "kWh", 3.0),
414 ],
415 )
416 async def test_sensor_value(self, aioclient_mock, index, unit, value):
417 entity = await self.updated(aioclient_mock, self.STATE_DEFAULT, index=index)
418 assert entity._feature.unit == unit
419 assert entity.native_value == value
420
421 async def test_sensor_error_state_reports_error(self, aioclient_mock):
422 """state == 3 is the only value that marks the sensor as errored."""
423
424 state_json = jmerge(
425 self.STATE_DEFAULT,
426 '{ "multiSensor": { "sensors": [ { "state": 3 } ] } }',
427 )
428
429 entity = await self.updated(aioclient_mock, state_json, index=0)
430
431 assert entity.native_value is None
432 assert entity._feature.is_error is True
433
434 async def test_sensor_initializing_state_reports_unknown_not_error(
435 self, aioclient_mock
436 ):
437 """state == 1 (measurement in progress) must not surface a value or an error."""
438
439 state_json = jmerge(
440 self.STATE_DEFAULT,
441 '{ "multiSensor": { "sensors": [ { "state": 1 } ] } }',
442 )
443
444 entity = await self.updated(aioclient_mock, state_json, index=0)
445
446 assert entity._feature.is_error is False
447 assert entity.native_value is None
448
449 @pytest.mark.parametrize("state", [0, 2, 4, 5])
450 async def test_sensor_valid_state_reports_value(self, aioclient_mock, state):
451 """States other than 1 (init) and 3 (error) trust the reported value,
452 including 4/5 (out of range), where value is the measurement limit."""
453
454 state_json = jmerge(
455 self.STATE_DEFAULT,
456 f'{{ "multiSensor": {{ "sensors": [ {{ "state": {state} }} ] }} }}',
457 )
458
459 entity = await self.updated(aioclient_mock, state_json, index=0)
460
461 assert entity._feature.is_error is False
462 assert entity.native_value == 1500
463
464
465 class TestAirSensor(DefaultBoxTest):
466 """Tests for sensors representing BleBox airSensor."""
467
468 DEV_INFO_PATH = "api/air/state"
469
470 DEVCLASS = "sensors"
471 ENTITY_CLASS = BleBoxSensorEntity
472
473 DEVICE_INFO = json.loads(
474 """
475 {
476 "deviceName": "My air 1",
477 "type": "airSensor",
478 "fv": "0.973",
479 "hv": "0.6",
480 "apiLevel": "20180403",
481 "id": "1afe34db9437",
482 "ip": "192.168.1.11"
483 }
484 """
485 )
486
487 def patch_version(apiLevel):
488 """Generate a patch for a JSON state fixture."""
489 return f"""
490 {{ "apiLevel": {apiLevel} }}
491 """
492
493 DEVICE_INFO_FUTURE = jmerge(DEVICE_INFO, patch_version(future_date()))
494 DEVICE_INFO_LATEST = jmerge(
495 DEVICE_INFO, patch_version(get_latest_api_level("airSensor"))
496 )
497 DEVICE_INFO_UNSUPPORTED = jmerge(DEVICE_INFO, patch_version(20180402))
498
499 DEVICE_INFO_UNSPECIFIED_API = json.loads(
500 """
501 {
502 "deviceName": "My air 1",
503 "type": "airSensor",
504 "fv": "0.973",
505 "hv": "0.6",
506 "id": "1afe34db9437",
507 "ip": "192.168.1.11"
508 }
509 """
510 )
511
512 STATE_DEFAULT = json.loads(
513 """
514 {
515 "air": {
516 "sensors": [
517 {
518 "type": "pm1",
519 "value": 49,
520 "trend": 3,
521 "state": 0,
522 "qualityLevel": 0,
523 "elaspedTimeS": -1
524 },
525 {
526 "type": "pm2.5",
527 "value": 222,
528 "trend": 1,
529 "state": 0,
530 "qualityLevel": 4,
531 "elaspedTimeS": -1
532 },
533 {
534 "type": "pm10",
535 "value": 333,
536 "trend": 0,
537 "state": 0,
538 "qualityLevel": 6,
539 "elaspedTimeS": -1
540 }
541 ]
542 }
543 }
544 """
545 )
546
547 # DEVICE_EXTENDED_INFO
548 # DEVICE_EXTENDED_INFO_PATH
549
550 async def test_init(self, aioclient_mock):
551 """Test air quality sensor default state."""
552
553 await self.allow_get_info(aioclient_mock)
554 entity = (await self.async_entities(aioclient_mock))[0]
555
556 assert entity.name == "My air 1 (airSensor#pm1)"
557 assert entity.unique_id == "BleBox-airSensor-1afe34db9437-pm1"
558 assert entity.native_value is None
559
560 async def test_device_info(self, aioclient_mock):
561 await self.allow_get_info(aioclient_mock, self.DEVICE_INFO)
562 entity = (await self.async_entities(aioclient_mock))[0]
563 assert entity.device_info["name"] == "My air 1"
564 assert entity.device_info["mac"] == "1afe34db9437"
565 assert entity.device_info["manufacturer"] == "BleBox"
566 assert entity.device_info["model"] == "airSensor"
567 assert entity.device_info["sw_version"] == "0.973"
568
569 @pytest.mark.parametrize("io_param", [(0, 49), (1, 222), (2, 333)])
570 async def test_update(self, aioclient_mock, io_param):
571 """Test air quality sensor state after update."""
572
573 await self.allow_get_info(aioclient_mock)
574 entity = (await self.async_entities(aioclient_mock))[io_param[0]]
575
576 self.allow_get_state(aioclient_mock, self.STATE_DEFAULT)
577 await entity.async_update()
578
579 assert entity.native_value == io_param[1] # parametrised
580
581 async def test_list_quantity(self, aioclient_mock):
582 """Test air sensor init from config."""
583 await self.allow_get_info(aioclient_mock)
584
585 entity = await self.async_entities(aioclient_mock)
586
587 assert len(entity) == 3