Add is_state_attr method.

Returns True if the entity exists and has an attribute with the given
name and value.
This commit is contained in:
Andrew Thigpen 2015-12-31 14:58:18 -06:00
parent 326e26fbeb
commit 11f32d0500
4 changed files with 29 additions and 1 deletions

View file

@ -468,6 +468,13 @@ class StateMachine(object):
return (entity_id in self._states and
self._states[entity_id].state == state)
def is_state_attr(self, entity_id, name, value):
"""Test if entity exists and has a state attribute set to value."""
entity_id = entity_id.lower()
return (entity_id in self._states and
self._states[entity_id].attributes.get(name, None) == value)
def remove(self, entity_id):
"""Remove the state of an entity.

View file

@ -43,7 +43,8 @@ def render(hass, template, variables=None, **kwargs):
try:
return ENV.from_string(template, {
'states': AllStates(hass),
'is_state': hass.states.is_state
'is_state': hass.states.is_state,
'is_state_attr': hass.states.is_state_attr
}).render(kwargs).strip()
except jinja2.TemplateError as err:
raise TemplateError(err)

View file

@ -321,6 +321,18 @@ class TestStateMachine(unittest.TestCase):
self.assertFalse(self.states.is_state('light.Bowl', 'off'))
self.assertFalse(self.states.is_state('light.Non_existing', 'on'))
def test_is_state_attr(self):
""" Test is_state_attr method. """
self.states.set("light.Bowl", "on", {"brightness": 100})
self.assertTrue(
self.states.is_state_attr('light.Bowl', 'brightness', 100))
self.assertFalse(
self.states.is_state_attr('light.Bowl', 'friendly_name', 200))
self.assertFalse(
self.states.is_state_attr('light.Bowl', 'friendly_name', 'Bowl'))
self.assertFalse(
self.states.is_state_attr('light.Non_existing', 'brightness', 100))
def test_entity_ids(self):
""" Test get_entity_ids method. """
ent_ids = self.states.entity_ids()

View file

@ -117,6 +117,14 @@ class TestUtilTemplate(unittest.TestCase):
self.hass,
'{% if is_state("test.object", "available") %}yes{% else %}no{% endif %}'))
def test_is_state_attr(self):
self.hass.states.set('test.object', 'available', {'mode': 'on'})
self.assertEqual(
'yes',
template.render(
self.hass,
'{% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %}'))
def test_states_function(self):
self.hass.states.set('test.object', 'available')
self.assertEqual(