Improve error message from InvalidDocumentError whenever an embedded document has a bad shape (e.g due to migration)

This commit is contained in:
Bastien Gérard
2019-10-28 22:05:13 +01:00
parent 178851589d
commit 8bf5370b6c
3 changed files with 31 additions and 2 deletions

View File

@@ -3656,6 +3656,29 @@ class TestInstance(MongoDBTestCase):
with self.assertRaises(DuplicateKeyError):
User.objects().select_related()
def test_embedded_document_failed_while_loading_instance_when_it_is_not_a_dict(
self
):
class LightSaber(EmbeddedDocument):
color = StringField()
class Jedi(Document):
light_saber = EmbeddedDocumentField(LightSaber)
coll = Jedi._get_collection()
Jedi(light_saber=LightSaber(color="red")).save()
_ = list(Jedi.objects) # Ensure a proper document loads without errors
# Forces a document with a wrong shape (may occur in case of migration)
coll.insert_one({"light_saber": "I_should_be_a_dict"})
with self.assertRaises(InvalidDocumentError) as cm:
list(Jedi.objects)
self.assertEqual(
str(cm.exception),
"Invalid data to create a `Jedi` instance.\nField 'light_saber' - The source SON object needs to be of type 'dict' but a '<type 'unicode'>' was found",
)
class ObjectKeyTestCase(MongoDBTestCase):
def test_object_key_simple_document(self):