From 21987a67e7c4d3c526ddfbd4866c64f93c2569f0 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Mon, 12 Aug 2024 19:20:21 +0200 Subject: [PATCH] Cleanup unneeded assignment of hass property on MQTT Template objects (#123706) * Cleanup unneeded assignment of hass property on MQTT Template objects * Commented out code and unneeded checks * Consistent assign hass to Template in mqtt tests * Remove unused hass attribute * Missed line --- homeassistant/components/mqtt/__init__.py | 5 ++-- homeassistant/components/mqtt/models.py | 19 +------------- homeassistant/components/mqtt/tag.py | 6 ++--- homeassistant/components/mqtt/trigger.py | 5 ++-- tests/components/mqtt/test_client.py | 2 +- tests/components/mqtt/test_init.py | 30 +++++++++++------------ 6 files changed, 23 insertions(+), 44 deletions(-) diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 5f7f1b1d330..013bd26e49c 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -303,8 +303,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: # has been deprecated with HA Core 2024.8.0 # and will be removed with HA Core 2025.2.0 rendered_topic: Any = MqttCommandTemplate( - template.Template(msg_topic_template), - hass=hass, + template.Template(msg_topic_template, hass), ).async_render() ir.async_create_issue( hass, @@ -353,7 +352,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: }, ) payload = MqttCommandTemplate( - template.Template(payload_template), hass=hass + template.Template(payload_template, hass) ).async_render() if TYPE_CHECKING: diff --git a/homeassistant/components/mqtt/models.py b/homeassistant/components/mqtt/models.py index c355510a5c2..f2b3165f66c 100644 --- a/homeassistant/components/mqtt/models.py +++ b/homeassistant/components/mqtt/models.py @@ -12,7 +12,7 @@ import logging from typing import TYPE_CHECKING, Any, TypedDict from homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME, Platform -from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback +from homeassistant.core import CALLBACK_TYPE, callback from homeassistant.exceptions import ServiceValidationError, TemplateError from homeassistant.helpers import template from homeassistant.helpers.entity import Entity @@ -159,22 +159,13 @@ class MqttCommandTemplate: self, command_template: template.Template | None, *, - hass: HomeAssistant | None = None, entity: Entity | None = None, ) -> None: """Instantiate a command template.""" self._template_state: template.TemplateStateFromEntityId | None = None self._command_template = command_template - if command_template is None: - return - self._entity = entity - command_template.hass = hass - - if entity: - command_template.hass = entity.hass - @callback def async_render( self, @@ -270,7 +261,6 @@ class MqttValueTemplate: self, value_template: template.Template | None, *, - hass: HomeAssistant | None = None, entity: Entity | None = None, config_attributes: TemplateVarsType = None, ) -> None: @@ -278,15 +268,8 @@ class MqttValueTemplate: self._template_state: template.TemplateStateFromEntityId | None = None self._value_template = value_template self._config_attributes = config_attributes - if value_template is None: - return - - value_template.hass = hass self._entity = entity - if entity: - value_template.hass = entity.hass - @callback def async_render_with_possible_json_value( self, diff --git a/homeassistant/components/mqtt/tag.py b/homeassistant/components/mqtt/tag.py index fbb0ea813c2..d5f5371c357 100644 --- a/homeassistant/components/mqtt/tag.py +++ b/homeassistant/components/mqtt/tag.py @@ -118,8 +118,7 @@ class MQTTTagScanner(MqttDiscoveryDeviceUpdateMixin): self.hass = hass self._sub_state: dict[str, EntitySubscription] | None = None self._value_template = MqttValueTemplate( - config.get(CONF_VALUE_TEMPLATE), - hass=self.hass, + config.get(CONF_VALUE_TEMPLATE) ).async_render_with_possible_json_value MqttDiscoveryDeviceUpdateMixin.__init__( @@ -136,8 +135,7 @@ class MQTTTagScanner(MqttDiscoveryDeviceUpdateMixin): return self._config = config self._value_template = MqttValueTemplate( - config.get(CONF_VALUE_TEMPLATE), - hass=self.hass, + config.get(CONF_VALUE_TEMPLATE) ).async_render_with_possible_json_value update_device(self.hass, self._config_entry, config) await self.subscribe_topics() diff --git a/homeassistant/components/mqtt/trigger.py b/homeassistant/components/mqtt/trigger.py index 91ac404a07a..3f7f03d7f19 100644 --- a/homeassistant/components/mqtt/trigger.py +++ b/homeassistant/components/mqtt/trigger.py @@ -60,10 +60,10 @@ async def async_attach_trigger( trigger_data: TriggerData = trigger_info["trigger_data"] command_template: Callable[ [PublishPayloadType, TemplateVarsType], PublishPayloadType - ] = MqttCommandTemplate(config.get(CONF_PAYLOAD), hass=hass).async_render + ] = MqttCommandTemplate(config.get(CONF_PAYLOAD)).async_render value_template: Callable[[ReceivePayloadType, str], ReceivePayloadType] value_template = MqttValueTemplate( - config.get(CONF_VALUE_TEMPLATE), hass=hass + config.get(CONF_VALUE_TEMPLATE) ).async_render_with_possible_json_value encoding: str | None = config[CONF_ENCODING] or None qos: int = config[CONF_QOS] @@ -75,7 +75,6 @@ async def async_attach_trigger( wanted_payload = command_template(None, variables) topic_template: Template = config[CONF_TOPIC] - topic_template.hass = hass topic = topic_template.async_render(variables, limited=True, parse_result=False) mqtt.util.valid_subscribe_topic(topic) diff --git a/tests/components/mqtt/test_client.py b/tests/components/mqtt/test_client.py index cd02d805e1c..c5887016f2e 100644 --- a/tests/components/mqtt/test_client.py +++ b/tests/components/mqtt/test_client.py @@ -225,7 +225,7 @@ async def test_publish( async def test_convert_outgoing_payload(hass: HomeAssistant) -> None: """Test the converting of outgoing MQTT payloads without template.""" - command_template = mqtt.MqttCommandTemplate(None, hass=hass) + command_template = mqtt.MqttCommandTemplate(None) assert command_template.async_render(b"\xde\xad\xbe\xef") == b"\xde\xad\xbe\xef" assert ( command_template.async_render("b'\\xde\\xad\\xbe\\xef'") diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 51379dc8508..f495c5ca585 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -89,12 +89,12 @@ async def test_command_template_value(hass: HomeAssistant) -> None: # test rendering value tpl = template.Template("{{ value + 1 }}", hass=hass) - cmd_tpl = mqtt.MqttCommandTemplate(tpl, hass=hass) + cmd_tpl = mqtt.MqttCommandTemplate(tpl) assert cmd_tpl.async_render(4321) == "4322" # test variables at rendering tpl = template.Template("{{ some_var }}", hass=hass) - cmd_tpl = mqtt.MqttCommandTemplate(tpl, hass=hass) + cmd_tpl = mqtt.MqttCommandTemplate(tpl) assert cmd_tpl.async_render(None, variables=variables) == "beer" @@ -161,8 +161,8 @@ async def test_command_template_variables( async def test_command_template_fails(hass: HomeAssistant) -> None: """Test the exception handling of an MQTT command template.""" - tpl = template.Template("{{ value * 2 }}") - cmd_tpl = mqtt.MqttCommandTemplate(tpl, hass=hass) + tpl = template.Template("{{ value * 2 }}", hass=hass) + cmd_tpl = mqtt.MqttCommandTemplate(tpl) with pytest.raises(MqttCommandTemplateException) as exc: cmd_tpl.async_render(None) assert "unsupported operand type(s) for *: 'NoneType' and 'int'" in str(exc.value) @@ -174,13 +174,13 @@ async def test_value_template_value(hass: HomeAssistant) -> None: variables = {"id": 1234, "some_var": "beer"} # test rendering value - tpl = template.Template("{{ value_json.id }}") - val_tpl = mqtt.MqttValueTemplate(tpl, hass=hass) + tpl = template.Template("{{ value_json.id }}", hass=hass) + val_tpl = mqtt.MqttValueTemplate(tpl) assert val_tpl.async_render_with_possible_json_value('{"id": 4321}') == "4321" # test variables at rendering - tpl = template.Template("{{ value_json.id }} {{ some_var }} {{ code }}") - val_tpl = mqtt.MqttValueTemplate(tpl, hass=hass, config_attributes={"code": 1234}) + tpl = template.Template("{{ value_json.id }} {{ some_var }} {{ code }}", hass=hass) + val_tpl = mqtt.MqttValueTemplate(tpl, config_attributes={"code": 1234}) assert ( val_tpl.async_render_with_possible_json_value( '{"id": 4321}', variables=variables @@ -189,8 +189,8 @@ async def test_value_template_value(hass: HomeAssistant) -> None: ) # test with default value if an error occurs due to an invalid template - tpl = template.Template("{{ value_json.id | as_datetime }}") - val_tpl = mqtt.MqttValueTemplate(tpl, hass=hass) + tpl = template.Template("{{ value_json.id | as_datetime }}", hass=hass) + val_tpl = mqtt.MqttValueTemplate(tpl) assert ( val_tpl.async_render_with_possible_json_value('{"otherid": 4321}', "my default") == "my default" @@ -200,19 +200,19 @@ async def test_value_template_value(hass: HomeAssistant) -> None: entity = Entity() entity.hass = hass entity.entity_id = "select.test" - tpl = template.Template("{{ value_json.id }}") + tpl = template.Template("{{ value_json.id }}", hass=hass) val_tpl = mqtt.MqttValueTemplate(tpl, entity=entity) assert val_tpl.async_render_with_possible_json_value('{"id": 4321}') == "4321" # test this object in a template - tpl2 = template.Template("{{ this.entity_id }}") + tpl2 = template.Template("{{ this.entity_id }}", hass=hass) val_tpl2 = mqtt.MqttValueTemplate(tpl2, entity=entity) assert val_tpl2.async_render_with_possible_json_value("bla") == "select.test" with patch( "homeassistant.helpers.template.TemplateStateFromEntityId", MagicMock() ) as template_state_calls: - tpl3 = template.Template("{{ this.entity_id }}") + tpl3 = template.Template("{{ this.entity_id }}", hass=hass) val_tpl3 = mqtt.MqttValueTemplate(tpl3, entity=entity) val_tpl3.async_render_with_possible_json_value("call1") val_tpl3.async_render_with_possible_json_value("call2") @@ -223,8 +223,8 @@ async def test_value_template_fails(hass: HomeAssistant) -> None: """Test the rendering of MQTT value template fails.""" entity = MockEntity(entity_id="sensor.test") entity.hass = hass - tpl = template.Template("{{ value_json.some_var * 2 }}") - val_tpl = mqtt.MqttValueTemplate(tpl, hass=hass, entity=entity) + tpl = template.Template("{{ value_json.some_var * 2 }}", hass=hass) + val_tpl = mqtt.MqttValueTemplate(tpl, entity=entity) with pytest.raises(MqttValueTemplateException) as exc: val_tpl.async_render_with_possible_json_value('{"some_var": null }') assert str(exc.value) == (