From bf6b9175a132d733b441b9ba1cf80f2709d65e3e Mon Sep 17 00:00:00 2001 From: Lars R Date: Wed, 10 Jan 2024 09:40:52 +0100 Subject: [PATCH] Add 'bitwise_xor' filter to jinja templates (#104942) Co-authored-by: Robert Resch --- homeassistant/helpers/template.py | 6 ++++++ tests/helpers/test_template.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index ac37360d5e2..db4e333fa1a 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2099,6 +2099,11 @@ def bitwise_or(first_value, second_value): return first_value | second_value +def bitwise_xor(first_value, second_value): + """Perform a bitwise xor operation.""" + return first_value ^ second_value + + def struct_pack(value: Any | None, format_string: str) -> bytes | None: """Pack an object into a bytes object.""" try: @@ -2462,6 +2467,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["regex_findall_index"] = regex_findall_index self.filters["bitwise_and"] = bitwise_and self.filters["bitwise_or"] = bitwise_or + self.filters["bitwise_xor"] = bitwise_xor self.filters["pack"] = struct_pack self.filters["unpack"] = struct_unpack self.filters["ord"] = ord diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index b70c9479abb..bf48199d419 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -2405,6 +2405,22 @@ def test_bitwise_or(hass: HomeAssistant) -> None: assert tpl.async_render() == 8 | 2 +@pytest.mark.parametrize( + ("value", "xor_value", "expected"), + [(8, 8, 0), (10, 2, 8), (0x8000, 0xFAFA, 31482), (True, False, 1), (True, True, 0)], +) +def test_bitwise_xor( + hass: HomeAssistant, value: Any, xor_value: Any, expected: int +) -> None: + """Test bitwise_xor method.""" + assert ( + template.Template("{{ value | bitwise_xor(xor_value) }}", hass).async_render( + {"value": value, "xor_value": xor_value} + ) + == expected + ) + + def test_pack(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None: """Test struct pack method."""