diff options
| -rw-r--r-- | openstack/common/strutils.py | 15 | ||||
| -rw-r--r-- | tests/unit/test_strutils.py | 12 |
2 files changed, 21 insertions, 6 deletions
diff --git a/openstack/common/strutils.py b/openstack/common/strutils.py index fe8418e..d6dfb13 100644 --- a/openstack/common/strutils.py +++ b/openstack/common/strutils.py @@ -49,12 +49,15 @@ def bool_from_string(subject): Useful for JSON-decoded stuff and config file parsing """ - if isinstance(subject, bool): - return subject - if isinstance(subject, basestring): - if subject.strip().lower() in ('true', 'on', 'yes', '1'): - return True - return False + try: + # True or 1 or '1' -> True + # False or < 1 or > 1 or '0' -> False + return int(subject) == 1 + except TypeError: + # None -> False + return False + except ValueError: + return subject.strip().lower() in ('true', 'on', 'yes') def safe_decode(text, incoming=None, errors='strict'): diff --git a/tests/unit/test_strutils.py b/tests/unit/test_strutils.py index 1863c40..b0af958 100644 --- a/tests/unit/test_strutils.py +++ b/tests/unit/test_strutils.py @@ -48,6 +48,10 @@ class StrUtilsTest(utils.BaseTestCase): self.assertFalse(strutils.bool_from_string(c( 'This should not be True'))) + # Whitespace should be stripped + self.assertTrue(strutils.bool_from_string(c(' true '))) + self.assertFalse(strutils.bool_from_string(c(' false '))) + def test_bool_from_string(self): self._test_bool_from_string(lambda s: s) @@ -55,8 +59,16 @@ class StrUtilsTest(utils.BaseTestCase): self._test_bool_from_string(six.text_type) def test_other_bool_from_string(self): + self.assertFalse(strutils.bool_from_string(None)) self.assertFalse(strutils.bool_from_string(mock.Mock())) + def test_int_bool_from_string(self): + self.assertTrue(strutils.bool_from_string(1)) + + self.assertFalse(strutils.bool_from_string(-1)) + self.assertFalse(strutils.bool_from_string(0)) + self.assertFalse(strutils.bool_from_string(2)) + def test_int_from_bool_as_string(self): self.assertEqual(1, strutils.int_from_bool_as_string(True)) self.assertEqual(0, strutils.int_from_bool_as_string(False)) |
