Support templates in event triggers (#46207)

* Support templates in event triggers

* Don't validate trigger schemas twice
This commit is contained in:
Erik Montnemery
2021-02-08 14:06:27 +01:00
committed by GitHub
parent eaa2d371a7
commit 0780e52ca4
5 changed files with 135 additions and 36 deletions

View File

@@ -17,7 +17,7 @@ def calls(hass):
@pytest.fixture
def context_with_user():
"""Track calls to a mock service."""
"""Create a context with default user_id."""
return Context(user_id="test_user_id")
@@ -59,6 +59,39 @@ async def test_if_fires_on_event(hass, calls):
assert len(calls) == 1
async def test_if_fires_on_templated_event(hass, calls):
"""Test the firing of events."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger_variables": {"event_type": "test_event"},
"trigger": {"platform": "event", "event_type": "{{event_type}}"},
"action": {"service": "test.automation"},
}
},
)
hass.bus.async_fire("test_event", context=context)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
await hass.services.async_call(
automation.DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_MATCH_ALL},
blocking=True,
)
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_multiple_events(hass, calls):
"""Test the firing of events."""
context = Context()
@@ -161,6 +194,58 @@ async def test_if_fires_on_event_with_data_and_context(hass, calls, context_with
assert len(calls) == 1
async def test_if_fires_on_event_with_templated_data_and_context(
hass, calls, context_with_user
):
"""Test the firing of events with templated data and context."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger_variables": {
"attr_1_val": "milk",
"attr_2_val": "beer",
"user_id": context_with_user.user_id,
},
"trigger": {
"platform": "event",
"event_type": "test_event",
"event_data": {
"attr_1": "{{attr_1_val}}",
"attr_2": "{{attr_2_val}}",
},
"context": {"user_id": "{{user_id}}"},
},
"action": {"service": "test.automation"},
}
},
)
hass.bus.async_fire(
"test_event",
{"attr_1": "milk", "another": "value", "attr_2": "beer"},
context=context_with_user,
)
await hass.async_block_till_done()
assert len(calls) == 1
hass.bus.async_fire(
"test_event",
{"attr_1": "milk", "another": "value"},
context=context_with_user,
)
await hass.async_block_till_done()
assert len(calls) == 1 # No new call
hass.bus.async_fire(
"test_event",
{"attr_1": "milk", "another": "value", "attr_2": "beer"},
)
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_event_with_empty_data_and_context_config(
hass, calls, context_with_user
):