Handle non-string values in JSON renderer (#20233)

Handle the case of async_render_with_possible_json_value's value argument
being something other than a string. This can happen, e.g., when using the
SQL sensor to extract a datetime column such as last_changed and also using
its value_template to convert that datetime to another format. This was
causing a TypeError from json.loads, but async_render_with_possible_json_value
was only catching ValueError's.
This commit is contained in:
Phil Bruckner 2019-01-20 18:46:14 -06:00 committed by Paulus Schoutsen
parent 3fcbcd5a38
commit 935e5c67a3
2 changed files with 12 additions and 1 deletions

View file

@ -167,7 +167,7 @@ class Template:
try:
variables['value_json'] = json.loads(value)
except ValueError:
except (ValueError, TypeError):
pass
try:

View file

@ -4,6 +4,7 @@ from datetime import datetime
import unittest
import random
import math
import pytz
from unittest.mock import patch
from homeassistant.components import group
@ -422,6 +423,16 @@ class TestHelpersTemplate(unittest.TestCase):
assert '' == \
tpl.render_with_possible_json_value('{"hello": "world"}', '')
def test_render_with_possible_json_value_non_string_value(self):
"""Render with possible JSON value with non-string value."""
tpl = template.Template("""
{{ strptime(value~'+0000', '%Y-%m-%d %H:%M:%S%z') }}
""", self.hass)
value = datetime(2019, 1, 18, 12, 13, 14)
expected = str(pytz.utc.localize(value))
assert expected == \
tpl.render_with_possible_json_value(value)
def test_raise_exception_on_error(self):
"""Test raising an exception on error."""
with pytest.raises(TemplateError):