From 5fa8037231d30937144d8f3b3006a58f69210f8b Mon Sep 17 00:00:00 2001 From: Anders Melchiorsen Date: Mon, 17 Apr 2017 01:36:15 +0200 Subject: [PATCH] Always return True/False from is_state and is_state_attr (#7138) * Always return True/False from is_state and is_state_attr These functions are documented to always return True/False but the short-circuit evaluation would return None if the entity_id did not exist. * Reword into a single statement --- homeassistant/core.py | 5 +++-- tests/helpers/test_template.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/homeassistant/core.py b/homeassistant/core.py index 320e857ac9e..a467cf28e51 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -648,7 +648,7 @@ class StateMachine(object): Async friendly. """ state_obj = self.get(entity_id) - return state_obj and state_obj.state == state + return state_obj is not None and state_obj.state == state def is_state_attr(self, entity_id, name, value): """Test if entity exists and has a state attribute set to value. @@ -656,7 +656,8 @@ class StateMachine(object): Async friendly. """ state_obj = self.get(entity_id) - return state_obj and state_obj.attributes.get(name, None) == value + return state_obj is not None and \ + state_obj.attributes.get(name, None) == value def remove(self, entity_id): """Remove the state of an entity. diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index b6951172c64..71075124f32 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -314,6 +314,11 @@ class TestHelpersTemplate(unittest.TestCase): """, self.hass) self.assertEqual('yes', tpl.render()) + tpl = template.Template(""" +{{ is_state("test.noobject", "available") }} + """, self.hass) + self.assertEqual('False', tpl.render()) + def test_is_state_attr(self): """Test is_state_attr method.""" self.hass.states.set('test.object', 'available', {'mode': 'on'}) @@ -322,6 +327,11 @@ class TestHelpersTemplate(unittest.TestCase): """, self.hass) self.assertEqual('yes', tpl.render()) + tpl = template.Template(""" +{{ is_state_attr("test.noobject", "mode", "on") }} + """, self.hass) + self.assertEqual('False', tpl.render()) + def test_states_function(self): """Test using states as a function.""" self.hass.states.set('test.object', 'available')