Remove unnecessary assignment of Template.hass from template (#123773)

This commit is contained in:
Erik Montnemery 2024-08-13 11:54:36 +02:00 committed by GitHub
parent 5837450a05
commit dc462aa529
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 39 additions and 32 deletions

View File

@ -108,7 +108,7 @@ async def _async_create_entities(hass, config):
alarm_control_panels = []
for object_id, entity_config in config[CONF_ALARM_CONTROL_PANELS].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
alarm_control_panels.append(

View File

@ -119,17 +119,21 @@ LEGACY_BINARY_SENSOR_SCHEMA = vol.All(
)
def rewrite_legacy_to_modern_conf(cfg: dict[str, dict]) -> list[dict]:
def rewrite_legacy_to_modern_conf(
hass: HomeAssistant, cfg: dict[str, dict]
) -> list[dict]:
"""Rewrite legacy binary sensor definitions to modern ones."""
sensors = []
for object_id, entity_cfg in cfg.items():
entity_cfg = {**entity_cfg, CONF_OBJECT_ID: object_id}
entity_cfg = rewrite_common_legacy_to_modern_conf(entity_cfg, LEGACY_FIELDS)
entity_cfg = rewrite_common_legacy_to_modern_conf(
hass, entity_cfg, LEGACY_FIELDS
)
if CONF_NAME not in entity_cfg:
entity_cfg[CONF_NAME] = template.Template(object_id)
entity_cfg[CONF_NAME] = template.Template(object_id, hass)
sensors.append(entity_cfg)
@ -183,7 +187,7 @@ async def async_setup_platform(
_async_create_template_tracking_entities(
async_add_entities,
hass,
rewrite_legacy_to_modern_conf(config[CONF_SENSORS]),
rewrite_legacy_to_modern_conf(hass, config[CONF_SENSORS]),
None,
)
return

View File

@ -115,7 +115,7 @@ async def async_validate_config(hass: HomeAssistant, config: ConfigType) -> Conf
)
definitions = list(cfg[new_key]) if new_key in cfg else []
definitions.extend(transform(cfg[old_key]))
definitions.extend(transform(hass, cfg[old_key]))
cfg = {**cfg, new_key: definitions}
config_sections.append(cfg)

View File

@ -106,7 +106,7 @@ async def _async_create_entities(hass, config):
covers = []
for object_id, entity_config in config[CONF_COVERS].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)

View File

@ -94,7 +94,7 @@ async def _async_create_entities(hass, config):
fans = []
for object_id, entity_config in config[CONF_FANS].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)

View File

