Skip to content

Commit

Permalink
split template
Browse files Browse the repository at this point in the history
  • Loading branch information
pvizeli committed Sep 8, 2016
1 parent e176922 commit dfa58ae
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
26 changes: 17 additions & 9 deletions homeassistant/helpers/config_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,8 @@ def template(value):
"""Validate a jinja2 template."""
if value is None:
raise vol.Invalid('template value is None')
if isinstance(value, list):
for idx, element in enumerate(value):
value[idx] = template(element)
return value
if isinstance(value, dict):
for key, element in value.items():
value[key] = template(element)
return value
if isinstance(value, (list, dict)):
raise vol.Invalid('template value should be a string')

value = str(value)
try:
Expand All @@ -250,6 +244,20 @@ def template(value):
raise vol.Invalid('invalid template ({})'.format(ex))


def template_complex(value):
"""Validate a complex jinja2 template."""
if isinstance(value, list):
for idx, element in enumerate(value):
value[idx] = template_complex(element)
return value
if isinstance(value, dict):
for key, element in value.items():
value[key] = template_complex(element)
return value

return template(value)


def time(value):
"""Validate time."""
time_val = dt_util.parse_time(value)
Expand Down Expand Up @@ -316,7 +324,7 @@ def validator(value):
vol.Exclusive('service', 'service name'): service,
vol.Exclusive('service_template', 'service name'): template,
vol.Optional('data'): dict,
vol.Optional('data_template'): {match_all: template},
vol.Optional('data_template'): {match_all: template_complex},
vol.Optional(CONF_ENTITY_ID): entity_ids,
}), has_at_least_one_key('service', 'service_template'))

Expand Down
16 changes: 16 additions & 0 deletions tests/helpers/test_config_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,22 @@ def test_template():
"""Test template validator."""
schema = vol.Schema(cv.template)

for value in (None, '{{ partial_print }', '{% if True %}Hello', ['test']):
with pytest.raises(vol.MultipleInvalid):
schema(value)

for value in (
1, 'Hello',
'{{ beer }}',
'{% if 1 == 1 %}Hello{% else %}World{% endif %}',
):
schema(value)


def test_template_complex():
"""Test template_complex validator."""
schema = vol.Schema(cv.template_complex)

for value in (None, '{{ partial_print }', '{% if True %}Hello'):
with pytest.raises(vol.MultipleInvalid):
schema(value)
Expand Down

0 comments on commit dfa58ae

Please sign in to comment.