From f96e68cd11c72ab321bc1b7923bdfffd29f3bb11 Mon Sep 17 00:00:00 2001 From: Ashley Whetter Date: Tue, 10 Nov 2015 15:02:19 +0000 Subject: [PATCH] Made type inheritance a validation check for abstract references --- mongoengine/fields.py | 8 ++++++++ tests/fields/fields.py | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/mongoengine/fields.py b/mongoengine/fields.py index 13538c89..4c8c8498 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -996,6 +996,14 @@ class ReferenceField(BaseField): self.error('You can only reference documents once they have been ' 'saved to the database') + if self.document_type._meta.get('abstract') and \ + not isinstance(value, self.document_type): + self.error('%s is not an instance of abstract reference' + ' type %s' % (value._class_name, + self.document_type._class_name) + ) + + def lookup_member(self, member_name): return self.document_type._fields.get(member_name) diff --git a/tests/fields/fields.py b/tests/fields/fields.py index 860a5749..15daecb9 100644 --- a/tests/fields/fields.py +++ b/tests/fields/fields.py @@ -2331,6 +2331,31 @@ class FieldTest(unittest.TestCase): Sister.drop_collection() Brother.drop_collection() + def test_abstract_reference_base_type(self): + """Ensure that an an abstract reference fails validation when given a + Document that does not inherit from the abstract type. + """ + class Sibling(Document): + name = StringField() + meta = {"abstract": True} + + class Brother(Sibling): + sibling = ReferenceField(Sibling) + + class Mother(Document): + name = StringField() + + Brother.drop_collection() + Mother.drop_collection() + + mother = Mother(name="Carol") + mother.save() + brother = Brother(name="Bob", sibling=mother) + self.assertRaises(ValidationError, brother.save) + + Brother.drop_collection() + Mother.drop_collection() + def test_generic_reference(self): """Ensure that a GenericReferenceField properly dereferences items. """