From 931c27f4527c3cacb833c02c32dd938d7d702dfe Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 3 Feb 2022 16:46:36 +0100 Subject: [PATCH] Return current state if template throws (#65534) --- homeassistant/components/mqtt/sensor.py | 2 +- tests/components/mqtt/test_sensor.py | 32 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index 59f124155d3..fa949009a0d 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -236,7 +236,7 @@ class MqttSensor(MqttEntity, SensorEntity, RestoreEntity): self.hass, self._value_is_expired, expiration_at ) - payload = self._template(msg.payload) + payload = self._template(msg.payload, default=self._state) if payload is not None and self.device_class in ( SensorDeviceClass.DATE, diff --git a/tests/components/mqtt/test_sensor.py b/tests/components/mqtt/test_sensor.py index ad43a7b2353..c758b670b3d 100644 --- a/tests/components/mqtt/test_sensor.py +++ b/tests/components/mqtt/test_sensor.py @@ -268,6 +268,38 @@ async def test_setting_sensor_value_via_mqtt_json_message(hass, mqtt_mock): assert state.state == "100" +async def test_setting_sensor_value_via_mqtt_json_message_and_default_current_state( + hass, mqtt_mock +): + """Test the setting of the value via MQTT with fall back to current state.""" + assert await async_setup_component( + hass, + sensor.DOMAIN, + { + sensor.DOMAIN: { + "platform": "mqtt", + "name": "test", + "state_topic": "test-topic", + "unit_of_measurement": "fav unit", + "value_template": "{{ value_json.val | is_defined }}-{{ value_json.par }}", + } + }, + ) + await hass.async_block_till_done() + + async_fire_mqtt_message( + hass, "test-topic", '{ "val": "valcontent", "par": "parcontent" }' + ) + state = hass.states.get("sensor.test") + + assert state.state == "valcontent-parcontent" + + async_fire_mqtt_message(hass, "test-topic", '{ "par": "invalidcontent" }') + state = hass.states.get("sensor.test") + + assert state.state == "valcontent-parcontent" + + async def test_setting_sensor_last_reset_via_mqtt_message(hass, mqtt_mock, caplog): """Test the setting of the last_reset property via MQTT.""" assert await async_setup_component(