Set MQTT sensor to state unavailable when value expires (#36609)

This commit is contained in:
Erik Montnemery authored and GitHub committed 2020-07-08 16:20:19 -07:00
1 parent fb420d5952
commit fb3049d6a2
3 files changed
+63 -8

No files matched your search

+41 -3
View File
@@ -7,7 +7,7 @@ import pytest
from homeassistant.components import mqtt
from homeassistant.components.mqtt.discovery import async_start
import homeassistant.components.sensor as sensor
from homeassistant.const import EVENT_STATE_CHANGED
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNAVAILABLE
import homeassistant.core as ha
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
@@ -73,6 +73,38 @@ async def test_setting_sensor_value_via_mqtt_message(hass, mqtt_mock):
assert state.attributes.get("unit_of_measurement") == "fav unit"
async def test_setting_sensor_value_expires_availability_topic(
hass, mqtt_mock, legacy_patchable_time, caplog
):
"""Test the expiration of the value."""
assert await async_setup_component(
hass,
sensor.DOMAIN,
{
sensor.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "test-topic",
"expire_after": 4,
"force_update": True,
"availability_topic": "availability-topic",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("sensor.test")
assert state.state == STATE_UNAVAILABLE
async_fire_mqtt_message(hass, "availability-topic", "online")
# State should be unavailable since expire_after is defined and > 0
state = hass.states.get("sensor.test")
assert state.state == STATE_UNAVAILABLE
await expires_helper(hass, mqtt_mock, caplog)
async def test_setting_sensor_value_expires(
hass, mqtt_mock, legacy_patchable_time, caplog
):
@@ -93,9 +125,15 @@ async def test_setting_sensor_value_expires(
)
await hass.async_block_till_done()
# State should be unavailable since expire_after is defined and > 0
state = hass.states.get("sensor.test")
assert state.state == "unknown"
assert state.state == STATE_UNAVAILABLE
await expires_helper(hass, mqtt_mock, caplog)
async def expires_helper(hass, mqtt_mock, caplog):
"""Run the basic expiry code."""
realnow = dt_util.utcnow()
now = datetime(realnow.year + 1, 1, 1, 1, tzinfo=dt_util.UTC)
with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now):
@@ -142,7 +180,7 @@ async def test_setting_sensor_value_expires(
# Value is expired now
state = hass.states.get("sensor.test")
assert state.state == "unknown"
assert state.state == STATE_UNAVAILABLE
async def test_setting_sensor_value_via_mqtt_json_message(hass, mqtt_mock):