-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathtest_sensor.py
429 lines (359 loc) · 11.5 KB
/
test_sensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""The test for the average sensor platform."""
# pylint: disable=redefined-outer-name
from __future__ import annotations
import logging
from asyncio import sleep
from datetime import timedelta
from unittest.mock import MagicMock, patch
import homeassistant.util.dt as dt_util
import pytest
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.components.water_heater import DOMAIN as WATER_HEATER_DOMAIN
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
CONF_ENTITIES,
CONF_NAME,
CONF_PLATFORM,
CONF_UNIQUE_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.template import Template
from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import TEMPERATURE_UNITS
from pytest_homeassistant_custom_component.common import assert_setup_component
from voluptuous import Invalid
from custom_components.average.const import (
CONF_DURATION,
CONF_END,
CONF_PRECISION,
CONF_START,
DOMAIN,
)
from custom_components.average.sensor import (
AverageSensor,
async_setup_platform,
check_period_keys,
)
from .const import TEST_ENTITY_IDS, TEST_NAME, TEST_UNIQUE_ID
@pytest.fixture
def default_sensor_config():
"""Return default test config for AverageSensor."""
return {
CONF_UNIQUE_ID: TEST_UNIQUE_ID,
CONF_NAME: TEST_NAME,
# CONF_START: None,
CONF_END: Template("{{ now() }}"),
CONF_DURATION: timedelta(minutes=3),
CONF_ENTITIES: TEST_ENTITY_IDS,
CONF_PRECISION: 2,
# CONF_PROCESS_UNDEF_AS: None,
}
@pytest.fixture
def default_sensor(hass: HomeAssistant, default_sensor_config):
"""Create an AverageSensor with default values."""
return AverageSensor(hass, default_sensor_config)
async def test_valid_check_period_keys(hass: HomeAssistant):
"""Test period keys check."""
assert check_period_keys(
{
CONF_DURATION: 10,
}
)
assert check_period_keys(
{
CONF_START: 11,
CONF_DURATION: 12,
}
)
assert check_period_keys(
{
CONF_DURATION: 13,
CONF_END: 14,
}
)
assert check_period_keys(
{
CONF_START: 15,
CONF_END: 16,
}
)
async def test_invalid_check_period_keys(hass: HomeAssistant):
"""Test period keys check."""
with pytest.raises(Invalid):
check_period_keys(
{
CONF_END: 20,
}
)
with pytest.raises(Invalid):
check_period_keys(
{
CONF_START: 21,
}
)
with pytest.raises(Invalid):
check_period_keys(
{
CONF_START: 22,
CONF_END: 23,
CONF_DURATION: 24,
}
)
async def test_setup_platform(hass: HomeAssistant):
"""Test platform setup."""
async_add_entities = MagicMock()
config = {
CONF_PLATFORM: DOMAIN,
CONF_NAME: "test",
CONF_ENTITIES: ["sensor.test_monitored"],
CONF_START: Template("{{ 0 }}"),
CONF_DURATION: timedelta(seconds=10),
}
await async_setup_platform(hass, config, async_add_entities, None)
assert async_add_entities.called
async def test_entity_initialization(
hass: HomeAssistant, default_sensor, default_sensor_config
):
"""Test sensor initialization."""
expected_attributes = {
"available_sources": 0,
"count": 0,
"count_sources": 1,
"sources": ["sensor.test_monitored"],
}
assert default_sensor.unique_id == TEST_UNIQUE_ID
assert default_sensor.name == TEST_NAME
assert default_sensor.should_poll is True
assert default_sensor.available is False
assert default_sensor.native_value is None
assert default_sensor.native_unit_of_measurement is None
assert default_sensor.icon is None
assert default_sensor.extra_state_attributes == expected_attributes
config = default_sensor_config.copy()
config[CONF_UNIQUE_ID] = None
entity = AverageSensor(hass, config)
#
assert entity.unique_id is None
config = default_sensor_config.copy()
config[CONF_UNIQUE_ID] = "__legacy__"
entity = AverageSensor(hass, config)
#
assert entity.unique_id in (
"2ef66732fb7155dce84ad53afe910beba59cfad4",
"ca6b83d00637cf7d1e2f5c30b4f4f0402ad2fc53",
)
async def test_async_setup_platform(hass: HomeAssistant):
"""Test platform setup."""
mock_sensor = {
"platform": "template",
"sensors": {"test_monitored": {"value_template": "{{ 2 }}"}},
}
config = {
CONF_PLATFORM: DOMAIN,
CONF_ENTITIES: ["sensor.test_monitored", "sensor.nonexistent"],
}
with assert_setup_component(2, SENSOR):
assert await async_setup_component(
hass,
SENSOR,
{
SENSOR: [
config,
mock_sensor,
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("sensor.average")
assert state is not None
assert state.state == "2.0"
# pylint: disable=protected-access
async def test__has_state():
"""Test states checker."""
# Valid states
states = [True, 12, "qwe", 45.22, False]
for state in states:
assert AverageSensor._has_state(state)
# Invalid states
states = [None, STATE_UNKNOWN, STATE_UNAVAILABLE, "None", ""]
for state in states:
assert AverageSensor._has_state(state) is False
# pylint: disable=protected-access
async def test__get_temperature(default_sensor):
"""Test temperature getter."""
state = State(
"weather.test",
"test",
{"temperature": 25},
)
assert default_sensor._get_temperature(state) == 25
state = State(
"climate.test",
"test",
{"current_temperature": 16},
)
assert default_sensor._get_temperature(state) == 16
state = State(
"sensor.test",
"125",
{ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.FAHRENHEIT},
dt_util.now(),
)
assert round(default_sensor._get_temperature(state), 3) == 51.667
state = State(
"sensor.test",
"",
{ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.FAHRENHEIT},
dt_util.now(),
)
assert default_sensor._get_temperature(state) is None
state = State(
"sensor.test",
"qwe",
{ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.FAHRENHEIT},
dt_util.now(),
)
assert default_sensor._get_temperature(state) is None
# pylint: disable=protected-access
async def test__get_state_value(default_sensor):
"""Test state getter."""
default_sensor._undef = "Undef"
state = State(
"sensor.test",
"None",
{ATTR_UNIT_OF_MEASUREMENT: None},
dt_util.now(),
)
assert default_sensor._get_state_value(state) == "Undef"
state = State(
"sensor.test",
"asd",
{ATTR_UNIT_OF_MEASUREMENT: None},
dt_util.now(),
)
assert default_sensor._get_state_value(state) is None
state = State(
"sensor.test",
"21",
{ATTR_UNIT_OF_MEASUREMENT: None},
dt_util.now(),
)
assert default_sensor._get_state_value(state) == 21
state = State(
"sensor.test",
"34",
{ATTR_UNIT_OF_MEASUREMENT: None},
dt_util.now(),
)
assert default_sensor._get_state_value(state) == 34
assert default_sensor.min_value == 21
assert default_sensor.max_value == 34
async def test__init_mode(hass: HomeAssistant, default_sensor, caplog):
"""Test sensor mode initialization."""
caplog.set_level(logging.DEBUG)
assert default_sensor._temperature_mode is None
assert default_sensor._attr_device_class is None
assert default_sensor._attr_native_unit_of_measurement is None
assert default_sensor._attr_icon is None
# Detect by device class
state = State(
"sensor.test",
"None",
{
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
},
)
caplog.clear()
default_sensor._temperature_mode = None
default_sensor._attr_device_class = None
default_sensor._attr_native_unit_of_measurement = None
default_sensor._init_mode(state)
assert default_sensor._temperature_mode is True
assert default_sensor._attr_device_class is SensorDeviceClass.TEMPERATURE
assert (
default_sensor._attr_native_unit_of_measurement
is hass.config.units.temperature_unit
)
assert len(caplog.records) == 1
# Detect by measuring unit
for unit in TEMPERATURE_UNITS:
state = State(
"sensor.test",
"None",
{
ATTR_UNIT_OF_MEASUREMENT: unit,
},
)
caplog.clear()
default_sensor._temperature_mode = None
default_sensor._attr_device_class = None
default_sensor._attr_native_unit_of_measurement = None
default_sensor._init_mode(state)
assert default_sensor._temperature_mode is True
assert default_sensor._attr_device_class is SensorDeviceClass.TEMPERATURE
assert (
default_sensor._attr_native_unit_of_measurement
== hass.config.units.temperature_unit
)
assert len(caplog.records) == 1
# Detect by domain
for domain in (WEATHER_DOMAIN, CLIMATE_DOMAIN, WATER_HEATER_DOMAIN):
state = State(
f"{domain}.test",
"None",
)
caplog.clear()
default_sensor._temperature_mode = None
default_sensor._attr_device_class = None
default_sensor._attr_native_unit_of_measurement = None
default_sensor._init_mode(state)
assert default_sensor._temperature_mode is True
assert default_sensor._attr_device_class is SensorDeviceClass.TEMPERATURE
assert (
default_sensor._attr_native_unit_of_measurement
== hass.config.units.temperature_unit
)
assert len(caplog.records) == 1
# Can't detect
state = State(
"sensor.test",
"None",
{
ATTR_ICON: "some_icon",
},
)
caplog.clear()
default_sensor._temperature_mode = None
default_sensor._attr_device_class = None
default_sensor._attr_native_unit_of_measurement = None
default_sensor._init_mode(state)
assert default_sensor._temperature_mode is False
assert default_sensor._attr_device_class is None
assert default_sensor._attr_native_unit_of_measurement is None
assert default_sensor._attr_icon == "some_icon"
assert len(caplog.records) == 1
# Skip if mode already detected
caplog.clear()
default_sensor._init_mode(state)
assert len(caplog.records) == 0
async def test_update(default_sensor):
"""Test update throttler."""
with patch.object(default_sensor, "_async_update_state") as ups:
await default_sensor.async_update()
await sleep(1)
await default_sensor.async_update()
assert ups.call_count == 1
# pylint: disable=protected-access
async def test__update_period(default_sensor):
"""Test period updater."""
# TODO(Limych): ; #noqa: TD003