Skip to content

Commit

Permalink
Cleanup unneeded assignment of hass property on MQTT Template objects (
Browse files Browse the repository at this point in the history
…home-assistant#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
  • Loading branch information
jbouwh authored Aug 12, 2024
1 parent 74a0907 commit 21987a6
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 44 deletions.
5 changes: 2 additions & 3 deletions homeassistant/components/mqtt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,7 @@ async def async_publish_service(call: ServiceCall) -> None:
# 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,
Expand Down Expand Up @@ -353,7 +352,7 @@ async def async_publish_service(call: ServiceCall) -> None:
},
)
payload = MqttCommandTemplate(
template.Template(payload_template), hass=hass
template.Template(payload_template, hass)
).async_render()

if TYPE_CHECKING:
Expand Down
19 changes: 1 addition & 18 deletions homeassistant/components/mqtt/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
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
Expand Down Expand Up @@ -159,22 +159,13 @@ def __init__(
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,
Expand Down Expand Up @@ -270,23 +261,15 @@ def __init__(
self,
value_template: template.Template | None,
*,
hass: HomeAssistant | None = None,
entity: Entity | None = None,
config_attributes: TemplateVarsType = None,
) -> None:
"""Instantiate a value template."""
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,
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/mqtt/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ def __init__(
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__(
Expand All @@ -136,8 +135,7 @@ async def async_update(self, discovery_data: MQTTDiscoveryPayload) -> None:
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()
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/mqtt/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion tests/components/mqtt/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'")
Expand Down
30 changes: 15 additions & 15 deletions tests/components/mqtt/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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"
Expand All @@ -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")
Expand All @@ -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) == (
Expand Down

0 comments on commit 21987a6

Please sign in to comment.