From d9b87ee5c5cb9e3911dbfc03ff9a7172f3ef046a Mon Sep 17 00:00:00 2001 From: avee87 <6134677+avee87@users.noreply.github.com> Date: Fri, 22 Oct 2021 19:09:54 +0100 Subject: [PATCH] Add warning when entity used in template doesn't exist (#57316) --- homeassistant/helpers/template.py | 7 ++++++- tests/helpers/test_template.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 6cfae98a2ac..ef66154ee91 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -831,7 +831,12 @@ def _get_state_if_valid(hass: HomeAssistant, entity_id: str) -> TemplateState | def _get_state(hass: HomeAssistant, entity_id: str) -> TemplateState | None: - return _get_template_state_from_state(hass, entity_id, hass.states.get(entity_id)) + state_obj = _get_template_state_from_state( + hass, entity_id, hass.states.get(entity_id) + ) + if state_obj is None: + _LOGGER.warning("Template warning: entity '%s' doesn't exist", entity_id) + return state_obj def _get_template_state_from_state( diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 305f8a6717b..c1f023071d0 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -3206,3 +3206,21 @@ async def test_undefined_variable(hass, caplog): "Template variable warning: 'no_such_variable' is undefined when rendering '{{ no_such_variable }}'" in caplog.text ) + + +async def test_missing_entity(hass, caplog): + """Test a warning is logged on missing entity.""" + hass.states.async_set("binary_sensor.active", "on") + valid_template = template.Template( + "{{ is_state('binary_sensor.active', 'on') }}", hass + ) + invalid_template = template.Template( + "{{ is_state('binary_sensor.abcde', 'on') }}", hass + ) + assert valid_template.async_render() is True + assert invalid_template.async_render() is False + assert ( + "Template warning: entity 'binary_sensor.active' doesn't exist" + not in caplog.text + ) + assert "Template warning: entity 'binary_sensor.abcde' doesn't exist" in caplog.text