16
16
from unittest .mock import patch
17
17
18
18
import pytest
19
+ from pydantic import ValidationError
19
20
20
21
from ha_mqtt_discoverable import Settings
21
22
from ha_mqtt_discoverable .sensors import Sensor , SensorInfo
22
23
23
24
24
- @pytest .fixture (params = ["°C" , "kWh" ])
25
- def sensor (request ) -> Sensor :
26
- mqtt_settings = Settings .MQTT (host = "localhost" )
27
- sensor_info = SensorInfo (name = "test" , unit_of_measurement = request .param )
28
- settings = Settings (mqtt = mqtt_settings , entity = sensor_info )
29
- return Sensor (settings )
25
+ @pytest .fixture
26
+ def make_sensor ():
27
+ def _make_sensor (suggested_display_precision : None | int = 2 ):
28
+ mqtt_settings = Settings .MQTT (host = "localhost" )
29
+ sensor_info = SensorInfo (name = "test" , unit_of_measurement = "kWh" , suggested_display_precision = suggested_display_precision )
30
+ settings = Settings (mqtt = mqtt_settings , entity = sensor_info )
31
+ return Sensor (settings )
30
32
33
+ return _make_sensor
31
34
32
- def test_required_config ():
33
- mqtt_settings = Settings .MQTT (host = "localhost" )
34
- sensor_info = SensorInfo (name = "test" )
35
- settings = Settings (mqtt = mqtt_settings , entity = sensor_info )
36
- sensor = Sensor (settings )
35
+
36
+ @pytest .fixture
37
+ def sensor (make_sensor ) -> Sensor :
38
+ return make_sensor ()
39
+
40
+
41
+ def test_required_config (sensor : Sensor ):
37
42
assert sensor is not None
38
43
39
44
40
45
def test_generate_config (sensor : Sensor ):
41
46
config = sensor .generate_config ()
42
47
43
48
assert config is not None
44
- # If we have defined a custom unit of measurement, check that is part of the
45
- # output config
46
- if sensor ._entity .unit_of_measurement :
47
- assert config ["unit_of_measurement" ] == sensor ._entity .unit_of_measurement
49
+ assert config ["unit_of_measurement" ] == sensor ._entity .unit_of_measurement
50
+ assert config ["suggested_display_precision" ] == sensor ._entity .suggested_display_precision
48
51
49
52
50
53
def test_update_state (sensor : Sensor ):
@@ -66,3 +69,8 @@ def test_update_state_with_last_reset(sensor: Sensor):
66
69
67
70
parameter_json = json .loads (parameter )
68
71
assert parameter_json ["last_reset" ] == midnight .isoformat ()
72
+
73
+
74
+ def test_invalid_suggested_display_precision (make_sensor ):
75
+ with pytest .raises (ValidationError ):
76
+ make_sensor (suggested_display_precision = - 1 )
0 commit comments