Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed set_state with last_update #294

Merged
merged 5 commits into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ha_mqtt_discoverable/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch!

logger.debug(f"Writing '{state}' to {topic}")

if self._settings.debug:
Expand Down
20 changes: 19 additions & 1 deletion tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down Expand Up @@ -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()
Loading