-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtest_instance.py
3978 lines (3035 loc) · 121 KB
/
test_instance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import pickle
import unittest
import uuid
import weakref
from datetime import datetime
from unittest.mock import Mock
import bson
import pytest
from bson import DBRef, ObjectId
from pymongo.errors import DuplicateKeyError
from mongoengine import *
from mongoengine import signals
from mongoengine.base import (
_document_registry,
_undefined_document_delete_rules,
get_document,
)
from mongoengine.connection import get_db
from mongoengine.context_managers import query_counter, switch_db
from mongoengine.errors import (
FieldDoesNotExist,
InvalidDocumentError,
InvalidQueryError,
NotRegistered,
NotUniqueError,
SaveConditionError,
)
from mongoengine.mongodb_support import (
MONGODB_34,
MONGODB_36,
get_mongodb_version,
)
from mongoengine.pymongo_support import (
PYMONGO_VERSION,
list_collection_names,
)
from mongoengine.queryset import NULLIFY, Q
from tests import fixtures
from tests.fixtures import (
PickleDynamicEmbedded,
PickleDynamicTest,
PickleEmbedded,
PickleSignalsTest,
PickleTest,
)
from tests.utils import MongoDBTestCase, get_as_pymongo
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), "../fields/mongoengine.png")
class TestDocumentInstance(MongoDBTestCase):
def setUp(self):
class Job(EmbeddedDocument):
name = StringField()
years = IntField()
class Person(Document):
name = StringField()
age = IntField()
job = EmbeddedDocumentField(Job)
non_field = True
meta = {"allow_inheritance": True}
self.Person = Person
self.Job = Job
def tearDown(self):
for collection in list_collection_names(self.db):
self.db.drop_collection(collection)
def _assert_db_equal(self, docs):
assert list(self.Person._get_collection().find().sort("id")) == sorted(
docs, key=lambda doc: doc["_id"]
)
def _assert_has_instance(self, field, instance):
assert hasattr(field, "_instance")
assert field._instance is not None
if isinstance(field._instance, weakref.ProxyType):
assert field._instance.__eq__(instance)
else:
assert field._instance == instance
def test_capped_collection(self):
"""Ensure that capped collections work properly."""
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_documents": 10, "max_size": 4096}
Log.drop_collection()
# Ensure that the collection handles up to its maximum
for _ in range(10):
Log().save()
assert Log.objects.count() == 10
# Check that extra documents don't increase the size
Log().save()
assert Log.objects.count() == 10
options = Log.objects._collection.options()
assert options["capped"] is True
assert options["max"] == 10
assert options["size"] == 4096
# Check that the document cannot be redefined with different options
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_documents": 11}
# Accessing Document.objects creates the collection
with pytest.raises(InvalidCollectionError):
Log.objects
def test_capped_collection_default(self):
"""Ensure that capped collections defaults work properly."""
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_documents": 10}
Log.drop_collection()
# Create a doc to create the collection
Log().save()
options = Log.objects._collection.options()
assert options["capped"] is True
assert options["max"] == 10
assert options["size"] == 10 * 2**20
# Check that the document with default value can be recreated
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_documents": 10}
# Create the collection by accessing Document.objects
Log.objects
def test_capped_collection_no_max_size_problems(self):
"""Ensure that capped collections with odd max_size work properly.
MongoDB rounds up max_size to next multiple of 256, recreating a doc
with the same spec failed in mongoengine <0.10
"""
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_size": 10000}
Log.drop_collection()
# Create a doc to create the collection
Log().save()
options = Log.objects._collection.options()
assert options["capped"] is True
assert options["size"] >= 10000
# Check that the document with odd max_size value can be recreated
class Log(Document):
date = DateTimeField(default=datetime.now)
meta = {"max_size": 10000}
# Create the collection by accessing Document.objects
Log.objects
def test_repr(self):
"""Ensure that unicode representation works"""
class Article(Document):
title = StringField()
def __unicode__(self):
return self.title
doc = Article(title="привет мир")
assert "<Article: привет мир>" == repr(doc)
def test_repr_none(self):
"""Ensure None values are handled correctly."""
class Article(Document):
title = StringField()
def __str__(self):
return None
doc = Article(title="привет мир")
assert "<Article: None>" == repr(doc)
def test_queryset_resurrects_dropped_collection(self):
self.Person.drop_collection()
assert list(self.Person.objects()) == []
# Ensure works correctly with inhertited classes
class Actor(self.Person):
pass
Actor.objects()
self.Person.drop_collection()
assert list(Actor.objects()) == []
def test_polymorphic_references(self):
"""Ensure that the correct subclasses are returned from a query
when using references / generic references
"""
class Animal(Document):
meta = {"allow_inheritance": True}
class Fish(Animal):
pass
class Mammal(Animal):
pass
class Dog(Mammal):
pass
class Human(Mammal):
pass
class Zoo(Document):
animals = ListField(ReferenceField(Animal))
Zoo.drop_collection()
Animal.drop_collection()
Animal().save()
Fish().save()
Mammal().save()
Dog().save()
Human().save()
# Save a reference to each animal
zoo = Zoo(animals=Animal.objects)
zoo.save()
zoo.reload()
classes = [a.__class__ for a in Zoo.objects.first().animals]
assert classes == [Animal, Fish, Mammal, Dog, Human]
Zoo.drop_collection()
class Zoo(Document):
animals = ListField(GenericReferenceField())
# Save a reference to each animal
zoo = Zoo(animals=Animal.objects)
zoo.save()
zoo.reload()
classes = [a.__class__ for a in Zoo.objects.first().animals]
assert classes == [Animal, Fish, Mammal, Dog, Human]
def test_reference_inheritance(self):
class Stats(Document):
created = DateTimeField(default=datetime.now)
meta = {"allow_inheritance": False}
class CompareStats(Document):
generated = DateTimeField(default=datetime.now)
stats = ListField(ReferenceField(Stats))
Stats.drop_collection()
CompareStats.drop_collection()
list_stats = []
for i in range(10):
s = Stats()
s.save()
list_stats.append(s)
cmp_stats = CompareStats(stats=list_stats)
cmp_stats.save()
assert list_stats == CompareStats.objects.first().stats
def test_db_field_load(self):
"""Ensure we load data correctly from the right db field."""
class Person(Document):
name = StringField(required=True)
_rank = StringField(required=False, db_field="rank")
@property
def rank(self):
return self._rank or "Private"
Person.drop_collection()
Person(name="Jack", _rank="Corporal").save()
Person(name="Fred").save()
assert Person.objects.get(name="Jack").rank == "Corporal"
assert Person.objects.get(name="Fred").rank == "Private"
def test_db_embedded_doc_field_load(self):
"""Ensure we load embedded document data correctly."""
class Rank(EmbeddedDocument):
title = StringField(required=True)
class Person(Document):
name = StringField(required=True)
rank_ = EmbeddedDocumentField(Rank, required=False, db_field="rank")
@property
def rank(self):
if self.rank_ is None:
return "Private"
return self.rank_.title
Person.drop_collection()
Person(name="Jack", rank_=Rank(title="Corporal")).save()
Person(name="Fred").save()
assert Person.objects.get(name="Jack").rank == "Corporal"
assert Person.objects.get(name="Fred").rank == "Private"
def test_custom_id_field(self):
"""Ensure that documents may be created with custom primary keys."""
class User(Document):
username = StringField(primary_key=True)
name = StringField()
meta = {"allow_inheritance": True}
User.drop_collection()
assert User._fields["username"].db_field == "_id"
assert User._meta["id_field"] == "username"
User.objects.create(username="test", name="test user")
user = User.objects.first()
assert user.id == "test"
assert user.pk == "test"
user_dict = User.objects._collection.find_one()
assert user_dict["_id"] == "test"
def test_change_custom_id_field_in_subclass(self):
"""Subclasses cannot override which field is the primary key."""
class User(Document):
username = StringField(primary_key=True)
name = StringField()
meta = {"allow_inheritance": True}
with pytest.raises(ValueError, match="Cannot override primary key field"):
class EmailUser(User):
email = StringField(primary_key=True)
def test_custom_id_field_is_required(self):
"""Ensure the custom primary key field is required."""
class User(Document):
username = StringField(primary_key=True)
name = StringField()
with pytest.raises(ValidationError) as exc_info:
User(name="test").save()
assert "Field is required: ['username']" in str(exc_info.value)
def test_document_not_registered(self):
class Place(Document):
name = StringField()
meta = {"allow_inheritance": True}
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.
del _document_registry["Place.NicePlace"]
with pytest.raises(NotRegistered):
list(Place.objects.all())
def test_document_registry_regressions(self):
class Location(Document):
name = StringField()
meta = {"allow_inheritance": True}
class Area(Location):
location = ReferenceField("Location", dbref=True)
Location.drop_collection()
assert Area == get_document("Area")
assert Area == get_document("Location.Area")
def test_creation(self):
"""Ensure that document may be created using keyword arguments."""
person = self.Person(name="Test User", age=30)
assert person.name == "Test User"
assert person.age == 30
def test__qs_property_does_not_raise(self):
# ensures no regression of #2500
class MyDocument(Document):
pass
MyDocument.drop_collection()
object = MyDocument()
object._qs().insert([MyDocument()])
assert MyDocument.objects.count() == 1
def test_to_dbref(self):
"""Ensure that you can get a dbref of a document."""
person = self.Person(name="Test User", age=30)
with pytest.raises(OperationError):
person.to_dbref()
person.save()
person.to_dbref()
def test_key_like_attribute_access(self):
person = self.Person(age=30)
assert person["age"] == 30
with pytest.raises(KeyError):
person["unknown_attr"]
def test_save_abstract_document(self):
"""Saving an abstract document should fail."""
class Doc(Document):
name = StringField()
meta = {"abstract": True}
with pytest.raises(InvalidDocumentError):
Doc(name="aaa").save()
def test_reload(self):
"""Ensure that attributes may be reloaded."""
person = self.Person(name="Test User", age=20)
person.save()
person_obj = self.Person.objects.first()
person_obj.name = "Mr Test User"
person_obj.age = 21
person_obj.save()
assert person.name == "Test User"
assert person.age == 20
person.reload("age")
assert person.name == "Test User"
assert person.age == 21
person.reload()
assert person.name == "Mr Test User"
assert person.age == 21
person.reload()
assert person.name == "Mr Test User"
assert person.age == 21
def test_reload_sharded(self):
class Animal(Document):
superphylum = StringField()
meta = {"shard_key": ("superphylum",)}
Animal.drop_collection()
doc = Animal.objects.create(superphylum="Deuterostomia")
mongo_db = get_mongodb_version()
CMD_QUERY_KEY = "command" if mongo_db >= MONGODB_36 else "query"
with query_counter() as q:
doc.reload()
query_op = q.db.system.profile.find({"ns": "mongoenginetest.animal"})[0]
assert set(query_op[CMD_QUERY_KEY]["filter"].keys()) == {
"_id",
"superphylum",
}
def test_reload_sharded_with_db_field(self):
class Person(Document):
nationality = StringField(db_field="country")
meta = {"shard_key": ("nationality",)}
Person.drop_collection()
doc = Person.objects.create(nationality="Poland")
mongo_db = get_mongodb_version()
CMD_QUERY_KEY = "command" if mongo_db >= MONGODB_36 else "query"
with query_counter() as q:
doc.reload()
query_op = q.db.system.profile.find({"ns": "mongoenginetest.person"})[0]
assert set(query_op[CMD_QUERY_KEY]["filter"].keys()) == {"_id", "country"}
def test_reload_sharded_nested(self):
class SuperPhylum(EmbeddedDocument):
name = StringField()
class Animal(Document):
superphylum = EmbeddedDocumentField(SuperPhylum)
meta = {"shard_key": ("superphylum.name",)}
Animal.drop_collection()
doc = Animal(superphylum=SuperPhylum(name="Deuterostomia"))
doc.save()
doc.reload()
Animal.drop_collection()
def test_save_update_shard_key_routing(self):
"""Ensures updating a doc with a specified shard_key includes it in
the query.
"""
class Animal(Document):
is_mammal = BooleanField()
name = StringField()
meta = {"shard_key": ("is_mammal", "id")}
Animal.drop_collection()
doc = Animal(is_mammal=True, name="Dog")
doc.save()
mongo_db = get_mongodb_version()
with query_counter() as q:
doc.name = "Cat"
doc.save()
query_op = q.db.system.profile.find({"ns": "mongoenginetest.animal"})[0]
assert query_op["op"] == "update"
if mongo_db <= MONGODB_34:
assert set(query_op["query"].keys()) == {"_id", "is_mammal"}
else:
assert set(query_op["command"]["q"].keys()) == {"_id", "is_mammal"}
Animal.drop_collection()
def test_save_create_shard_key_routing(self):
"""Ensures inserting a doc with a specified shard_key includes it in
the query.
"""
class Animal(Document):
_id = UUIDField(binary=False, primary_key=True, default=uuid.uuid4)
is_mammal = BooleanField()
name = StringField()
meta = {"shard_key": ("is_mammal",)}
Animal.drop_collection()
doc = Animal(is_mammal=True, name="Dog")
with query_counter() as q:
doc.save()
query_op = q.db.system.profile.find({"ns": "mongoenginetest.animal"})[0]
assert query_op["op"] == "command"
assert query_op["command"]["findAndModify"] == "animal"
assert set(query_op["command"]["query"].keys()) == {"_id", "is_mammal"}
Animal.drop_collection()
def test_reload_with_changed_fields(self):
"""Ensures reloading will not affect changed fields"""
class User(Document):
name = StringField()
number = IntField()
User.drop_collection()
user = User(name="Bob", number=1).save()
user.name = "John"
user.number = 2
assert user._get_changed_fields() == ["name", "number"]
user.reload("number")
assert user._get_changed_fields() == ["name"]
user.save()
user.reload()
assert user.name == "John"
def test_reload_referencing(self):
"""Ensures reloading updates weakrefs correctly."""
class Embedded(EmbeddedDocument):
dict_field = DictField()
list_field = ListField()
class Doc(Document):
dict_field = DictField()
list_field = ListField()
embedded_field = EmbeddedDocumentField(Embedded)
Doc.drop_collection()
doc = Doc()
doc.dict_field = {"hello": "world"}
doc.list_field = ["1", 2, {"hello": "world"}]
embedded_1 = Embedded()
embedded_1.dict_field = {"hello": "world"}
embedded_1.list_field = ["1", 2, {"hello": "world"}]
doc.embedded_field = embedded_1
doc.save()
doc = doc.reload(10)
doc.list_field.append(1)
doc.dict_field["woot"] = "woot"
doc.embedded_field.list_field.append(1)
doc.embedded_field.dict_field["woot"] = "woot"
changed = doc._get_changed_fields()
assert changed == [
"list_field",
"dict_field.woot",
"embedded_field.list_field",
"embedded_field.dict_field.woot",
]
doc.save()
assert len(doc.list_field) == 4
doc = doc.reload(10)
assert doc._get_changed_fields() == []
assert len(doc.list_field) == 4
assert len(doc.dict_field) == 2
assert len(doc.embedded_field.list_field) == 4
assert len(doc.embedded_field.dict_field) == 2
doc.list_field.append(1)
doc.save()
doc.dict_field["extra"] = 1
doc = doc.reload(10, "list_field")
assert doc._get_changed_fields() == ["dict_field.extra"]
assert len(doc.list_field) == 5
assert len(doc.dict_field) == 3
assert len(doc.embedded_field.list_field) == 4
assert len(doc.embedded_field.dict_field) == 2
def test_reload_doesnt_exist(self):
class Foo(Document):
pass
f = Foo()
with pytest.raises(Foo.DoesNotExist):
f.reload()
f.save()
f.delete()
with pytest.raises(Foo.DoesNotExist):
f.reload()
def test_reload_of_non_strict_with_special_field_name(self):
"""Ensures reloading works for documents with meta strict is False."""
class Post(Document):
meta = {"strict": False}
title = StringField()
items = ListField()
Post.drop_collection()
Post._get_collection().insert_one(
{"title": "Items eclipse", "items": ["more lorem", "even more ipsum"]}
)
post = Post.objects.first()
post.reload()
assert post.title == "Items eclipse"
assert post.items == ["more lorem", "even more ipsum"]
def test_dictionary_access(self):
"""Ensure that dictionary-style field access works properly."""
person = self.Person(name="Test User", age=30, job=self.Job())
assert person["name"] == "Test User"
with pytest.raises(KeyError):
person.__getitem__("salary")
with pytest.raises(KeyError):
person.__setitem__("salary", 50)
person["name"] = "Another User"
assert person["name"] == "Another User"
# Length = length(assigned fields + id)
assert len(person) == 5
assert "age" in person
person.age = None
assert "age" not in person
assert "nationality" not in person
def test_embedded_document_to_mongo(self):
class Person(EmbeddedDocument):
name = StringField()
age = IntField()
meta = {"allow_inheritance": True}
class Employee(Person):
salary = IntField()
assert sorted(Person(name="Bob", age=35).to_mongo().keys()) == [
"_cls",
"age",
"name",
]
assert sorted(Employee(name="Bob", age=35, salary=0).to_mongo().keys()) == [
"_cls",
"age",
"name",
"salary",
]
def test_embedded_document_to_mongo_id(self):
class SubDoc(EmbeddedDocument):
id = StringField(required=True)
sub_doc = SubDoc(id="abc")
assert list(sub_doc.to_mongo().keys()) == ["id"]
def test_embedded_document(self):
"""Ensure that embedded documents are set up correctly."""
class Comment(EmbeddedDocument):
content = StringField()
assert "content" in Comment._fields
assert "id" not in Comment._fields
def test_embedded_document_instance(self):
"""Ensure that embedded documents can reference parent instance."""
class Embedded(EmbeddedDocument):
string = StringField()
class Doc(Document):
embedded_field = EmbeddedDocumentField(Embedded)
Doc.drop_collection()
doc = Doc(embedded_field=Embedded(string="Hi"))
self._assert_has_instance(doc.embedded_field, doc)
doc.save()
doc = Doc.objects.get()
self._assert_has_instance(doc.embedded_field, doc)
def test_embedded_document_complex_instance(self):
"""Ensure that embedded documents in complex fields can reference
parent instance.
"""
class Embedded(EmbeddedDocument):
string = StringField()
class Doc(Document):
embedded_field = ListField(EmbeddedDocumentField(Embedded))
Doc.drop_collection()
doc = Doc(embedded_field=[Embedded(string="Hi")])
self._assert_has_instance(doc.embedded_field[0], doc)
doc.save()
doc = Doc.objects.get()
self._assert_has_instance(doc.embedded_field[0], doc)
def test_embedded_document_complex_instance_no_use_db_field(self):
"""Ensure that use_db_field is propagated to list of Emb Docs."""
class Embedded(EmbeddedDocument):
string = StringField(db_field="s")
class Doc(Document):
embedded_field = ListField(EmbeddedDocumentField(Embedded))
d = (
Doc(embedded_field=[Embedded(string="Hi")])
.to_mongo(use_db_field=False)
.to_dict()
)
assert d["embedded_field"] == [{"string": "Hi"}]
def test_instance_is_set_on_setattr(self):
class Email(EmbeddedDocument):
email = EmailField()
class Account(Document):
email = EmbeddedDocumentField(Email)
Account.drop_collection()
acc = Account()
acc.email = Email(email="[email protected]")
self._assert_has_instance(acc._data["email"], acc)
acc.save()
acc1 = Account.objects.first()
self._assert_has_instance(acc1._data["email"], acc1)
def test_instance_is_set_on_setattr_on_embedded_document_list(self):
class Email(EmbeddedDocument):
email = EmailField()
class Account(Document):
emails = EmbeddedDocumentListField(Email)
Account.drop_collection()
acc = Account()
acc.emails = [Email(email="[email protected]")]
self._assert_has_instance(acc._data["emails"][0], acc)
acc.save()
acc1 = Account.objects.first()
self._assert_has_instance(acc1._data["emails"][0], acc1)
def test_save_checks_that_clean_is_called(self):
class CustomError(Exception):
pass
class TestDocument(Document):
def clean(self):
raise CustomError()
with pytest.raises(CustomError):
TestDocument().save()
TestDocument().save(clean=False)
def test_save_signal_pre_save_post_validation_makes_change_to_doc(self):
class BlogPost(Document):
content = StringField()
@classmethod
def pre_save_post_validation(cls, sender, document, **kwargs):
document.content = "checked"
signals.pre_save_post_validation.connect(
BlogPost.pre_save_post_validation, sender=BlogPost
)
BlogPost.drop_collection()
post = BlogPost(content="unchecked").save()
assert post.content == "checked"
# Make sure pre_save_post_validation changes makes it to the db
raw_doc = get_as_pymongo(post)
assert raw_doc == {"content": "checked", "_id": post.id}
# Important to disconnect as it could cause some assertions in test_signals
# to fail (due to the garbage collection timing of this signal)
signals.pre_save_post_validation.disconnect(BlogPost.pre_save_post_validation)
def test_document_clean(self):
class TestDocument(Document):
status = StringField()
cleaned = BooleanField(default=False)
def clean(self):
self.cleaned = True
TestDocument.drop_collection()
t = TestDocument(status="draft")
# Ensure clean=False prevent call to clean
t = TestDocument(status="published")
t.save(clean=False)
assert t.status == "published"
assert t.cleaned is False
t = TestDocument(status="published")
assert t.cleaned is False
t.save(clean=True)
assert t.status == "published"
assert t.cleaned is True
raw_doc = get_as_pymongo(t)
# Make sure clean changes makes it to the db
assert raw_doc == {"status": "published", "cleaned": True, "_id": t.id}
def test_document_embedded_clean(self):
class TestEmbeddedDocument(EmbeddedDocument):
x = IntField(required=True)
y = IntField(required=True)
z = IntField(required=True)
meta = {"allow_inheritance": False}
def clean(self):
if self.z:
if self.z != self.x + self.y:
raise ValidationError("Value of z != x + y")
else:
self.z = self.x + self.y
class TestDocument(Document):
doc = EmbeddedDocumentField(TestEmbeddedDocument)
status = StringField()
TestDocument.drop_collection()
t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25, z=15))
with pytest.raises(ValidationError) as exc_info:
t.save()
expected_msg = "Value of z != x + y"
assert expected_msg in str(exc_info.value)
assert exc_info.value.to_dict() == {"doc": {"__all__": expected_msg}}
t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25)).save()
assert t.doc.z == 35
# Asserts not raises
t = TestDocument(doc=TestEmbeddedDocument(x=15, y=35, z=5))
t.save(clean=False)
def test_modify_empty(self):
doc = self.Person(name="bob", age=10).save()
with pytest.raises(InvalidDocumentError):
self.Person().modify(set__age=10)
self._assert_db_equal([dict(doc.to_mongo())])
def test_modify_invalid_query(self):
doc1 = self.Person(name="bob", age=10).save()
doc2 = self.Person(name="jim", age=20).save()
docs = [dict(doc1.to_mongo()), dict(doc2.to_mongo())]
with pytest.raises(InvalidQueryError):
doc1.modify({"id": doc2.id}, set__value=20)
self._assert_db_equal(docs)
def test_modify_match_another_document(self):
doc1 = self.Person(name="bob", age=10).save()
doc2 = self.Person(name="jim", age=20).save()
docs = [dict(doc1.to_mongo()), dict(doc2.to_mongo())]
n_modified = doc1.modify({"name": doc2.name}, set__age=100)
assert n_modified == 0
self._assert_db_equal(docs)
def test_modify_not_exists(self):
doc1 = self.Person(name="bob", age=10).save()
doc2 = self.Person(id=ObjectId(), name="jim", age=20)
docs = [dict(doc1.to_mongo())]
n_modified = doc2.modify({"name": doc2.name}, set__age=100)
assert n_modified == 0
self._assert_db_equal(docs)
def test_modify_update(self):
other_doc = self.Person(name="bob", age=10).save()
doc = self.Person(
name="jim", age=20, job=self.Job(name="10gen", years=3)
).save()
doc_copy = doc._from_son(doc.to_mongo())
# these changes must go away
doc.name = "liza"
doc.job.name = "Google"
doc.job.years = 3
n_modified = doc.modify(
set__age=21, set__job__name="MongoDB", unset__job__years=True
)
assert n_modified == 1
doc_copy.age = 21
doc_copy.job.name = "MongoDB"
del doc_copy.job.years
assert doc.to_json() == doc_copy.to_json()
assert doc._get_changed_fields() == []
self._assert_db_equal([dict(other_doc.to_mongo()), dict(doc.to_mongo())])
def test_modify_with_positional_push(self):
class Content(EmbeddedDocument):
keywords = ListField(StringField())
class BlogPost(Document):
tags = ListField(StringField())
content = EmbeddedDocumentField(Content)