From ddbcc8e84ba45539a01ab622161e28350268e327 Mon Sep 17 00:00:00 2001 From: Axel Haustant Date: Mon, 13 Apr 2015 18:48:42 +0200 Subject: [PATCH] Ensure meta.strict does not bypass constructor check --- mongoengine/base/document.py | 6 +++--- tests/fields/fields.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index 0ca3fcde..d31d75ba 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -70,9 +70,9 @@ class BaseDocument(object): signals.pre_init.send(self.__class__, document=self, values=values) - # Check if there are undefined fields supplied, if so raise an - # Exception. - if not self._dynamic and self._meta.get('strict', True): + # Check if there are undefined fields supplied to the constructor, + # if so raise an Exception. + if not self._dynamic and (self._meta.get('strict', True) or _created): for var in values.keys(): if var not in self._fields.keys() + ['id', 'pk', '_cls', '_text_score']: msg = ( diff --git a/tests/fields/fields.py b/tests/fields/fields.py index 887291db..f0a73951 100644 --- a/tests/fields/fields.py +++ b/tests/fields/fields.py @@ -3171,6 +3171,21 @@ class FieldTest(unittest.TestCase): self.assertRaises(FieldDoesNotExist, test) + def test_undefined_field_exception_with_strict(self): + """Tests if a `FieldDoesNotExist` exception is raised when trying to + instanciate a document with a field that's not defined, + even when strict is set to False. + """ + + class Doc(Document): + foo = StringField(db_field='f') + meta = {'strict': False} + + def test(): + Doc(bar='test') + + self.assertRaises(FieldDoesNotExist, test) + class EmbeddedDocumentListFieldTestCase(unittest.TestCase):