@ -126,7 +126,7 @@ async def _async_create_entities(hass, config):
lights = []
for object_id, entity_config in config[CONF_LIGHTS].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
lights.append(

View File

@ -59,7 +59,7 @@ PLATFORM_SCHEMA = LOCK_PLATFORM_SCHEMA.extend(
async def _async_create_entities(hass, config):
"""Create the Template lock."""
config = rewrite_common_legacy_to_modern_conf(config)
config = rewrite_common_legacy_to_modern_conf(hass, config)
return [TemplateLock(hass, config, config.get(CONF_UNIQUE_ID))]

View File

@ -142,17 +142,21 @@ def extra_validation_checks(val):
return val
def rewrite_legacy_to_modern_conf(cfg: dict[str, dict]) -> list[dict]:
def rewrite_legacy_to_modern_conf(
hass: HomeAssistant, cfg: dict[str, dict]
) -> list[dict]:
"""Rewrite legacy sensor definitions to modern ones."""
sensors = []
for object_id, entity_cfg in cfg.items():
entity_cfg = {**entity_cfg, CONF_OBJECT_ID: object_id}
entity_cfg = rewrite_common_legacy_to_modern_conf(entity_cfg, LEGACY_FIELDS)
entity_cfg = rewrite_common_legacy_to_modern_conf(
hass, entity_cfg, LEGACY_FIELDS
)
if CONF_NAME not in entity_cfg:
entity_cfg[CONF_NAME] = template.Template(object_id)
entity_cfg[CONF_NAME] = template.Template(object_id, hass)
sensors.append(entity_cfg)
@ -210,7 +214,7 @@ async def async_setup_platform(
_async_create_template_tracking_entities(
async_add_entities,
hass,
rewrite_legacy_to_modern_conf(config[CONF_SENSORS]),
rewrite_legacy_to_modern_conf(hass, config[CONF_SENSORS]),
None,
)
return

View File

@ -76,7 +76,7 @@ async def _async_create_entities(hass, config):
switches = []
for object_id, entity_config in config[CONF_SWITCHES].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
switches.append(

View File

@ -123,7 +123,9 @@ LEGACY_FIELDS = {
def rewrite_common_legacy_to_modern_conf(
entity_cfg: dict[str, Any], extra_legacy_fields: dict[str, str] | None = None
hass: HomeAssistant,
entity_cfg: dict[str, Any],
extra_legacy_fields: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Rewrite legacy config."""
entity_cfg = {**entity_cfg}
@ -138,11 +140,11 @@ def rewrite_common_legacy_to_modern_conf(
val = entity_cfg.pop(from_key)
if isinstance(val, str):
val = Template(val)
val = Template(val, hass)
entity_cfg[to_key] = val
if CONF_NAME in entity_cfg and isinstance(entity_cfg[CONF_NAME], str):
entity_cfg[CONF_NAME] = Template(entity_cfg[CONF_NAME])
entity_cfg[CONF_NAME] = Template(entity_cfg[CONF_NAME], hass)
return entity_cfg
@ -310,7 +312,6 @@ class TemplateEntity(Entity):
# Try to render the name as it can influence the entity ID
self._attr_name = fallback_name
if self._friendly_name_template:
self._friendly_name_template.hass = hass
with contextlib.suppress(TemplateError):
self._attr_name = self._friendly_name_template.async_render(
variables=variables, parse_result=False
@ -319,14 +320,12 @@ class TemplateEntity(Entity):
# 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(
variables=variables, parse_result=False
)
if self._icon_template:
self._icon_template.hass = hass
with contextlib.suppress(TemplateError):
self._attr_icon = self._icon_template.async_render(
variables=variables, parse_result=False
@ -388,8 +387,10 @@ class TemplateEntity(Entity):
If True, the attribute will be set to None if the template errors.
"""
assert self.hass is not None, "hass cannot be None"
template.hass = self.hass
if self.hass is None:
raise ValueError("hass cannot be None")
if template.hass is None:
raise ValueError("template.hass cannot be None")
template_attribute = _TemplateAttribute(
self, attribute, template, validator, on_update, none_on_template_error
)

View File

@ -49,9 +49,7 @@ async def async_attach_trigger(
"""Listen for state changes based on configuration."""
trigger_data = trigger_info["trigger_data"]
value_template: Template = config[CONF_VALUE_TEMPLATE]
value_template.hass = hass
time_delta = config.get(CONF_FOR)
template.attach(hass, time_delta)
delay_cancel = None
job = HassJob(action)
armed = False

View File

@ -100,7 +100,7 @@ async def _async_create_entities(hass, config):
vacuums = []
for object_id, entity_config in config[CONF_VACUUMS].items():
entity_config = rewrite_common_legacy_to_modern_conf(entity_config)
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
vacuums.append(

View File

@ -153,7 +153,7 @@ async def async_setup_platform(
)
return
config = rewrite_common_legacy_to_modern_conf(config)
config = rewrite_common_legacy_to_modern_conf(hass, config)
unique_id = config.get(CONF_UNIQUE_ID)
async_add_entities(

View File

@ -244,7 +244,7 @@ async def test_template_syntax_error(
"platform": "template",
"panels": {
"test_template_panel": {
"name": "Template Alarm Panel",
"name": '{{ "Template Alarm Panel" }}',
"value_template": "disarmed",
**OPTIMISTIC_TEMPLATE_ALARM_CONFIG,
}

View File

@ -11,14 +11,14 @@ async def test_template_entity_requires_hass_set(hass: HomeAssistant) -> None:
"""Test template entity requires hass to be set before accepting templates."""
entity = template_entity.TemplateEntity(hass)
with pytest.raises(AssertionError):
with pytest.raises(ValueError, match="^hass cannot be None"):
entity.add_template_attribute("_hello", template.Template("Hello"))
entity.hass = object()
entity.add_template_attribute("_hello", template.Template("Hello", None))
with pytest.raises(ValueError, match="^template.hass cannot be None"):
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
assert len(entity._template_attrs.get(tpl_with_hass, [])) == 1