-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathtest_bulk.py
1137 lines (992 loc) · 40.5 KB
/
test_bulk.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 2014-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 bulk API."""
from __future__ import annotations
import sys
import uuid
from typing import Any, Optional
from pymongo.asynchronous.mongo_client import AsyncMongoClient
sys.path[0:0] = [""]
from test.asynchronous import AsyncIntegrationTest, async_client_context, remove_all_users, unittest
from test.utils_shared import async_wait_until
from bson.binary import Binary, UuidRepresentation
from bson.codec_options import CodecOptions
from bson.objectid import ObjectId
from pymongo.asynchronous.collection import AsyncCollection
from pymongo.common import partition_node
from pymongo.errors import BulkWriteError, ConfigurationError, InvalidOperation, OperationFailure
from pymongo.operations import *
from pymongo.write_concern import WriteConcern
_IS_SYNC = False
class AsyncBulkTestBase(AsyncIntegrationTest):
coll: AsyncCollection
coll_w0: AsyncCollection
async def asyncSetUp(self):
await super().asyncSetUp()
self.coll = self.db.test
await self.coll.drop()
self.coll_w0 = self.coll.with_options(write_concern=WriteConcern(w=0))
def assertEqualResponse(self, expected, actual):
"""Compare response from bulk.execute() to expected response."""
for key, value in expected.items():
if key == "nModified":
self.assertEqual(value, actual["nModified"])
elif key == "upserted":
expected_upserts = value
actual_upserts = actual["upserted"]
self.assertEqual(
len(expected_upserts),
len(actual_upserts),
'Expected %d elements in "upserted", got %d'
% (len(expected_upserts), len(actual_upserts)),
)
for e, a in zip(expected_upserts, actual_upserts):
self.assertEqualUpsert(e, a)
elif key == "writeErrors":
expected_errors = value
actual_errors = actual["writeErrors"]
self.assertEqual(
len(expected_errors),
len(actual_errors),
'Expected %d elements in "writeErrors", got %d'
% (len(expected_errors), len(actual_errors)),
)
for e, a in zip(expected_errors, actual_errors):
self.assertEqualWriteError(e, a)
else:
self.assertEqual(
actual.get(key),
value,
f"{key!r} value of {actual.get(key)!r} does not match expected {value!r}",
)
def assertEqualUpsert(self, expected, actual):
"""Compare bulk.execute()['upserts'] to expected value.
Like: {'index': 0, '_id': ObjectId()}
"""
self.assertEqual(expected["index"], actual["index"])
if expected["_id"] == "...":
# Unspecified value.
self.assertTrue("_id" in actual)
else:
self.assertEqual(expected["_id"], actual["_id"])
def assertEqualWriteError(self, expected, actual):
"""Compare bulk.execute()['writeErrors'] to expected value.
Like: {'index': 0, 'code': 123, 'errmsg': '...', 'op': { ... }}
"""
self.assertEqual(expected["index"], actual["index"])
self.assertEqual(expected["code"], actual["code"])
if expected["errmsg"] == "...":
# Unspecified value.
self.assertTrue("errmsg" in actual)
else:
self.assertEqual(expected["errmsg"], actual["errmsg"])
expected_op = expected["op"].copy()
actual_op = actual["op"].copy()
if expected_op.get("_id") == "...":
# Unspecified _id.
self.assertTrue("_id" in actual_op)
actual_op.pop("_id")
expected_op.pop("_id")
self.assertEqual(expected_op, actual_op)
class AsyncTestBulk(AsyncBulkTestBase):
async def test_empty(self):
with self.assertRaises(InvalidOperation):
await self.coll.bulk_write([])
async def test_insert(self):
expected = {
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 1,
"nRemoved": 0,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
result = await self.coll.bulk_write([InsertOne({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.inserted_count)
self.assertEqual(1, await self.coll.count_documents({}))
async def _test_update_many(self, update):
expected = {
"nMatched": 2,
"nModified": 2,
"nUpserted": 0,
"nInserted": 0,
"nRemoved": 0,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
await self.coll.insert_many([{}, {}])
result = await self.coll.bulk_write([UpdateMany({}, update)])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(2, result.matched_count)
self.assertTrue(result.modified_count in (2, None))
async def test_update_many(self):
await self._test_update_many({"$set": {"foo": "bar"}})
@async_client_context.require_version_min(4, 1, 11)
async def test_update_many_pipeline(self):
await self._test_update_many([{"$set": {"foo": "bar"}}])
async def test_array_filters_validation(self):
with self.assertRaises(TypeError):
await UpdateMany({}, {}, array_filters={}) # type: ignore[arg-type]
with self.assertRaises(TypeError):
await UpdateOne({}, {}, array_filters={}) # type: ignore[arg-type]
async def test_array_filters_unacknowledged(self):
coll = self.coll_w0
update_one = UpdateOne({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}])
update_many = UpdateMany({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}])
with self.assertRaises(ConfigurationError):
await coll.bulk_write([update_one])
with self.assertRaises(ConfigurationError):
await coll.bulk_write([update_many])
async def _test_update_one(self, update):
expected = {
"nMatched": 1,
"nModified": 1,
"nUpserted": 0,
"nInserted": 0,
"nRemoved": 0,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
await self.coll.insert_many([{}, {}])
result = await self.coll.bulk_write([UpdateOne({}, update)])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.matched_count)
self.assertTrue(result.modified_count in (1, None))
async def test_update_one(self):
await self._test_update_one({"$set": {"foo": "bar"}})
@async_client_context.require_version_min(4, 1, 11)
async def test_update_one_pipeline(self):
await self._test_update_one([{"$set": {"foo": "bar"}}])
async def test_replace_one(self):
expected = {
"nMatched": 1,
"nModified": 1,
"nUpserted": 0,
"nInserted": 0,
"nRemoved": 0,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
await self.coll.insert_many([{}, {}])
result = await self.coll.bulk_write([ReplaceOne({}, {"foo": "bar"})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.matched_count)
self.assertTrue(result.modified_count in (1, None))
async def test_remove(self):
# Test removing all documents, ordered.
expected = {
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 0,
"nRemoved": 2,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
await self.coll.insert_many([{}, {}])
result = await self.coll.bulk_write([DeleteMany({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(2, result.deleted_count)
async def test_remove_one(self):
# Test removing one document, empty selector.
await self.coll.insert_many([{}, {}])
expected = {
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 0,
"nRemoved": 1,
"upserted": [],
"writeErrors": [],
"writeConcernErrors": [],
}
result = await self.coll.bulk_write([DeleteOne({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.deleted_count)
self.assertEqual(await self.coll.count_documents({}), 1)
async def test_upsert(self):
expected = {
"nMatched": 0,
"nModified": 0,
"nUpserted": 1,
"nInserted": 0,
"nRemoved": 0,
"upserted": [{"index": 0, "_id": "..."}],
}
result = await self.coll.bulk_write([ReplaceOne({}, {"foo": "bar"}, upsert=True)])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.upserted_count)
assert result.upserted_ids is not None
self.assertEqual(1, len(result.upserted_ids))
self.assertTrue(isinstance(result.upserted_ids.get(0), ObjectId))
self.assertEqual(await self.coll.count_documents({"foo": "bar"}), 1)
async def test_numerous_inserts(self):
# Ensure we don't exceed server's maxWriteBatchSize size limit.
n_docs = await async_client_context.max_write_batch_size + 100
requests = [InsertOne[dict]({}) for _ in range(n_docs)]
result = await self.coll.bulk_write(requests, ordered=False)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, await self.coll.count_documents({}))
# Same with ordered bulk.
await self.coll.drop()
result = await self.coll.bulk_write(requests)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, await self.coll.count_documents({}))
async def test_numerous_inserts_generator(self):
# Ensure we don't exceed server's maxWriteBatchSize size limit.
n_docs = await async_client_context.max_write_batch_size + 100
requests = (InsertOne[dict]({}) for _ in range(n_docs))
result = await self.coll.bulk_write(requests, ordered=False)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, await self.coll.count_documents({}))
# Same with ordered bulk.
await self.coll.drop()
requests = (InsertOne[dict]({}) for _ in range(n_docs))
result = await self.coll.bulk_write(requests)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, await self.coll.count_documents({}))
async def test_bulk_max_message_size(self):
await self.coll.delete_many({})
self.addAsyncCleanup(self.coll.delete_many, {})
_16_MB = 16 * 1000 * 1000
# Generate a list of documents such that the first batched OP_MSG is
# as close as possible to the 48MB limit.
docs = [
{"_id": 1, "l": "s" * _16_MB},
{"_id": 2, "l": "s" * _16_MB},
{"_id": 3, "l": "s" * (_16_MB - 10000)},
]
# Fill in the remaining ~10000 bytes with small documents.
for i in range(4, 10000):
docs.append({"_id": i})
result = await self.coll.insert_many(docs)
self.assertEqual(len(docs), len(result.inserted_ids))
async def test_generator_insert(self):
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 self.coll.insert_many(gen())
self.assertEqual(5, len(result.inserted_ids))
async def test_bulk_write_no_results(self):
result = await self.coll_w0.bulk_write([InsertOne({})])
self.assertFalse(result.acknowledged)
self.assertRaises(InvalidOperation, lambda: result.inserted_count)
self.assertRaises(InvalidOperation, lambda: result.matched_count)
self.assertRaises(InvalidOperation, lambda: result.modified_count)
self.assertRaises(InvalidOperation, lambda: result.deleted_count)
self.assertRaises(InvalidOperation, lambda: result.upserted_count)
self.assertRaises(InvalidOperation, lambda: result.upserted_ids)
async def test_bulk_write_invalid_arguments(self):
# The requests argument must be a list.
generator = (InsertOne[dict]({}) for _ in range(10))
with self.assertRaises(TypeError):
await self.coll.bulk_write(generator) # type: ignore[arg-type]
# Document is not wrapped in a bulk write operation.
with self.assertRaises(TypeError):
await self.coll.bulk_write([{}]) # type: ignore[list-item]
async def test_upsert_large(self):
big = "a" * (await async_client_context.max_bson_size - 37)
result = await self.coll.bulk_write(
[UpdateOne({"x": 1}, {"$set": {"s": big}}, upsert=True)]
)
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 1,
"nInserted": 0,
"nRemoved": 0,
"upserted": [{"index": 0, "_id": "..."}],
},
result.bulk_api_result,
)
self.assertEqual(1, await self.coll.count_documents({"x": 1}))
async def test_client_generated_upsert_id(self):
result = await self.coll.bulk_write(
[
UpdateOne({"_id": 0}, {"$set": {"a": 0}}, upsert=True),
ReplaceOne({"a": 1}, {"_id": 1}, upsert=True),
# This is just here to make the counts right in all cases.
ReplaceOne({"_id": 2}, {"_id": 2}, upsert=True),
]
)
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 3,
"nInserted": 0,
"nRemoved": 0,
"upserted": [
{"index": 0, "_id": 0},
{"index": 1, "_id": 1},
{"index": 2, "_id": 2},
],
},
result.bulk_api_result,
)
async def test_upsert_uuid_standard(self):
options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
coll = self.coll.with_options(codec_options=options)
uuids = [uuid.uuid4() for _ in range(3)]
result = await coll.bulk_write(
[
UpdateOne({"_id": uuids[0]}, {"$set": {"a": 0}}, upsert=True),
ReplaceOne({"a": 1}, {"_id": uuids[1]}, upsert=True),
# This is just here to make the counts right in all cases.
ReplaceOne({"_id": uuids[2]}, {"_id": uuids[2]}, upsert=True),
]
)
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 3,
"nInserted": 0,
"nRemoved": 0,
"upserted": [
{"index": 0, "_id": uuids[0]},
{"index": 1, "_id": uuids[1]},
{"index": 2, "_id": uuids[2]},
],
},
result.bulk_api_result,
)
async def test_upsert_uuid_unspecified(self):
options = CodecOptions(uuid_representation=UuidRepresentation.UNSPECIFIED)
coll = self.coll.with_options(codec_options=options)
uuids = [Binary.from_uuid(uuid.uuid4()) for _ in range(3)]
result = await coll.bulk_write(
[
UpdateOne({"_id": uuids[0]}, {"$set": {"a": 0}}, upsert=True),
ReplaceOne({"a": 1}, {"_id": uuids[1]}, upsert=True),
# This is just here to make the counts right in all cases.
ReplaceOne({"_id": uuids[2]}, {"_id": uuids[2]}, upsert=True),
]
)
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 3,
"nInserted": 0,
"nRemoved": 0,
"upserted": [
{"index": 0, "_id": uuids[0]},
{"index": 1, "_id": uuids[1]},
{"index": 2, "_id": uuids[2]},
],
},
result.bulk_api_result,
)
async def test_upsert_uuid_standard_subdocuments(self):
options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
coll = self.coll.with_options(codec_options=options)
ids: list = [{"f": Binary(bytes(i)), "f2": uuid.uuid4()} for i in range(3)]
result = await coll.bulk_write(
[
UpdateOne({"_id": ids[0]}, {"$set": {"a": 0}}, upsert=True),
ReplaceOne({"a": 1}, {"_id": ids[1]}, upsert=True),
# This is just here to make the counts right in all cases.
ReplaceOne({"_id": ids[2]}, {"_id": ids[2]}, upsert=True),
]
)
# The `Binary` values are returned as `bytes` objects.
for _id in ids:
_id["f"] = bytes(_id["f"])
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 3,
"nInserted": 0,
"nRemoved": 0,
"upserted": [
{"index": 0, "_id": ids[0]},
{"index": 1, "_id": ids[1]},
{"index": 2, "_id": ids[2]},
],
},
result.bulk_api_result,
)
async def test_single_ordered_batch(self):
result = await self.coll.bulk_write(
[
InsertOne({"a": 1}),
UpdateOne({"a": 1}, {"$set": {"b": 1}}),
UpdateOne({"a": 2}, {"$set": {"b": 2}}, upsert=True),
InsertOne({"a": 3}),
DeleteOne({"a": 3}),
]
)
self.assertEqualResponse(
{
"nMatched": 1,
"nModified": 1,
"nUpserted": 1,
"nInserted": 2,
"nRemoved": 1,
"upserted": [{"index": 2, "_id": "..."}],
},
result.bulk_api_result,
)
async def test_single_error_ordered_batch(self):
await self.coll.create_index("a", unique=True)
self.addAsyncCleanup(self.coll.drop_index, [("a", 1)])
requests: list = [
InsertOne({"b": 1, "a": 1}),
UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
InsertOne({"b": 3, "a": 2}),
]
try:
await self.coll.bulk_write(requests)
except BulkWriteError as exc:
result = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 1,
"nRemoved": 0,
"upserted": [],
"writeConcernErrors": [],
"writeErrors": [
{
"index": 1,
"code": 11000,
"errmsg": "...",
"op": {
"q": {"b": 2},
"u": {"$set": {"a": 1}},
"multi": False,
"upsert": True,
},
}
],
},
result,
)
async def test_multiple_error_ordered_batch(self):
await self.coll.create_index("a", unique=True)
self.addAsyncCleanup(self.coll.drop_index, [("a", 1)])
requests: list = [
InsertOne({"b": 1, "a": 1}),
UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
UpdateOne({"b": 3}, {"$set": {"a": 2}}, upsert=True),
UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
InsertOne({"b": 4, "a": 3}),
InsertOne({"b": 5, "a": 1}),
]
try:
await self.coll.bulk_write(requests)
except BulkWriteError as exc:
result = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 1,
"nRemoved": 0,
"upserted": [],
"writeConcernErrors": [],
"writeErrors": [
{
"index": 1,
"code": 11000,
"errmsg": "...",
"op": {
"q": {"b": 2},
"u": {"$set": {"a": 1}},
"multi": False,
"upsert": True,
},
}
],
},
result,
)
async def test_single_unordered_batch(self):
requests: list = [
InsertOne({"a": 1}),
UpdateOne({"a": 1}, {"$set": {"b": 1}}),
UpdateOne({"a": 2}, {"$set": {"b": 2}}, upsert=True),
InsertOne({"a": 3}),
DeleteOne({"a": 3}),
]
result = await self.coll.bulk_write(requests, ordered=False)
self.assertEqualResponse(
{
"nMatched": 1,
"nModified": 1,
"nUpserted": 1,
"nInserted": 2,
"nRemoved": 1,
"upserted": [{"index": 2, "_id": "..."}],
"writeErrors": [],
"writeConcernErrors": [],
},
result.bulk_api_result,
)
async def test_single_error_unordered_batch(self):
await self.coll.create_index("a", unique=True)
self.addAsyncCleanup(self.coll.drop_index, [("a", 1)])
requests: list = [
InsertOne({"b": 1, "a": 1}),
UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
InsertOne({"b": 3, "a": 2}),
]
try:
await self.coll.bulk_write(requests, ordered=False)
except BulkWriteError as exc:
result = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 0,
"nInserted": 2,
"nRemoved": 0,
"upserted": [],
"writeConcernErrors": [],
"writeErrors": [
{
"index": 1,
"code": 11000,
"errmsg": "...",
"op": {
"q": {"b": 2},
"u": {"$set": {"a": 1}},
"multi": False,
"upsert": True,
},
}
],
},
result,
)
async def test_multiple_error_unordered_batch(self):
await self.coll.create_index("a", unique=True)
self.addAsyncCleanup(self.coll.drop_index, [("a", 1)])
requests: list = [
InsertOne({"b": 1, "a": 1}),
UpdateOne({"b": 2}, {"$set": {"a": 3}}, upsert=True),
UpdateOne({"b": 3}, {"$set": {"a": 4}}, upsert=True),
UpdateOne({"b": 4}, {"$set": {"a": 3}}, upsert=True),
InsertOne({"b": 5, "a": 2}),
InsertOne({"b": 6, "a": 1}),
]
try:
await self.coll.bulk_write(requests, ordered=False)
except BulkWriteError as exc:
result = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
# Assume the update at index 1 runs before the update at index 3,
# although the spec does not require it. Same for inserts.
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,
"nUpserted": 2,
"nInserted": 2,
"nRemoved": 0,
"upserted": [{"index": 1, "_id": "..."}, {"index": 2, "_id": "..."}],
"writeConcernErrors": [],
"writeErrors": [
{
"index": 3,
"code": 11000,
"errmsg": "...",
"op": {
"q": {"b": 4},
"u": {"$set": {"a": 3}},
"multi": False,
"upsert": True,
},
},
{
"index": 5,
"code": 11000,
"errmsg": "...",
"op": {"_id": "...", "b": 6, "a": 1},
},
],
},
result,
)
async def test_large_inserts_ordered(self):
big = "x" * await async_client_context.max_bson_size
requests = [
InsertOne({"b": 1, "a": 1}),
InsertOne({"big": big}),
InsertOne({"b": 2, "a": 2}),
]
try:
await self.coll.bulk_write(requests)
except BulkWriteError as exc:
result = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqual(1, result["nInserted"])
await self.coll.delete_many({})
big = "x" * (1024 * 1024 * 4)
write_result = await self.coll.bulk_write(
[
InsertOne({"a": 1, "big": big}),
InsertOne({"a": 2, "big": big}),
InsertOne({"a": 3, "big": big}),
InsertOne({"a": 4, "big": big}),
InsertOne({"a": 5, "big": big}),
InsertOne({"a": 6, "big": big}),
]
)
self.assertEqual(6, write_result.inserted_count)
self.assertEqual(6, await self.coll.count_documents({}))
async def test_large_inserts_unordered(self):
big = "x" * await async_client_context.max_bson_size
requests = [
InsertOne({"b": 1, "a": 1}),
InsertOne({"big": big}),
InsertOne({"b": 2, "a": 2}),
]
try:
await self.coll.bulk_write(requests, ordered=False)
except BulkWriteError as exc:
details = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqual(2, details["nInserted"])
await self.coll.delete_many({})
big = "x" * (1024 * 1024 * 4)
result = await self.coll.bulk_write(
[
InsertOne({"a": 1, "big": big}),
InsertOne({"a": 2, "big": big}),
InsertOne({"a": 3, "big": big}),
InsertOne({"a": 4, "big": big}),
InsertOne({"a": 5, "big": big}),
InsertOne({"a": 6, "big": big}),
],
ordered=False,
)
self.assertEqual(6, result.inserted_count)
self.assertEqual(6, await self.coll.count_documents({}))
class AsyncBulkAuthorizationTestBase(AsyncBulkTestBase):
@async_client_context.require_auth
@async_client_context.require_no_api_version
async def asyncSetUp(self):
await super().asyncSetUp()
await async_client_context.create_user(self.db.name, "readonly", "pw", ["read"])
await self.db.command(
"createRole",
"noremove",
privileges=[
{
"actions": ["insert", "update", "find"],
"resource": {"db": "pymongo_test", "collection": "test"},
}
],
roles=[],
)
await async_client_context.create_user(self.db.name, "noremove", "pw", ["noremove"])
async def asyncTearDown(self):
await self.db.command("dropRole", "noremove")
await remove_all_users(self.db)
class AsyncTestBulkUnacknowledged(AsyncBulkTestBase):
async def asyncTearDown(self):
await self.coll.delete_many({})
async def test_no_results_ordered_success(self):
requests: list = [
InsertOne({"a": 1}),
UpdateOne({"a": 3}, {"$set": {"b": 1}}, upsert=True),
InsertOne({"a": 2}),
DeleteOne({"a": 1}),
]
result = await self.coll_w0.bulk_write(requests)
self.assertFalse(result.acknowledged)
async def predicate():
return await self.coll.count_documents({}) == 2
await async_wait_until(predicate, "insert 2 documents")
async def predicate():
return await self.coll.find_one({"_id": 1}) is None
await async_wait_until(predicate, 'removed {"_id": 1}')
async def test_no_results_ordered_failure(self):
requests: list = [
InsertOne({"_id": 1}),
UpdateOne({"_id": 3}, {"$set": {"b": 1}}, upsert=True),
InsertOne({"_id": 2}),
# Fails with duplicate key error.
InsertOne({"_id": 1}),
# Should not be executed since the batch is ordered.
DeleteOne({"_id": 1}),
]
result = await self.coll_w0.bulk_write(requests)
self.assertFalse(result.acknowledged)
async def predicate():
return await self.coll.count_documents({}) == 3
await async_wait_until(predicate, "insert 3 documents")
self.assertEqual({"_id": 1}, await self.coll.find_one({"_id": 1}))
async def test_no_results_unordered_success(self):
requests: list = [
InsertOne({"a": 1}),
UpdateOne({"a": 3}, {"$set": {"b": 1}}, upsert=True),
InsertOne({"a": 2}),
DeleteOne({"a": 1}),
]
result = await self.coll_w0.bulk_write(requests, ordered=False)
self.assertFalse(result.acknowledged)
async def predicate():
return await self.coll.count_documents({}) == 2
await async_wait_until(predicate, "insert 2 documents")
async def predicate():
return await self.coll.find_one({"_id": 1}) is None
await async_wait_until(predicate, 'removed {"_id": 1}')
async def test_no_results_unordered_failure(self):
requests: list = [
InsertOne({"_id": 1}),
UpdateOne({"_id": 3}, {"$set": {"b": 1}}, upsert=True),
InsertOne({"_id": 2}),
# Fails with duplicate key error.
InsertOne({"_id": 1}),
# Should be executed since the batch is unordered.
DeleteOne({"_id": 1}),
]
result = await self.coll_w0.bulk_write(requests, ordered=False)
self.assertFalse(result.acknowledged)
async def predicate():
return await self.coll.count_documents({}) == 2
await async_wait_until(predicate, "insert 2 documents")
async def predicate():
return await self.coll.find_one({"_id": 1}) is None
await async_wait_until(predicate, 'removed {"_id": 1}')
class AsyncTestBulkAuthorization(AsyncBulkAuthorizationTestBase):
async def test_readonly(self):
# We test that an authorization failure aborts the batch and is raised
# as OperationFailure.
cli = await self.async_rs_or_single_client_noauth(
username="readonly", password="pw", authSource="pymongo_test"
)
coll = cli.pymongo_test.test
await coll.find_one()
with self.assertRaises(OperationFailure):
await coll.bulk_write([InsertOne({"x": 1})])
async def test_no_remove(self):
# We test that an authorization failure aborts the batch and is raised
# as OperationFailure.
cli = await self.async_rs_or_single_client_noauth(
username="noremove", password="pw", authSource="pymongo_test"
)
coll = cli.pymongo_test.test
await coll.find_one()
requests = [
InsertOne({"x": 1}),
ReplaceOne({"x": 2}, {"x": 2}, upsert=True),
DeleteMany({}), # Prohibited.
InsertOne({"x": 3}), # Never attempted.
]
with self.assertRaises(OperationFailure):
await coll.bulk_write(requests) # type: ignore[arg-type]
self.assertEqual({1, 2}, set(await self.coll.distinct("x")))
class AsyncTestBulkWriteConcern(AsyncBulkTestBase):
w: Optional[int]
secondary: AsyncMongoClient
async def asyncSetUp(self):
await super().asyncSetUp()
self.w = async_client_context.w
self.secondary = None
if self.w is not None and self.w > 1:
for member in (await async_client_context.hello)["hosts"]:
if member != (await async_client_context.hello)["primary"]:
self.secondary = await self.async_single_client(*partition_node(member))
break
async def asyncTearDown(self):
if self.secondary:
await self.secondary.close()
async def cause_wtimeout(self, requests, ordered):
if not async_client_context.test_commands_enabled:
self.skipTest("Test commands must be enabled.")
# Use the rsSyncApplyStop failpoint to pause replication on a
# secondary which will cause a wtimeout error.
await self.secondary.admin.command("configureFailPoint", "rsSyncApplyStop", mode="alwaysOn")
try:
coll = self.coll.with_options(write_concern=WriteConcern(w=self.w, wtimeout=1))
return await coll.bulk_write(requests, ordered=ordered)
finally:
await self.secondary.admin.command("configureFailPoint", "rsSyncApplyStop", mode="off")
@async_client_context.require_version_max(7, 1) # PYTHON-4560
@async_client_context.require_replica_set
@async_client_context.require_secondaries_count(1)
async def test_write_concern_failure_ordered(self):
details = None
# Ensure we don't raise on wnote.
coll_ww = self.coll.with_options(write_concern=WriteConcern(w=self.w))
result = await coll_ww.bulk_write([DeleteOne({"something": "that does no exist"})])
self.assertTrue(result.acknowledged)
requests: list[Any] = [InsertOne({"a": 1}), InsertOne({"a": 2})]
# Replication wtimeout is a 'soft' error.
# It shouldn't stop batch processing.
try:
await self.cause_wtimeout(requests, ordered=True)
except BulkWriteError as exc:
details = exc.details
self.assertEqual(exc.code, 65)
else:
self.fail("Error not raised")
self.assertEqualResponse(
{
"nMatched": 0,
"nModified": 0,