diff --git a/cliquet/schema.py b/cliquet/schema.py index b409e9d6..d8ba96f7 100644 --- a/cliquet/schema.py +++ b/cliquet/schema.py @@ -47,10 +47,13 @@ class Options: * ``readonly_fields``: Fields that cannot be updated * ``unique_fields``: Fields that must have unique values for the user collection. + * ``preserve_unknown``: Define if unknown fields should be preserved + or not (default False). """ readonly_fields = ('id', 'last_modified') unique_fields = ('id', 'last_modified') + preserve_unknown = False def is_readonly(self, field): """Return True if specified field name is read-only. @@ -62,3 +65,10 @@ def is_readonly(self, field): :rtype: boolean """ return field in self.Options.readonly_fields + + def schema_type(self, **kw): + if self.Options.preserve_unknown is True: + unknown = 'preserve' + else: + unknown = 'ignore' + return colander.Mapping(unknown=unknown) diff --git a/cliquet/tests/test_schema.py b/cliquet/tests/test_schema.py index 7530a04e..bc127b19 100644 --- a/cliquet/tests/test_schema.py +++ b/cliquet/tests/test_schema.py @@ -25,3 +25,30 @@ def test_raises_invalid_if_no_scheme(self): self.assertRaises(colander.Invalid, schema.URL().deserialize, url) + + +class ResourceSchemaTest(unittest.TestCase): + + def test_preserves_unknown_fields_when_specified(self): + class PreserveSchema(schema.ResourceSchema): + class Options: + preserve_unknown = True + + schema_instance = PreserveSchema() + deserialized = schema_instance.deserialize({'foo': 'bar'}) + self.assertIn('foo', deserialized) + self.assertEquals(deserialized['foo'], 'bar') + + def test_ignore_unknwon_fields_when_specified(self): + class PreserveSchema(schema.ResourceSchema): + class Options: + preserve_unknown = False + + schema_instance = PreserveSchema() + deserialized = schema_instance.deserialize({'foo': 'bar'}) + self.assertNotIn('foo', deserialized) + + def test_ignore_unknwon_fields_by_default(self): + schema_instance = schema.ResourceSchema() + deserialized = schema_instance.deserialize({'foo': 'bar'}) + self.assertNotIn('foo', deserialized)