Now Raise an exception if subclasses are missing at querytime.

Beats returning None thanks to #aid for mentioning it on IRC
This commit is contained in:
Ross Lawley 2011-08-24 13:37:39 +01:00
parent dd49d1d4bb
commit 1631788ab6
3 changed files with 34 additions and 6 deletions

View File

@ -671,7 +671,6 @@ class BaseDocument(object):
# get the class name from the document, falling back to the given
# class if unavailable
class_name = son.get(u'_cls', cls._class_name)
data = dict((str(key), value) for key, value in son.items())
if '_types' in data:
@ -686,7 +685,11 @@ class BaseDocument(object):
if class_name not in subclasses:
# Type of document is probably more generic than the class
# that has been queried to return this SON
return None
raise NotRegistered("""
`%s` has not been registered in the document registry.
Importing the document class automatically registers it,
has it been imported?
""".strip() % class_name)
cls = subclasses[class_name]
present_fields = data.keys()

View File

@ -12,7 +12,7 @@ import weakref
from fixtures import Base, Mixin, PickleEmbedded, PickleTest
from mongoengine import *
from mongoengine.base import BaseField
from mongoengine.base import _document_registry, NotRegistered
from mongoengine.connection import _get_db
@ -740,7 +740,6 @@ class DocumentTest(unittest.TestCase):
post1.save()
BlogPost.drop_collection()
def test_geo_indexes_recursion(self):
class User(Document):
@ -799,7 +798,6 @@ class DocumentTest(unittest.TestCase):
post2 = BlogPost(title='test2', slug='test')
self.assertRaises(OperationError, post2.save)
def test_unique_with(self):
"""Ensure that unique_with constraints are applied to fields.
"""
@ -978,6 +976,32 @@ class DocumentTest(unittest.TestCase):
User.drop_collection()
def test_document_not_registered(self):
class Place(Document):
name = StringField()
class NicePlace(Place):
pass
Place.drop_collection()
Place(name="London").save()
NicePlace(name="Buckingham Palace").save()
# Mimic Place and NicePlace definitions being in a different file
# and the NicePlace model not being imported in at query time.
@classmethod
def _get_subclasses(cls):
return {}
Place._get_subclasses = _get_subclasses
def query_without_importing_nice_place():
print Place.objects.all()
self.assertRaises(NotRegistered, query_without_importing_nice_place)
def test_creation(self):
"""Ensure that document may be created using keyword arguments.
"""

View File

@ -1062,6 +1062,7 @@ class FieldTest(unittest.TestCase):
Post.drop_collection()
User.drop_collection()
def test_generic_reference_document_not_registered(self):
"""Ensure dereferencing out of the document registry throws a
`NotRegistered` error.
@ -1445,7 +1446,7 @@ class FieldTest(unittest.TestCase):
a.save()
self.assertEqual(a.counter, 2)
a = Animal.objects.first()
self.assertEqual(a.counter, 2)
a.reload()