Commits

Adam Lowry committed a7de761

Ensure that Dicts don't fail when set to non-dictlikes

Comments (0)

Files changed (2)

flatland/schema/containers.py

         fields = self.field_schema_mapping
         seen = set()
         converted = True
-        for key, value in pairs:
-            if key not in fields:
-                if policy != 'duck':
-                    raise KeyError(
-                        'Dict %r schema does not allow key %r' % (
-                            self.name, key))
-                continue
-            if dict.__contains__(self, key):
-                converted &= self[key].set(value)
-            else:
-                self[key] = el = fields[key]()
-                converted &= el.set(value)
-            seen.add(key)
+        try:
+            for key, value in pairs:
+                if key not in fields:
+                    if policy != 'duck':
+                        raise KeyError(
+                            'Dict %r schema does not allow key %r' % (
+                                self.name, key))
+                    continue
+                if dict.__contains__(self, key):
+                    converted &= self[key].set(value)
+                else:
+                    self[key] = el = fields[key]()
+                    converted &= el.set(value)
+                seen.add(key)
+        except ValueError:
+            return False
 
         if policy == 'strict':
             required = set(fields.iterkeys())

tests/schema/test_containers.py

         assert leaf.el(u'.') is root
 
         assert root.el([u'0', u'0']) is leaf
+
+
+def test_invalid_dict():
+    # Make sure Dict instantiation doesn't fail when set to a non-dictlike
+
+    schema = Dict.of(Integer.named('x'))
+    schema('foo')