From 371b589cb294b33a5371a4b033fafd75dcf42502 Mon Sep 17 00:00:00 2001 From: Kevin Cathcart Date: Fri, 25 Sep 2020 03:15:04 -0400 Subject: [PATCH] Fix bug in state trigger when using for: without to: (#40556) --- .../homeassistant/triggers/state.py | 2 +- .../homeassistant/triggers/test_state.py | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/homeassistant/triggers/state.py b/homeassistant/components/homeassistant/triggers/state.py index f57db0ed56a..a7377ffe43e 100644 --- a/homeassistant/components/homeassistant/triggers/state.py +++ b/homeassistant/components/homeassistant/triggers/state.py @@ -145,7 +145,7 @@ async def async_attach_trigger( else: cur_value = new_st.attributes.get(attribute) - if CONF_TO not in config: + if CONF_FROM in config and CONF_TO not in config: return cur_value != old_value return cur_value == new_value diff --git a/tests/components/homeassistant/triggers/test_state.py b/tests/components/homeassistant/triggers/test_state.py index ce9ecaba1b0..990fc9cc956 100644 --- a/tests/components/homeassistant/triggers/test_state.py +++ b/tests/components/homeassistant/triggers/test_state.py @@ -538,6 +538,39 @@ async def test_if_fires_on_entity_change_with_for_without_to(hass, calls): assert len(calls) == 1 +async def test_if_does_not_fires_on_entity_change_with_for_without_to_2(hass, calls): + """Test for firing on entity change with for.""" + assert await async_setup_component( + hass, + automation.DOMAIN, + { + automation.DOMAIN: { + "trigger": { + "platform": "state", + "entity_id": "test.entity", + "for": {"seconds": 5}, + }, + "action": {"service": "test.automation"}, + } + }, + ) + await hass.async_block_till_done() + + utcnow = dt_util.utcnow() + with patch("homeassistant.core.dt_util.utcnow") as mock_utcnow: + mock_utcnow.return_value = utcnow + + for i in range(10): + hass.states.async_set("test.entity", str(i)) + await hass.async_block_till_done() + + mock_utcnow.return_value += timedelta(seconds=1) + async_fire_time_changed(hass, mock_utcnow.return_value) + await hass.async_block_till_done() + + assert len(calls) == 0 + + async def test_if_fires_on_entity_creation_and_removal(hass, calls): """Test for firing on entity creation and removal, with to/from constraints.""" # set automations for multiple combinations to/from