From 2d5edeb1ef2f797957153e289f912d27ee022318 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sun, 11 Apr 2021 22:49:09 -0700 Subject: [PATCH] Set hass when adding template attribute (#49094) --- .../components/template/template_entity.py | 2 ++ .../template/test_template_entity.py | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/components/template/test_template_entity.py diff --git a/homeassistant/components/template/template_entity.py b/homeassistant/components/template/template_entity.py index f8909206dec..4f72511fe24 100644 --- a/homeassistant/components/template/template_entity.py +++ b/homeassistant/components/template/template_entity.py @@ -211,6 +211,8 @@ class TemplateEntity(Entity): if the template or validator resulted in an error. """ + assert self.hass is not None, "hass cannot be None" + template.hass = self.hass attribute = _TemplateAttribute( self, attribute, template, validator, on_update, none_on_template_error ) diff --git a/tests/components/template/test_template_entity.py b/tests/components/template/test_template_entity.py new file mode 100644 index 00000000000..ae812370d93 --- /dev/null +++ b/tests/components/template/test_template_entity.py @@ -0,0 +1,22 @@ +"""Test template entity.""" +import pytest + +from homeassistant.components.template import template_entity +from homeassistant.helpers import template + + +async def test_template_entity_requires_hass_set(): + """Test template entity requires hass to be set before accepting templates.""" + entity = template_entity.TemplateEntity() + + with pytest.raises(AssertionError): + entity.add_template_attribute("_hello", template.Template("Hello")) + + entity.hass = object() + entity.add_template_attribute("_hello", template.Template("Hello", None)) + + tpl_with_hass = template.Template("Hello", entity.hass) + entity.add_template_attribute("_hello", tpl_with_hass) + + # Because hass is set in `add_template_attribute`, both templates match `tpl_with_hass` + assert len(entity._template_attrs.get(tpl_with_hass, [])) == 2