33import pytest
44from bson import InvalidDocument
55
6- from mongoengine import Document , EnumField , ValidationError
6+ from mongoengine import (
7+ DictField ,
8+ Document ,
9+ EnumField ,
10+ ListField ,
11+ ValidationError ,
12+ )
713from tests .utils import MongoDBTestCase , get_as_pymongo
814
915
@@ -21,6 +27,12 @@ class ModelWithEnum(Document):
2127 status = EnumField (Status )
2228
2329
30+ class ModelComplexEnum (Document ):
31+ status = EnumField (Status )
32+ statuses = ListField (EnumField (Status ))
33+ color_mapping = DictField (EnumField (Color ))
34+
35+
2436class TestStringEnumField (MongoDBTestCase ):
2537 def test_storage (self ):
2638 model = ModelWithEnum (status = Status .NEW ).save ()
@@ -101,6 +113,38 @@ def test_wrong_choices(self):
101113 with pytest .raises (ValueError , match = "Invalid choices" ):
102114 EnumField (Status , choices = [Status .DONE , Color .RED ])
103115
116+ def test_embedding_in_complex_field (self ):
117+ ModelComplexEnum .drop_collection ()
118+ model = ModelComplexEnum (
119+ status = "new" , statuses = ["new" ], color_mapping = {"red" : 1 }
120+ ).save ()
121+ assert model .status == Status .NEW
122+ assert model .statuses == [Status .NEW ]
123+ assert model .color_mapping == {"red" : Color .RED }
124+ model .reload ()
125+ assert model .status == Status .NEW
126+ assert model .statuses == [Status .NEW ]
127+ assert model .color_mapping == {"red" : Color .RED }
128+ model .status = "done"
129+ model .color_mapping = {"blue" : 2 }
130+ model .statuses = ["new" , "done" ]
131+ assert model .status == Status .DONE
132+ assert model .color_mapping == {"blue" : Color .BLUE }, model .color_mapping
133+ assert model .statuses == [Status .NEW , Status .DONE ], model .statuses
134+ model = model .save ().reload ()
135+ assert model .status == Status .DONE
136+ assert model .color_mapping == {"blue" : Color .BLUE }, model .color_mapping
137+ assert model .statuses == [Status .NEW , Status .DONE ], model .statuses
138+
139+ with pytest .raises (ValidationError , match = "must be one of ..Status" ):
140+ model .statuses = [1 ]
141+ model .save ()
142+
143+ model .statuses = ["done" ]
144+ model .color_mapping = {"blue" : "done" }
145+ with pytest .raises (ValidationError , match = "must be one of ..Color" ):
146+ model .save ()
147+
104148
105149class ModelWithColor (Document ):
106150 color = EnumField (Color , default = Color .RED )
@@ -124,10 +168,7 @@ def test_storage_enum_with_int(self):
124168 assert get_as_pymongo (model ) == {"_id" : model .id , "color" : 2 }
125169
126170 def test_validate_model (self ):
127- with pytest .raises (ValidationError , match = "Value must be one of" ):
128- ModelWithColor (color = 3 ).validate ()
129-
130- with pytest .raises (ValidationError , match = "Value must be one of" ):
171+ with pytest .raises (ValidationError , match = "must be one of ..Color" ):
131172 ModelWithColor (color = "wrong_type" ).validate ()
132173
133174
0 commit comments