From 556f7e85fce9703bb3325af1534f861a01867f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastien=20G=C3=A9rard?= Date: Wed, 10 Oct 2018 23:13:34 +0200 Subject: [PATCH] Improve the error message that mentions that Document cant be subclassed --- mongoengine/base/metaclasses.py | 3 ++- tests/document/inheritance.py | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mongoengine/base/metaclasses.py b/mongoengine/base/metaclasses.py index 481408bf..ae191706 100644 --- a/mongoengine/base/metaclasses.py +++ b/mongoengine/base/metaclasses.py @@ -121,7 +121,8 @@ class DocumentMetaclass(type): # inheritance of classes where inheritance is set to False allow_inheritance = base._meta.get('allow_inheritance') if not allow_inheritance and not base._meta.get('abstract'): - raise ValueError('Document %s may not be subclassed' % + raise ValueError('Document %s may not be subclassed. ' + 'To enable inheritance, use the "allow_inheritance" meta attribute.' % base.__name__) # Get superclasses from last base superclass diff --git a/tests/document/inheritance.py b/tests/document/inheritance.py index b2ab1b52..2789ad8e 100644 --- a/tests/document/inheritance.py +++ b/tests/document/inheritance.py @@ -258,9 +258,10 @@ class InheritanceTest(unittest.TestCase): name = StringField() # can't inherit because Animal didn't explicitly allow inheritance - with self.assertRaises(ValueError): + with self.assertRaises(ValueError) as cm: class Dog(Animal): pass + self.assertIn("Document Animal may not be subclassed", str(cm.exception)) # Check that _cls etc aren't present on simple documents dog = Animal(name='dog').save() @@ -277,9 +278,10 @@ class InheritanceTest(unittest.TestCase): name = StringField() meta = {'allow_inheritance': True} - with self.assertRaises(ValueError): + with self.assertRaises(ValueError) as cm: class Mammal(Animal): meta = {'allow_inheritance': False} + self.assertEqual(str(cm.exception), 'Only direct subclasses of Document may set "allow_inheritance" to False') def test_allow_inheritance_abstract_document(self): """Ensure that abstract documents can set inheritance rules and that @@ -292,7 +294,7 @@ class InheritanceTest(unittest.TestCase): class Animal(FinalDocument): name = StringField() - with self.assertRaises(ValueError): + with self.assertRaises(ValueError) as cm: class Mammal(Animal): pass