Commits

Andy Mikhailenko committed ddbe168

Fix data manipulation: handle optional dictionaries correctly

  • Participants
  • Parent commits e0464a0

Comments (0)

Files changed (2)

monk/manipulation.py

     if value is not None and not isinstance(value, dict):
         # bogus value; will not pass validation but should be preserved
         return value
+    if spec.optional and value is None:
+        return None
     return merged(spec.inner_spec or {}, value or {})
 
 

unittests/test_manipulation.py

 import pytest
 
 from monk.compat import text_type as t
-from monk.schema import Rule
+from monk.schema import Rule, optional
 from monk.manipulation import merged
 
 
         data = {}
         expected = {'foo': 'bar'}
         assert merged(spec, data) == expected
+
+    def test_required_inside_optional_dict(self):
+        spec = {'foo': optional({'a': 1, 'b': optional(2)})}
+
+        data = {}
+        expected = {'foo': None}
+        assert merged(spec, data) == expected
+
+        data = {'foo': None}
+        expected = {'foo': None}
+        assert merged(spec, data) == expected
+
+        data = {'foo': {}}
+        expected = {'foo': {'a': 1, 'b': 2}}
+        assert merged(spec, data) == expected
+
+        data = {'foo': {'a': 3}}
+        expected = {'foo': {'a': 3, 'b': 2}}
+        assert merged(spec, data) == expected
+
+        data = {'foo': {'b': 3}}
+        expected = {'foo': {'a': 1, 'b': 3}}
+        assert merged(spec, data) == expected