From dd9e926689557eaf70e41a171f3ec7393998eeae Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Mon, 1 Mar 2021 23:34:26 +0100 Subject: [PATCH] Pass variables to initial evaluation of template trigger (#47236) * Pass variables to initial evaluation of template trigger * Add test * Clarify test --- homeassistant/components/template/trigger.py | 4 ++- tests/components/template/test_trigger.py | 38 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/template/trigger.py b/homeassistant/components/template/trigger.py index 9e6ee086c73..1f378c59335 100644 --- a/homeassistant/components/template/trigger.py +++ b/homeassistant/components/template/trigger.py @@ -41,7 +41,9 @@ async def async_attach_trigger( # Arm at setup if the template is already false. try: - if not result_as_boolean(value_template.async_render()): + if not result_as_boolean( + value_template.async_render(automation_info["variables"]) + ): armed = True except exceptions.TemplateError as ex: _LOGGER.warning( diff --git a/tests/components/template/test_trigger.py b/tests/components/template/test_trigger.py index 3ba79e85bf2..55311005201 100644 --- a/tests/components/template/test_trigger.py +++ b/tests/components/template/test_trigger.py @@ -135,6 +135,44 @@ async def test_if_not_fires_when_true_at_setup(hass, calls): assert len(calls) == 0 +async def test_if_not_fires_when_true_at_setup_variables(hass, calls): + """Test for not firing during startup + trigger_variables.""" + assert await async_setup_component( + hass, + automation.DOMAIN, + { + automation.DOMAIN: { + "trigger_variables": {"entity": "test.entity"}, + "trigger": { + "platform": "template", + "value_template": '{{ is_state(entity|default("test.entity2"), "hello") }}', + }, + "action": {"service": "test.automation"}, + } + }, + ) + + assert len(calls) == 0 + + # Assert that the trigger doesn't fire immediately when it's setup + # If trigger_variable 'entity' is not passed to initial check at setup, the + # trigger will immediately fire + hass.states.async_set("test.entity", "hello", force_update=True) + await hass.async_block_till_done() + assert len(calls) == 0 + + hass.states.async_set("test.entity", "goodbye", force_update=True) + await hass.async_block_till_done() + assert len(calls) == 0 + + # Assert that the trigger fires after state change + # If trigger_variable 'entity' is not passed to the template trigger, the + # trigger will never fire because it falls back to 'test.entity2' + hass.states.async_set("test.entity", "hello", force_update=True) + await hass.async_block_till_done() + assert len(calls) == 1 + + async def test_if_not_fires_because_fail(hass, calls): """Test for not firing after TemplateError.""" hass.states.async_set("test.number", "1")