Currently ForceDictType converts False on an empty string, but errors
out on None. Fixing, and updating unit tests.

Signed-off-by: Guido Trotter <[email protected]>
---
 lib/utils.py                  |    3 ++-
 test/ganeti.utils_unittest.py |    6 +++++-
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/lib/utils.py b/lib/utils.py
index ddf6882..9d04ed6 100644
--- a/lib/utils.py
+++ b/lib/utils.py
@@ -788,7 +788,8 @@ def ForceDictType(target, key_types, allowed_values=None):
 
     if ktype == constants.VTYPE_STRING:
       if not isinstance(target[key], basestring):
-        if isinstance(target[key], bool) and not target[key]:
+        if (target[key] is None or
+            isinstance(target[key], bool) and not target[key]):
           target[key] = ''
         else:
           msg = "'%s' (value %s) is not a valid string" % (key, target[key])
diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py
index 839838e..3b67f83 100755
--- a/test/ganeti.utils_unittest.py
+++ b/test/ganeti.utils_unittest.py
@@ -1519,7 +1519,6 @@ class TestForceDictType(unittest.TestCase):
     self.assertEqual(self._fdt({'a': '1'}), {'a': 1})
     self.assertEqual(self._fdt({'a': 1, 'b': 1}), {'a':1, 'b': True})
     self.assertEqual(self._fdt({'b': 1, 'c': 'foo'}), {'b': True, 'c': 'foo'})
-    self.assertEqual(self._fdt({'b': 1, 'c': False}), {'b': True, 'c': ''})
     self.assertEqual(self._fdt({'b': 'false'}), {'b': False})
     self.assertEqual(self._fdt({'b': 'False'}), {'b': False})
     self.assertEqual(self._fdt({'b': 'true'}), {'b': True})
@@ -1527,9 +1526,14 @@ class TestForceDictType(unittest.TestCase):
     self.assertEqual(self._fdt({'d': '4'}), {'d': 4})
     self.assertEqual(self._fdt({'d': '4M'}), {'d': 4})
 
+  def testEmptyStringConversion(self):
+    self.assertEqual(self._fdt({'c': False}), {'c': ''})
+    self.assertEqual(self._fdt({'c': None}), {'c': ''})
+
   def testErrors(self):
     self.assertRaises(errors.TypeEnforcementError, self._fdt, {'a': 'astring'})
     self.assertRaises(errors.TypeEnforcementError, self._fdt, {'c': True})
+    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'c': object()})
     self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': 'astring'})
     self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': '4 L'})
 
-- 
1.7.1

Reply via email to