Render icon and picture templates at setup (#64838)

pull/64853/head
Erik Montnemery 2022-01-24 16:40:50 +01:00 committed by GitHub
parent 2e25213101
commit 5622e45980
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 0 deletions

View File

@ -250,6 +250,20 @@ class TemplateEntity(Entity):
parse_result=False
)
# Templates will not render while the entity is unavailable, try to render the
# icon and picture templates.
if self._entity_picture_template:
self._entity_picture_template.hass = hass
with contextlib.suppress(TemplateError):
self._attr_entity_picture = self._entity_picture_template.async_render(
parse_result=False
)
if self._icon_template:
self._icon_template.hass = hass
with contextlib.suppress(TemplateError):
self._attr_icon = self._icon_template.async_render(parse_result=False)
@callback
def _update_available(self, result):
if isinstance(result, TemplateError):

View File

@ -853,6 +853,67 @@ async def test_template_validation_error(hass, caplog, start_ha):
assert state.attributes.get("icon") is None
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"config,domain,entity_id",
[
(
{
"binary_sensor": {
"platform": "template",
"sensors": {
"test": {
"availability_template": "{{ is_state('sensor.bla', 'available') }}",
"entity_picture_template": "{{ 'blib' + 'blub' }}",
"icon_template": "mdi:{{ 1+2 }}",
"friendly_name": "{{ 'My custom ' + 'sensor' }}",
"value_template": "{{ true }}",
},
},
},
},
binary_sensor.DOMAIN,
"binary_sensor.test",
),
(
{
"template": {
"binary_sensor": {
"availability": "{{ is_state('sensor.bla', 'available') }}",
"picture": "{{ 'blib' + 'blub' }}",
"icon": "mdi:{{ 1+2 }}",
"name": "{{ 'My custom ' + 'sensor' }}",
"state": "{{ true }}",
},
},
},
template.DOMAIN,
"binary_sensor.my_custom_sensor",
),
],
)
async def test_availability_icon_picture(hass, start_ha, entity_id):
"""Test name, icon and picture templates are rendered at setup."""
state = hass.states.get(entity_id)
assert state.state == "unavailable"
assert state.attributes == {
"entity_picture": "blibblub",
"friendly_name": "My custom sensor",
"icon": "mdi:3",
}
hass.states.async_set("sensor.bla", "available")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state.state == "on"
assert state.attributes == {
"entity_picture": "blibblub",
"friendly_name": "My custom sensor",
"icon": "mdi:3",
}
@pytest.mark.parametrize("count,domain", [(2, "template")])
@pytest.mark.parametrize(
"config",