diff --git a/ha_mqtt_discoverable/__init__.py b/ha_mqtt_discoverable/__init__.py index 6098c35..57c0290 100644 --- a/ha_mqtt_discoverable/__init__.py +++ b/ha_mqtt_discoverable/__init__.py @@ -740,6 +740,7 @@ def _state_helper( topic = self.state_topic if last_reset: state = {"state": state, "last_reset": last_reset} + state = json.dumps(state) logger.debug(f"Writing '{state}' to {topic}") if self._settings.debug: diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 6c5980a..7adc4ce 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -17,6 +17,7 @@ from ha_mqtt_discoverable import Settings from ha_mqtt_discoverable.sensors import Sensor, SensorInfo +from unittest.mock import patch @pytest.fixture(params=["°C", "kWh"]) @@ -46,4 +47,21 @@ def test_generate_config(sensor: Sensor): def test_update_state(sensor: Sensor): - sensor.set_state(1) + with patch.object(sensor.mqtt_client, "publish") as mock_publish: + sensor.set_state(1) + mock_publish.assert_called_with(sensor.state_topic, "1", retain=True) + + +def test_update_state_with_last_reset(sensor: Sensor): + from datetime import datetime, timedelta, timezone + + now = datetime.now(timezone(timedelta(hours=1))) + midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) + + with patch.object(sensor.mqtt_client, "publish") as mock_publish: + sensor.set_state(1, midnight.isoformat()) + parameter = mock_publish.call_args.args[1] + import json + + parameter_json = json.loads(parameter) + assert parameter_json["last_reset"] == midnight.isoformat()