Add bitwise operations as template helpers (#16833)

This commit is contained in:
Blake Blackshear 2018-09-26 04:57:16 -05:00 committed by Pascal Vizeli
parent 75c372021d
commit f13f723a04
2 changed files with 42 additions and 0 deletions

View file

@ -580,6 +580,16 @@ def regex_findall_index(value, find='', index=0, ignorecase=False):
return re.findall(find, value, flags)[index]
def bitwise_and(first_value, second_value):
"""Perform a bitwise and operation."""
return first_value & second_value
def bitwise_or(first_value, second_value):
"""Perform a bitwise or operation."""
return first_value | second_value
@contextfilter
def random_every_time(context, values):
"""Choose a random value.
@ -617,6 +627,8 @@ ENV.filters['regex_match'] = regex_match
ENV.filters['regex_replace'] = regex_replace
ENV.filters['regex_search'] = regex_search
ENV.filters['regex_findall_index'] = regex_findall_index
ENV.filters['bitwise_and'] = bitwise_and
ENV.filters['bitwise_or'] = bitwise_or
ENV.globals['log'] = logarithm
ENV.globals['sin'] = sine
ENV.globals['cos'] = cosine

View file

@ -562,6 +562,36 @@ class TestHelpersTemplate(unittest.TestCase):
""", self.hass)
self.assertEqual('LHR', tpl.render())
def test_bitwise_and(self):
"""Test bitwise_and method."""
tpl = template.Template("""
{{ 8 | bitwise_and(8) }}
""", self.hass)
self.assertEqual(str(8 & 8), tpl.render())
tpl = template.Template("""
{{ 10 | bitwise_and(2) }}
""", self.hass)
self.assertEqual(str(10 & 2), tpl.render())
tpl = template.Template("""
{{ 8 | bitwise_and(2) }}
""", self.hass)
self.assertEqual(str(8 & 2), tpl.render())
def test_bitwise_or(self):
"""Test bitwise_or method."""
tpl = template.Template("""
{{ 8 | bitwise_or(8) }}
""", self.hass)
self.assertEqual(str(8 | 8), tpl.render())
tpl = template.Template("""
{{ 10 | bitwise_or(2) }}
""", self.hass)
self.assertEqual(str(10 | 2), tpl.render())
tpl = template.Template("""
{{ 8 | bitwise_or(2) }}
""", self.hass)
self.assertEqual(str(8 | 2), tpl.render())
def test_distance_function_with_1_state(self):
"""Test distance function with 1 state."""
self.hass.states.set('test.object', 'happy', {