From 935e5c67a3e9892f9bc3611c8ee4efa629bedea4 Mon Sep 17 00:00:00 2001 From: Phil Bruckner Date: Sun, 20 Jan 2019 18:46:14 -0600 Subject: [PATCH] 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. --- homeassistant/helpers/template.py | 2 +- tests/helpers/test_template.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 267bf8853d9..03ae37843d8 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -167,7 +167,7 @@ class Template: try: variables['value_json'] = json.loads(value) - except ValueError: + except (ValueError, TypeError): pass try: diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 02331c400d3..3febd4037ad 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -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):