Fix template sensor when name template doesn't render (#58088)

This commit is contained in:
Erik Montnemery 2021-10-20 23:53:06 +02:00 committed by GitHub
parent 4513ee4ea5
commit c1d671b817
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 4 deletions

View File

@ -245,6 +245,7 @@ class SensorTemplate(TemplateEntity, SensorEntity):
self._friendly_name_template = friendly_name_template
self._attr_name = None
# Try to render the name as it can influence the entity ID
if friendly_name_template:
friendly_name_template.hass = hass

View File

@ -115,7 +115,7 @@ async def test_entity_picture_template(hass, start_ha):
@pytest.mark.parametrize("count,domain", [(1, sensor.DOMAIN)])
@pytest.mark.parametrize(
"attribute,config",
"attribute,config,expected",
[
(
"friendly_name",
@ -130,6 +130,22 @@ async def test_entity_picture_template(hass, start_ha):
},
},
},
("It .", "It Works."),
),
(
"friendly_name",
{
"sensor": {
"platform": "template",
"sensors": {
"test_template_sensor": {
"value_template": "{{ states.sensor.test_state.state }}",
"friendly_name_template": "{{ 'It ' + states.sensor.test_state.state + '.'}}",
}
},
},
},
(None, "It Works."),
),
(
"friendly_name",
@ -144,6 +160,7 @@ async def test_entity_picture_template(hass, start_ha):
},
},
},
("It .", "It Works."),
),
(
"test_attribute",
@ -160,16 +177,17 @@ async def test_entity_picture_template(hass, start_ha):
},
},
},
("It .", "It Works."),
),
],
)
async def test_friendly_name_template(hass, attribute, start_ha):
async def test_friendly_name_template(hass, attribute, expected, start_ha):
"""Test friendly_name template with an unknown value_template."""
assert hass.states.get(TEST_NAME).attributes.get(attribute) == "It ."
assert hass.states.get(TEST_NAME).attributes.get(attribute) == expected[0]
hass.states.async_set("sensor.test_state", "Works")
await hass.async_block_till_done()
assert hass.states.get(TEST_NAME).attributes[attribute] == "It Works."
assert hass.states.get(TEST_NAME).attributes[attribute] == expected[1]
@pytest.mark.parametrize("count,domain", [(0, sensor.DOMAIN)])