From e31558318e48a5734818360e9632239efdb1a762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastien=20G=C3=A9rard?= Date: Mon, 12 Nov 2018 23:12:35 +0100 Subject: [PATCH] BugFix - _cls not set in constructor #1950 --- docs/changelog.rst | 1 + mongoengine/base/document.py | 3 +++ tests/document/inheritance.py | 29 +++++++++++++++++++++++++---- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 47af2b1b..1e223aa1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -5,6 +5,7 @@ Changelog Development =========== - (Fill this out as you fix issues and develop your features). +- Fix `_cls` that is not set properly in Document constructor (regression) #1950 - Remove deprecated `save()` method and used `insert_one()` #1899 ================= diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index 348ab24b..11b3a49a 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -91,6 +91,9 @@ class BaseDocument(object): value = getattr(self, key, None) setattr(self, key, value) + if '_cls' not in values: + self._cls = self._class_name + # Set passed values after initialisation if self._dynamic: dynamic_data = {} diff --git a/tests/document/inheritance.py b/tests/document/inheritance.py index b4ba6058..32e3ed29 100644 --- a/tests/document/inheritance.py +++ b/tests/document/inheritance.py @@ -2,11 +2,11 @@ import unittest import warnings -from tests.fixtures import Base - -from mongoengine import Document, EmbeddedDocument, connect, ReferenceField,\ - BooleanField, GenericReferenceField, IntField, StringField +from mongoengine import (BooleanField, Document, EmbeddedDocument, + EmbeddedDocumentField, GenericReferenceField, + IntField, ReferenceField, StringField, connect) from mongoengine.connection import get_db +from tests.fixtures import Base __all__ = ('InheritanceTest', ) @@ -23,6 +23,27 @@ class InheritanceTest(unittest.TestCase): continue self.db.drop_collection(collection) + def test_constructor_cls(self): + # Ensures _cls is properly set during construction + # and when object gets reloaded (prevent regression of #1950) + class EmbedData(EmbeddedDocument): + data = StringField() + meta = {'allow_inheritance': True} + + class DataDoc(Document): + name = StringField() + embed = EmbeddedDocumentField(EmbedData) + meta = {'allow_inheritance': True} + + test_doc = DataDoc(name='test', embed=EmbedData(data='data')) + assert test_doc._cls == 'DataDoc' + assert test_doc.embed._cls == 'EmbedData' + test_doc.save() + saved_doc = DataDoc.objects.with_id(test_doc.id) + assert test_doc._cls == saved_doc._cls + assert test_doc.embed._cls == saved_doc.embed._cls + test_doc.delete() + def test_superclasses(self): """Ensure that the correct list of superclasses is assembled. """