Return current state if template throws (#65534)

This commit is contained in:
Jan Bouwhuis 2022-02-03 16:46:36 +01:00 committed by Paulus Schoutsen
parent 689133976a
commit 931c27f452
2 changed files with 33 additions and 1 deletions

View File

@ -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,

View File

@ -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(