-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathtest_collection.py
2309 lines (1912 loc) · 94 KB
/
test_collection.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
# Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test the collection module."""
from __future__ import annotations
import asyncio
import contextlib
import re
import sys
from codecs import utf_8_decode
from collections import defaultdict
from typing import Any, Iterable, no_type_check
from pymongo.asynchronous.database import AsyncDatabase
sys.path[0:0] = [""]
from test import unittest
from test.asynchronous import ( # TODO: fix sync imports in PYTHON-4528
AsyncIntegrationTest,
AsyncUnitTest,
async_client_context,
)
from test.utils import (
IMPOSSIBLE_WRITE_CONCERN,
EventListener,
OvertCommandListener,
async_get_pool,
async_is_mongos,
async_wait_until,
wait_until,
)
from bson import encode
from bson.codec_options import CodecOptions
from bson.objectid import ObjectId
from bson.raw_bson import RawBSONDocument
from bson.regex import Regex
from bson.son import SON
from pymongo import ASCENDING, DESCENDING, GEO2D, GEOSPHERE, HASHED, TEXT
from pymongo.asynchronous.collection import AsyncCollection, ReturnDocument
from pymongo.asynchronous.command_cursor import AsyncCommandCursor
from pymongo.asynchronous.helpers import anext
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from pymongo.bulk_shared import BulkWriteError
from pymongo.cursor_shared import CursorType
from pymongo.errors import (
ConfigurationError,
DocumentTooLarge,
DuplicateKeyError,
ExecutionTimeout,
InvalidDocument,
InvalidName,
InvalidOperation,
NetworkTimeout,
OperationFailure,
WriteConcernError,
)
from pymongo.message import _COMMAND_OVERHEAD, _gen_find_command
from pymongo.operations import *
from pymongo.read_concern import DEFAULT_READ_CONCERN
from pymongo.read_preferences import ReadPreference
from pymongo.results import (
DeleteResult,
InsertManyResult,
InsertOneResult,
UpdateResult,
)
from pymongo.write_concern import WriteConcern
_IS_SYNC = False
class TestCollectionNoConnect(AsyncUnitTest):
"""Test Collection features on a client that does not connect."""
db: AsyncDatabase
client: AsyncMongoClient
@classmethod
async def _setup_class(cls):
cls.client = AsyncMongoClient(connect=False)
cls.db = cls.client.pymongo_test
@classmethod
async def _tearDown_class(cls):
await cls.client.close()
def test_collection(self):
self.assertRaises(TypeError, AsyncCollection, self.db, 5)
def make_col(base, name):
return base[name]
self.assertRaises(InvalidName, make_col, self.db, "")
self.assertRaises(InvalidName, make_col, self.db, "te$t")
self.assertRaises(InvalidName, make_col, self.db, ".test")
self.assertRaises(InvalidName, make_col, self.db, "test.")
self.assertRaises(InvalidName, make_col, self.db, "tes..t")
self.assertRaises(InvalidName, make_col, self.db.test, "")
self.assertRaises(InvalidName, make_col, self.db.test, "te$t")
self.assertRaises(InvalidName, make_col, self.db.test, ".test")
self.assertRaises(InvalidName, make_col, self.db.test, "test.")
self.assertRaises(InvalidName, make_col, self.db.test, "tes..t")
self.assertRaises(InvalidName, make_col, self.db.test, "tes\x00t")
def test_getattr(self):
coll = self.db.test
self.assertTrue(isinstance(coll["_does_not_exist"], AsyncCollection))
with self.assertRaises(AttributeError) as context:
coll._does_not_exist
# Message should be:
# "AttributeError: Collection has no attribute '_does_not_exist'. To
# access the test._does_not_exist collection, use
# database['test._does_not_exist']."
self.assertIn("has no attribute '_does_not_exist'", str(context.exception))
coll2 = coll.with_options(write_concern=WriteConcern(w=0))
self.assertEqual(coll2.write_concern, WriteConcern(w=0))
self.assertNotEqual(coll.write_concern, coll2.write_concern)
coll3 = coll2.subcoll
self.assertEqual(coll2.write_concern, coll3.write_concern)
coll4 = coll2["subcoll"]
self.assertEqual(coll2.write_concern, coll4.write_concern)
def test_iteration(self):
coll = self.db.coll
if "PyPy" in sys.version and sys.version_info < (3, 8, 15):
msg = "'NoneType' object is not callable"
else:
if _IS_SYNC:
msg = "'Collection' object is not iterable"
else:
msg = "'AsyncCollection' object is not iterable"
# Iteration fails
with self.assertRaisesRegex(TypeError, msg):
for _ in coll: # type: ignore[misc] # error: "None" not callable [misc]
break
# Non-string indices will start failing in PyMongo 5.
self.assertEqual(coll[0].name, "coll.0")
self.assertEqual(coll[{}].name, "coll.{}")
# next fails
with self.assertRaisesRegex(TypeError, msg):
_ = next(coll)
# .next() fails
with self.assertRaisesRegex(TypeError, msg):
_ = coll.next()
# Do not implement typing.Iterable.
self.assertNotIsInstance(coll, Iterable)
class AsyncTestCollection(AsyncIntegrationTest):
w: int
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.w = async_client_context.w # type: ignore
@classmethod
def tearDownClass(cls):
if _IS_SYNC:
cls.db.drop_collection("test_large_limit") # type: ignore[unused-coroutine]
else:
asyncio.run(cls.async_tearDownClass())
@classmethod
async def async_tearDownClass(cls):
await cls.db.drop_collection("test_large_limit")
async def asyncSetUp(self):
await self.db.test.drop()
async def asyncTearDown(self):
await self.db.test.drop()
@contextlib.contextmanager
def write_concern_collection(self):
if async_client_context.is_rs:
with self.assertRaises(WriteConcernError):
# Unsatisfiable write concern.
yield AsyncCollection(
self.db,
"test",
write_concern=WriteConcern(w=len(async_client_context.nodes) + 1),
)
else:
yield self.db.test
async def test_equality(self):
self.assertTrue(isinstance(self.db.test, AsyncCollection))
self.assertEqual(self.db.test, self.db["test"])
self.assertEqual(self.db.test, AsyncCollection(self.db, "test"))
self.assertEqual(self.db.test.mike, self.db["test.mike"])
self.assertEqual(self.db.test["mike"], self.db["test.mike"])
async def test_hashable(self):
self.assertIn(self.db.test.mike, {self.db["test.mike"]})
async def test_create(self):
# No Exception.
db = async_client_context.client.pymongo_test
await db.create_test_no_wc.drop()
async def lambda_test():
return "create_test_no_wc" not in await db.list_collection_names()
async def lambda_test_2():
return "create_test_no_wc" in await db.list_collection_names()
await async_wait_until(
lambda_test,
"drop create_test_no_wc collection",
)
await db.create_collection("create_test_no_wc")
await async_wait_until(
lambda_test_2,
"create create_test_no_wc collection",
)
# SERVER-33317
if not async_client_context.is_mongos or not async_client_context.version.at_least(3, 7, 0):
with self.assertRaises(OperationFailure):
await db.create_collection("create-test-wc", write_concern=IMPOSSIBLE_WRITE_CONCERN)
async def test_drop_nonexistent_collection(self):
await self.db.drop_collection("test")
self.assertFalse("test" in await self.db.list_collection_names())
# No exception
await self.db.drop_collection("test")
async def test_create_indexes(self):
db = self.db
with self.assertRaises(TypeError):
await db.test.create_indexes("foo") # type: ignore[arg-type]
with self.assertRaises(TypeError):
await db.test.create_indexes(["foo"]) # type: ignore[list-item]
self.assertRaises(TypeError, IndexModel, 5)
self.assertRaises(ValueError, IndexModel, [])
await db.test.drop_indexes()
await db.test.insert_one({})
self.assertEqual(len(await db.test.index_information()), 1)
await db.test.create_indexes([IndexModel("hello")])
await db.test.create_indexes([IndexModel([("hello", DESCENDING), ("world", ASCENDING)])])
# Tuple instead of list.
await db.test.create_indexes([IndexModel((("world", ASCENDING),))])
self.assertEqual(len(await db.test.index_information()), 4)
await db.test.drop_indexes()
names = await db.test.create_indexes(
[IndexModel([("hello", DESCENDING), ("world", ASCENDING)], name="hello_world")]
)
self.assertEqual(names, ["hello_world"])
await db.test.drop_indexes()
self.assertEqual(len(await db.test.index_information()), 1)
await db.test.create_indexes([IndexModel("hello")])
self.assertTrue("hello_1" in await db.test.index_information())
await db.test.drop_indexes()
self.assertEqual(len(await db.test.index_information()), 1)
names = await db.test.create_indexes(
[IndexModel([("hello", DESCENDING), ("world", ASCENDING)]), IndexModel("hello")]
)
info = await db.test.index_information()
for name in names:
self.assertTrue(name in info)
await db.test.drop()
await db.test.insert_one({"a": 1})
await db.test.insert_one({"a": 1})
with self.assertRaises(DuplicateKeyError):
await db.test.create_indexes([IndexModel("a", unique=True)])
with self.write_concern_collection() as coll:
await coll.create_indexes([IndexModel("hello")])
@async_client_context.require_version_max(4, 3, -1)
async def test_create_indexes_commitQuorum_requires_44(self):
db = self.db
with self.assertRaisesRegex(
ConfigurationError,
r"Must be connected to MongoDB 4\.4\+ to use the commitQuorum option for createIndexes",
):
await db.coll.create_indexes([IndexModel("a")], commitQuorum="majority")
@async_client_context.require_no_standalone
@async_client_context.require_version_min(4, 4, -1)
async def test_create_indexes_commitQuorum(self):
await self.db.coll.create_indexes([IndexModel("a")], commitQuorum="majority")
async def test_create_index(self):
db = self.db
with self.assertRaises(TypeError):
await db.test.create_index(5) # type: ignore[arg-type]
with self.assertRaises(ValueError):
await db.test.create_index([])
await db.test.drop_indexes()
await db.test.insert_one({})
self.assertEqual(len(await db.test.index_information()), 1)
await db.test.create_index("hello")
await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)])
# Tuple instead of list.
await db.test.create_index((("world", ASCENDING),))
self.assertEqual(len(await db.test.index_information()), 4)
await db.test.drop_indexes()
ix = await db.test.create_index(
[("hello", DESCENDING), ("world", ASCENDING)], name="hello_world"
)
self.assertEqual(ix, "hello_world")
await db.test.drop_indexes()
self.assertEqual(len(await db.test.index_information()), 1)
await db.test.create_index("hello")
self.assertTrue("hello_1" in await db.test.index_information())
await db.test.drop_indexes()
self.assertEqual(len(await db.test.index_information()), 1)
await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)])
self.assertTrue("hello_-1_world_1" in await db.test.index_information())
await db.test.drop_indexes()
await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], name=None)
self.assertTrue("hello_-1_world_1" in await db.test.index_information())
await db.test.drop()
await db.test.insert_one({"a": 1})
await db.test.insert_one({"a": 1})
with self.assertRaises(DuplicateKeyError):
await db.test.create_index("a", unique=True)
with self.write_concern_collection() as coll:
await coll.create_index([("hello", DESCENDING)])
await db.test.create_index(["hello", "world"])
await db.test.create_index(["hello", ("world", DESCENDING)])
await db.test.create_index({"hello": 1}.items()) # type:ignore[arg-type]
async def test_drop_index(self):
db = self.db
await db.test.drop_indexes()
await db.test.create_index("hello")
name = await db.test.create_index("goodbye")
self.assertEqual(len(await db.test.index_information()), 3)
self.assertEqual(name, "goodbye_1")
await db.test.drop_index(name)
# Drop it again.
with self.assertRaises(OperationFailure):
await db.test.drop_index(name)
self.assertEqual(len(await db.test.index_information()), 2)
self.assertTrue("hello_1" in await db.test.index_information())
await db.test.drop_indexes()
await db.test.create_index("hello")
name = await db.test.create_index("goodbye")
self.assertEqual(len(await db.test.index_information()), 3)
self.assertEqual(name, "goodbye_1")
await db.test.drop_index([("goodbye", ASCENDING)])
self.assertEqual(len(await db.test.index_information()), 2)
self.assertTrue("hello_1" in await db.test.index_information())
with self.write_concern_collection() as coll:
await coll.drop_index("hello_1")
@async_client_context.require_no_mongos
@async_client_context.require_test_commands
async def test_index_management_max_time_ms(self):
coll = self.db.test
await self.client.admin.command(
"configureFailPoint", "maxTimeAlwaysTimeOut", mode="alwaysOn"
)
try:
with self.assertRaises(ExecutionTimeout):
await coll.create_index("foo", maxTimeMS=1)
with self.assertRaises(ExecutionTimeout):
await coll.create_indexes([IndexModel("foo")], maxTimeMS=1)
with self.assertRaises(ExecutionTimeout):
await coll.drop_index("foo", maxTimeMS=1)
with self.assertRaises(ExecutionTimeout):
await coll.drop_indexes(maxTimeMS=1)
finally:
await self.client.admin.command(
"configureFailPoint", "maxTimeAlwaysTimeOut", mode="off"
)
async def test_list_indexes(self):
db = self.db
await db.test.drop()
await db.test.insert_one({}) # create collection
def map_indexes(indexes):
return {index["name"]: index for index in indexes}
indexes = await (await db.test.list_indexes()).to_list()
self.assertEqual(len(indexes), 1)
self.assertTrue("_id_" in map_indexes(indexes))
await db.test.create_index("hello")
indexes = await (await db.test.list_indexes()).to_list()
self.assertEqual(len(indexes), 2)
self.assertEqual(map_indexes(indexes)["hello_1"]["key"], SON([("hello", ASCENDING)]))
await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True)
indexes = await (await db.test.list_indexes()).to_list()
self.assertEqual(len(indexes), 3)
index_map = map_indexes(indexes)
self.assertEqual(
index_map["hello_-1_world_1"]["key"], SON([("hello", DESCENDING), ("world", ASCENDING)])
)
self.assertEqual(True, index_map["hello_-1_world_1"]["unique"])
# List indexes on a collection that does not exist.
indexes = await (await db.does_not_exist.list_indexes()).to_list()
self.assertEqual(len(indexes), 0)
# List indexes on a database that does not exist.
indexes = await (await db.does_not_exist.list_indexes()).to_list()
self.assertEqual(len(indexes), 0)
async def test_index_info(self):
db = self.db
await db.test.drop()
await db.test.insert_one({}) # create collection
self.assertEqual(len(await db.test.index_information()), 1)
self.assertTrue("_id_" in await db.test.index_information())
await db.test.create_index("hello")
self.assertEqual(len(await db.test.index_information()), 2)
self.assertEqual(
(await db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)]
)
await db.test.create_index([("hello", DESCENDING), ("world", ASCENDING)], unique=True)
self.assertEqual(
(await db.test.index_information())["hello_1"]["key"], [("hello", ASCENDING)]
)
self.assertEqual(len(await db.test.index_information()), 3)
self.assertEqual(
[("hello", DESCENDING), ("world", ASCENDING)],
(await db.test.index_information())["hello_-1_world_1"]["key"],
)
self.assertEqual(True, (await db.test.index_information())["hello_-1_world_1"]["unique"])
async def test_index_geo2d(self):
db = self.db
await db.test.drop_indexes()
self.assertEqual("loc_2d", await db.test.create_index([("loc", GEO2D)]))
index_info = (await db.test.index_information())["loc_2d"]
self.assertEqual([("loc", "2d")], index_info["key"])
# geoSearch was deprecated in 4.4 and removed in 5.0
@async_client_context.require_version_max(4, 5)
@async_client_context.require_no_mongos
async def test_index_haystack(self):
db = self.db
await db.test.drop()
_id = (
await db.test.insert_one({"pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"})
).inserted_id
await db.test.insert_one({"pos": {"long": 34.2, "lat": 37.3}, "type": "restaurant"})
await db.test.insert_one({"pos": {"long": 59.1, "lat": 87.2}, "type": "office"})
await db.test.create_index([("pos", "geoHaystack"), ("type", ASCENDING)], bucketSize=1)
results = (
await db.command(
SON(
[
("geoSearch", "test"),
("near", [33, 33]),
("maxDistance", 6),
("search", {"type": "restaurant"}),
("limit", 30),
]
)
)
)["results"]
self.assertEqual(2, len(results))
self.assertEqual(
{"_id": _id, "pos": {"long": 34.2, "lat": 33.3}, "type": "restaurant"}, results[0]
)
@async_client_context.require_no_mongos
async def test_index_text(self):
db = self.db
await db.test.drop_indexes()
self.assertEqual("t_text", await db.test.create_index([("t", TEXT)]))
index_info = (await db.test.index_information())["t_text"]
self.assertTrue("weights" in index_info)
await db.test.insert_many(
[{"t": "spam eggs and spam"}, {"t": "spam"}, {"t": "egg sausage and bacon"}]
)
# MongoDB 2.6 text search. Create 'score' field in projection.
cursor = db.test.find({"$text": {"$search": "spam"}}, {"score": {"$meta": "textScore"}})
# Sort by 'score' field.
cursor.sort([("score", {"$meta": "textScore"})])
results = await cursor.to_list()
self.assertTrue(results[0]["score"] >= results[1]["score"])
await db.test.drop_indexes()
async def test_index_2dsphere(self):
db = self.db
await db.test.drop_indexes()
self.assertEqual("geo_2dsphere", await db.test.create_index([("geo", GEOSPHERE)]))
for dummy, info in (await db.test.index_information()).items():
field, idx_type = info["key"][0]
if field == "geo" and idx_type == "2dsphere":
break
else:
self.fail("2dsphere index not found.")
poly = {"type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [41, 5], [40, 5]]]}
query = {"geo": {"$within": {"$geometry": poly}}}
# This query will error without a 2dsphere index.
db.test.find(query)
await db.test.drop_indexes()
async def test_index_hashed(self):
db = self.db
await db.test.drop_indexes()
self.assertEqual("a_hashed", await db.test.create_index([("a", HASHED)]))
for dummy, info in (await db.test.index_information()).items():
field, idx_type = info["key"][0]
if field == "a" and idx_type == "hashed":
break
else:
self.fail("hashed index not found.")
await db.test.drop_indexes()
async def test_index_sparse(self):
db = self.db
await db.test.drop_indexes()
await db.test.create_index([("key", ASCENDING)], sparse=True)
self.assertTrue((await db.test.index_information())["key_1"]["sparse"])
async def test_index_background(self):
db = self.db
await db.test.drop_indexes()
await db.test.create_index([("keya", ASCENDING)])
await db.test.create_index([("keyb", ASCENDING)], background=False)
await db.test.create_index([("keyc", ASCENDING)], background=True)
self.assertFalse("background" in (await db.test.index_information())["keya_1"])
self.assertFalse((await db.test.index_information())["keyb_1"]["background"])
self.assertTrue((await db.test.index_information())["keyc_1"]["background"])
async def _drop_dups_setup(self, db):
await db.drop_collection("test")
await db.test.insert_one({"i": 1})
await db.test.insert_one({"i": 2})
await db.test.insert_one({"i": 2}) # duplicate
await db.test.insert_one({"i": 3})
async def test_index_dont_drop_dups(self):
# Try *not* dropping duplicates
db = self.db
await self._drop_dups_setup(db)
# There's a duplicate
async def _test_create():
await db.test.create_index([("i", ASCENDING)], unique=True, dropDups=False)
with self.assertRaises(DuplicateKeyError):
await _test_create()
# Duplicate wasn't dropped
self.assertEqual(4, await db.test.count_documents({}))
# Index wasn't created, only the default index on _id
self.assertEqual(1, len(await db.test.index_information()))
# Get the plan dynamically because the explain format will change.
def get_plan_stage(self, root, stage):
if root.get("stage") == stage:
return root
elif "inputStage" in root:
return self.get_plan_stage(root["inputStage"], stage)
elif "inputStages" in root:
for i in root["inputStages"]:
stage = self.get_plan_stage(i, stage)
if stage:
return stage
elif "queryPlan" in root:
# queryPlan (and slotBasedPlan) are new in 5.0.
return self.get_plan_stage(root["queryPlan"], stage)
elif "shards" in root:
for i in root["shards"]:
stage = self.get_plan_stage(i["winningPlan"], stage)
if stage:
return stage
return {}
async def test_index_filter(self):
db = self.db
await db.drop_collection("test")
# Test bad filter spec on create.
with self.assertRaises(OperationFailure):
await db.test.create_index("x", partialFilterExpression=5)
with self.assertRaises(OperationFailure):
await db.test.create_index("x", partialFilterExpression={"x": {"$asdasd": 3}})
with self.assertRaises(OperationFailure):
await db.test.create_index("x", partialFilterExpression={"$and": 5})
self.assertEqual(
"x_1",
await db.test.create_index(
[("x", ASCENDING)], partialFilterExpression={"a": {"$lte": 1.5}}
),
)
await db.test.insert_one({"x": 5, "a": 2})
await db.test.insert_one({"x": 6, "a": 1})
# Operations that use the partial index.
explain = await db.test.find({"x": 6, "a": 1}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN")
self.assertEqual("x_1", stage.get("indexName"))
self.assertTrue(stage.get("isPartial"))
explain = await db.test.find({"x": {"$gt": 1}, "a": 1}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN")
self.assertEqual("x_1", stage.get("indexName"))
self.assertTrue(stage.get("isPartial"))
explain = await db.test.find({"x": 6, "a": {"$lte": 1}}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "IXSCAN")
self.assertEqual("x_1", stage.get("indexName"))
self.assertTrue(stage.get("isPartial"))
# Operations that do not use the partial index.
explain = await db.test.find({"x": 6, "a": {"$lte": 1.6}}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN")
self.assertNotEqual({}, stage)
explain = await db.test.find({"x": 6}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN")
self.assertNotEqual({}, stage)
# Test drop_indexes.
await db.test.drop_index("x_1")
explain = await db.test.find({"x": 6, "a": 1}).explain()
stage = self.get_plan_stage(explain["queryPlanner"]["winningPlan"], "COLLSCAN")
self.assertNotEqual({}, stage)
async def test_field_selection(self):
db = self.db
await db.drop_collection("test")
doc = {"a": 1, "b": 5, "c": {"d": 5, "e": 10}}
await db.test.insert_one(doc)
# Test field inclusion
doc = await anext(db.test.find({}, ["_id"]))
self.assertEqual(list(doc), ["_id"])
doc = await anext(db.test.find({}, ["a"]))
l = list(doc)
l.sort()
self.assertEqual(l, ["_id", "a"])
doc = await anext(db.test.find({}, ["b"]))
l = list(doc)
l.sort()
self.assertEqual(l, ["_id", "b"])
doc = await anext(db.test.find({}, ["c"]))
l = list(doc)
l.sort()
self.assertEqual(l, ["_id", "c"])
doc = await anext(db.test.find({}, ["a"]))
self.assertEqual(doc["a"], 1)
doc = await anext(db.test.find({}, ["b"]))
self.assertEqual(doc["b"], 5)
doc = await anext(db.test.find({}, ["c"]))
self.assertEqual(doc["c"], {"d": 5, "e": 10})
# Test inclusion of fields with dots
doc = await anext(db.test.find({}, ["c.d"]))
self.assertEqual(doc["c"], {"d": 5})
doc = await anext(db.test.find({}, ["c.e"]))
self.assertEqual(doc["c"], {"e": 10})
doc = await anext(db.test.find({}, ["b", "c.e"]))
self.assertEqual(doc["c"], {"e": 10})
doc = await anext(db.test.find({}, ["b", "c.e"]))
l = list(doc)
l.sort()
self.assertEqual(l, ["_id", "b", "c"])
doc = await anext(db.test.find({}, ["b", "c.e"]))
self.assertEqual(doc["b"], 5)
# Test field exclusion
doc = await anext(db.test.find({}, {"a": False, "b": 0}))
l = list(doc)
l.sort()
self.assertEqual(l, ["_id", "c"])
doc = await anext(db.test.find({}, {"_id": False}))
l = list(doc)
self.assertFalse("_id" in l)
async def test_options(self):
db = self.db
await db.drop_collection("test")
await db.create_collection("test", capped=True, size=4096)
result = await db.test.options()
self.assertEqual(result, {"capped": True, "size": 4096})
await db.drop_collection("test")
async def test_insert_one(self):
db = self.db
await db.test.drop()
document: dict[str, Any] = {"_id": 1000}
result = await db.test.insert_one(document)
self.assertTrue(isinstance(result, InsertOneResult))
self.assertTrue(isinstance(result.inserted_id, int))
self.assertEqual(document["_id"], result.inserted_id)
self.assertTrue(result.acknowledged)
self.assertIsNotNone(await db.test.find_one({"_id": document["_id"]}))
self.assertEqual(1, await db.test.count_documents({}))
document = {"foo": "bar"}
result = await db.test.insert_one(document)
self.assertTrue(isinstance(result, InsertOneResult))
self.assertTrue(isinstance(result.inserted_id, ObjectId))
self.assertEqual(document["_id"], result.inserted_id)
self.assertTrue(result.acknowledged)
self.assertIsNotNone(await db.test.find_one({"_id": document["_id"]}))
self.assertEqual(2, await db.test.count_documents({}))
db = db.client.get_database(db.name, write_concern=WriteConcern(w=0))
result = await db.test.insert_one(document)
self.assertTrue(isinstance(result, InsertOneResult))
self.assertTrue(isinstance(result.inserted_id, ObjectId))
self.assertEqual(document["_id"], result.inserted_id)
self.assertFalse(result.acknowledged)
# The insert failed duplicate key...
async def async_lambda():
return await db.test.count_documents({}) == 2
await async_wait_until(async_lambda, "forcing duplicate key error")
document = RawBSONDocument(encode({"_id": ObjectId(), "foo": "bar"}))
result = await db.test.insert_one(document)
self.assertTrue(isinstance(result, InsertOneResult))
self.assertEqual(result.inserted_id, None)
async def test_insert_many(self):
db = self.db
await db.test.drop()
docs: list = [{} for _ in range(5)]
result = await db.test.insert_many(docs)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertTrue(isinstance(result.inserted_ids, list))
self.assertEqual(5, len(result.inserted_ids))
for doc in docs:
_id = doc["_id"]
self.assertTrue(isinstance(_id, ObjectId))
self.assertTrue(_id in result.inserted_ids)
self.assertEqual(1, await db.test.count_documents({"_id": _id}))
self.assertTrue(result.acknowledged)
docs = [{"_id": i} for i in range(5)]
result = await db.test.insert_many(docs)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertTrue(isinstance(result.inserted_ids, list))
self.assertEqual(5, len(result.inserted_ids))
for doc in docs:
_id = doc["_id"]
self.assertTrue(isinstance(_id, int))
self.assertTrue(_id in result.inserted_ids)
self.assertEqual(1, await db.test.count_documents({"_id": _id}))
self.assertTrue(result.acknowledged)
docs = [RawBSONDocument(encode({"_id": i + 5})) for i in range(5)]
result = await db.test.insert_many(docs)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertTrue(isinstance(result.inserted_ids, list))
self.assertEqual([], result.inserted_ids)
db = db.client.get_database(db.name, write_concern=WriteConcern(w=0))
docs: list = [{} for _ in range(5)]
result = await db.test.insert_many(docs)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertFalse(result.acknowledged)
self.assertEqual(20, await db.test.count_documents({}))
async def test_insert_many_generator(self):
coll = self.db.test
await coll.delete_many({})
def gen():
yield {"a": 1, "b": 1}
yield {"a": 1, "b": 2}
yield {"a": 2, "b": 3}
yield {"a": 3, "b": 5}
yield {"a": 5, "b": 8}
result = await coll.insert_many(gen())
self.assertEqual(5, len(result.inserted_ids))
async def test_insert_many_invalid(self):
db = self.db
with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"):
await db.test.insert_many({})
with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"):
await db.test.insert_many([])
with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"):
await db.test.insert_many(1) # type: ignore[arg-type]
with self.assertRaisesRegex(TypeError, "documents must be a non-empty list"):
await db.test.insert_many(RawBSONDocument(encode({"_id": 2})))
async def test_delete_one(self):
await self.db.test.drop()
await self.db.test.insert_one({"x": 1})
await self.db.test.insert_one({"y": 1})
await self.db.test.insert_one({"z": 1})
result = await self.db.test.delete_one({"x": 1})
self.assertTrue(isinstance(result, DeleteResult))
self.assertEqual(1, result.deleted_count)
self.assertTrue(result.acknowledged)
self.assertEqual(2, await self.db.test.count_documents({}))
result = await self.db.test.delete_one({"y": 1})
self.assertTrue(isinstance(result, DeleteResult))
self.assertEqual(1, result.deleted_count)
self.assertTrue(result.acknowledged)
self.assertEqual(1, await self.db.test.count_documents({}))
db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0))
result = await db.test.delete_one({"z": 1})
self.assertTrue(isinstance(result, DeleteResult))
self.assertRaises(InvalidOperation, lambda: result.deleted_count)
self.assertFalse(result.acknowledged)
async def lambda_async():
return await db.test.count_documents({}) == 0
await async_wait_until(lambda_async, "delete 1 documents")
async def test_delete_many(self):
await self.db.test.drop()
await self.db.test.insert_one({"x": 1})
await self.db.test.insert_one({"x": 1})
await self.db.test.insert_one({"y": 1})
await self.db.test.insert_one({"y": 1})
result = await self.db.test.delete_many({"x": 1})
self.assertTrue(isinstance(result, DeleteResult))
self.assertEqual(2, result.deleted_count)
self.assertTrue(result.acknowledged)
self.assertEqual(0, await self.db.test.count_documents({"x": 1}))
db = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0))
result = await db.test.delete_many({"y": 1})
self.assertTrue(isinstance(result, DeleteResult))
self.assertRaises(InvalidOperation, lambda: result.deleted_count)
self.assertFalse(result.acknowledged)
async def lambda_async():
return await db.test.count_documents({}) == 0
await async_wait_until(lambda_async, "delete 2 documents")
async def test_command_document_too_large(self):
large = "*" * (await async_client_context.max_bson_size + _COMMAND_OVERHEAD)
coll = self.db.test
with self.assertRaises(DocumentTooLarge):
await coll.insert_one({"data": large})
# update_one and update_many are the same
with self.assertRaises(DocumentTooLarge):
await coll.replace_one({}, {"data": large})
with self.assertRaises(DocumentTooLarge):
await coll.delete_one({"data": large})
async def test_write_large_document(self):
max_size = await async_client_context.max_bson_size
half_size = int(max_size / 2)
max_str = "x" * max_size
half_str = "x" * half_size
self.assertEqual(max_size, 16777216)
with self.assertRaises(OperationFailure):
await self.db.test.insert_one({"foo": max_str})
with self.assertRaises(OperationFailure):
await self.db.test.replace_one({}, {"foo": max_str}, upsert=True)
with self.assertRaises(OperationFailure):
await self.db.test.insert_many([{"x": 1}, {"foo": max_str}])
await self.db.test.insert_many([{"foo": half_str}, {"foo": half_str}])
await self.db.test.insert_one({"bar": "x"})
# Use w=0 here to test legacy doc size checking in all server versions
unack_coll = self.db.test.with_options(write_concern=WriteConcern(w=0))
with self.assertRaises(DocumentTooLarge):
await unack_coll.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 14)})
await self.db.test.replace_one({"bar": "x"}, {"bar": "x" * (max_size - 32)})
async def test_insert_bypass_document_validation(self):
db = self.db
await db.test.drop()
await db.create_collection("test", validator={"a": {"$exists": True}})
db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0))
# Test insert_one
with self.assertRaises(OperationFailure):
await db.test.insert_one({"_id": 1, "x": 100})
result = await db.test.insert_one({"_id": 1, "x": 100}, bypass_document_validation=True)
self.assertTrue(isinstance(result, InsertOneResult))
self.assertEqual(1, result.inserted_id)
result = await db.test.insert_one({"_id": 2, "a": 0})
self.assertTrue(isinstance(result, InsertOneResult))
self.assertEqual(2, result.inserted_id)
await db_w0.test.insert_one({"y": 1}, bypass_document_validation=True)
async def async_lambda():
return await db_w0.test.find_one({"y": 1})
await async_wait_until(async_lambda, "find w:0 inserted document")
# Test insert_many
docs = [{"_id": i, "x": 100 - i} for i in range(3, 100)]
with self.assertRaises(OperationFailure):
await db.test.insert_many(docs)
result = await db.test.insert_many(docs, bypass_document_validation=True)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertTrue(97, len(result.inserted_ids))
for doc in docs:
_id = doc["_id"]
self.assertTrue(isinstance(_id, int))
self.assertTrue(_id in result.inserted_ids)
self.assertEqual(1, await db.test.count_documents({"x": doc["x"]}))
self.assertTrue(result.acknowledged)
docs = [{"_id": i, "a": 200 - i} for i in range(100, 200)]
result = await db.test.insert_many(docs)
self.assertTrue(isinstance(result, InsertManyResult))
self.assertTrue(97, len(result.inserted_ids))
for doc in docs:
_id = doc["_id"]
self.assertTrue(isinstance(_id, int))
self.assertTrue(_id in result.inserted_ids)
self.assertEqual(1, await db.test.count_documents({"a": doc["a"]}))
self.assertTrue(result.acknowledged)
with self.assertRaises(OperationFailure):
await db_w0.test.insert_many(
[{"x": 1}, {"x": 2}],
bypass_document_validation=True,
)
async def test_replace_bypass_document_validation(self):
db = self.db
await db.test.drop()
await db.create_collection("test", validator={"a": {"$exists": True}})
db_w0 = self.db.client.get_database(self.db.name, write_concern=WriteConcern(w=0))
# Test replace_one
await db.test.insert_one({"a": 101})
with self.assertRaises(OperationFailure):