From cc99a9b62a8b3282c53789bc11993ee07c230918 Mon Sep 17 00:00:00 2001 From: Troon Date: Wed, 8 May 2024 14:39:36 +0100 Subject: [PATCH] Add an add template filter (#109884) * Addition of add filter This change adds an `add` filter, the addition equivalent of the existing `multiply` filter. * Test for add filter * Update test_template.py * Update tests/helpers/test_template.py --------- Co-authored-by: Erik Montnemery --- homeassistant/helpers/template.py | 12 ++++++++++++ tests/helpers/test_template.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index de264760ff5..44b67f1c228 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1888,6 +1888,17 @@ def multiply(value, amount, default=_SENTINEL): return default +def add(value, amount, default=_SENTINEL): + """Filter to convert value to float and add it.""" + try: + return float(value) + amount + except (ValueError, TypeError): + # If value can't be converted to float + if default is _SENTINEL: + raise_no_default("add", value) + return default + + def logarithm(value, base=math.e, default=_SENTINEL): """Filter and function to get logarithm of the value with a specific base.""" try: @@ -2728,6 +2739,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.add_extension("jinja2.ext.loopcontrols") self.filters["round"] = forgiving_round self.filters["multiply"] = multiply + self.filters["add"] = add self.filters["log"] = logarithm self.filters["sin"] = sine self.filters["cos"] = cosine diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index ae9dcbe50d5..241a59f9b68 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -721,6 +721,25 @@ def test_multiply(hass: HomeAssistant) -> None: assert render(hass, "{{ 'no_number' | multiply(10, default=1) }}") == 1 +def test_add(hass: HomeAssistant) -> None: + """Test add.""" + tests = {10: 42} + + for inp, out in tests.items(): + assert ( + template.Template(f"{{{{ {inp} | add(32) | round }}}}", hass).async_render() + == out + ) + + # Test handling of invalid input + with pytest.raises(TemplateError): + template.Template("{{ abcd | add(10) }}", hass).async_render() + + # Test handling of default return value + assert render(hass, "{{ 'no_number' | add(10, 1) }}") == 1 + assert render(hass, "{{ 'no_number' | add(10, default=1) }}") == 1 + + def test_logarithm(hass: HomeAssistant) -> None: """Test logarithm.""" tests = [