Allow service data template to return a dict (#57105)

This commit is contained in:
Chris Browet 2021-10-23 21:10:30 +02:00 committed by GitHub
parent 9ae7f0ecd7
commit e961d92b5e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 5 deletions

View file

@ -929,8 +929,10 @@ SERVICE_SCHEMA = vol.All(
vol.Exclusive(CONF_SERVICE_TEMPLATE, "service name"): vol.Any(
service, dynamic_template
),
vol.Optional("data"): vol.All(dict, template_complex),
vol.Optional("data_template"): vol.All(dict, template_complex),
vol.Optional("data"): vol.Any(template, vol.All(dict, template_complex)),
vol.Optional("data_template"): vol.Any(
template, vol.All(dict, template_complex)
),
vol.Optional(CONF_ENTITY_ID): comp_entity_ids,
vol.Optional(CONF_TARGET): vol.Any(ENTITY_SERVICE_FIELDS, dynamic_template),
}

View file

@ -234,7 +234,12 @@ def async_prepare_call_from_config(
continue
try:
template.attach(hass, config[conf])
service_data.update(template.render_complex(config[conf], variables))
render = template.render_complex(config[conf], variables)
if not isinstance(render, dict):
raise HomeAssistantError(
"Error rendering data template: Result is not a Dictionary"
)
service_data.update(render)
except TemplateError as ex:
raise HomeAssistantError(f"Error rendering data template: {ex}") from ex

View file

@ -45,9 +45,9 @@ def calls(hass):
return async_mock_service(hass, "test", "automation")
async def test_service_data_not_a_dict(hass, calls):
async def test_service_data_not_a_dict(hass, caplog, calls):
"""Test service data not dict."""
with assert_setup_component(0, automation.DOMAIN):
with assert_setup_component(1, automation.DOMAIN):
assert await async_setup_component(
hass,
automation.DOMAIN,
@ -59,6 +59,34 @@ async def test_service_data_not_a_dict(hass, calls):
},
)
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 0
assert "Result is not a Dictionary" in caplog.text
async def test_service_data_single_template(hass, calls):
"""Test service data not dict."""
with assert_setup_component(1, automation.DOMAIN):
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"action": {
"service": "test.automation",
"data": "{{ { 'foo': 'bar' } }}",
},
}
},
)
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["foo"] == "bar"
async def test_service_specify_data(hass, calls):
"""Test service data."""