forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_bulk.py
More file actions
418 lines (349 loc) · 14.8 KB
/
test_bulk.py
File metadata and controls
418 lines (349 loc) · 14.8 KB
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
# 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."""
import sys
sys.path[0:0] = [""]
from bson.objectid import ObjectId
from pymongo.operations import *
from pymongo.errors import (ConfigurationError,
InvalidOperation,
OperationFailure)
from pymongo.write_concern import WriteConcern
from test import (client_context,
unittest,
IntegrationTest)
from test.utils import (remove_all_users,
rs_or_single_client_noauth)
class BulkTestBase(IntegrationTest):
@classmethod
def setUpClass(cls):
super(BulkTestBase, cls).setUpClass()
cls.coll = cls.db.test
ismaster = client_context.client.admin.command('ismaster')
cls.has_write_commands = (ismaster.get("maxWireVersion", 0) > 1)
def setUp(self):
super(BulkTestBase, self).setUp()
self.coll.drop()
def assertEqualResponse(self, expected, actual):
"""Compare response from bulk.execute() to expected response."""
for key, value in expected.items():
if key == 'nModified':
if self.has_write_commands:
self.assertEqual(value, actual['nModified'])
else:
# Legacy servers don't include nModified in the response.
self.assertFalse('nModified' in actual)
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,
'%r value of %r does not match expected %r' %
(key, actual.get(key), value))
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 TestBulk(BulkTestBase):
def test_empty(self):
self.assertRaises(InvalidOperation, self.coll.bulk_write, [])
def test_insert(self):
expected = {
'nMatched': 0,
'nModified': 0,
'nUpserted': 0,
'nInserted': 1,
'nRemoved': 0,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
result = self.coll.bulk_write([InsertOne({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.inserted_count)
self.assertEqual(1, self.coll.count_documents({}))
def _test_update_many(self, update):
expected = {
'nMatched': 2,
'nModified': 2,
'nUpserted': 0,
'nInserted': 0,
'nRemoved': 0,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert_many([{}, {}])
result = 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))
def test_update_many(self):
self._test_update_many({'$set': {'foo': 'bar'}})
@client_context.require_version_min(4, 1, 11)
def test_update_many_pipeline(self):
self._test_update_many([{'$set': {'foo': 'bar'}}])
@client_context.require_version_max(3, 5, 5)
def test_array_filters_unsupported(self):
requests = [
UpdateMany(
{}, {'$set': {'y.$[i].b': 5}}, array_filters=[{'i.b': 1}]),
UpdateOne(
{}, {'$set': {"y.$[i].b": 2}}, array_filters=[{'i.b': 3}])
]
for bulk_op in requests:
self.assertRaises(
ConfigurationError, self.coll.bulk_write, [bulk_op])
def test_array_filters_validation(self):
self.assertRaises(TypeError, UpdateMany, {}, {}, array_filters={})
self.assertRaises(TypeError, UpdateOne, {}, {}, array_filters={})
def test_array_filters_unacknowledged(self):
coll = self.coll.with_options(write_concern=WriteConcern(w=0))
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}])
self.assertRaises(ConfigurationError, coll.bulk_write, [update_one])
self.assertRaises(ConfigurationError, coll.bulk_write, [update_many])
def _test_update_one(self, update):
expected = {
'nMatched': 1,
'nModified': 1,
'nUpserted': 0,
'nInserted': 0,
'nRemoved': 0,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert_many([{}, {}])
result = 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))
def test_update_one(self):
self._test_update_one({'$set': {'foo': 'bar'}})
@client_context.require_version_min(4, 1, 11)
def test_update_one_pipeline(self):
self._test_update_one([{'$set': {'foo': 'bar'}}])
def test_replace_one(self):
expected = {
'nMatched': 1,
'nModified': 1,
'nUpserted': 0,
'nInserted': 0,
'nRemoved': 0,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert_many([{}, {}])
result = 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))
def test_remove(self):
# Test removing all documents, ordered.
expected = {
'nMatched': 0,
'nModified': 0,
'nUpserted': 0,
'nInserted': 0,
'nRemoved': 2,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
self.coll.insert_many([{}, {}])
result = self.coll.bulk_write([DeleteMany({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(2, result.deleted_count)
def test_remove_one(self):
# Test removing one document, empty selector.
self.coll.insert_many([{}, {}])
expected = {
'nMatched': 0,
'nModified': 0,
'nUpserted': 0,
'nInserted': 0,
'nRemoved': 1,
'upserted': [],
'writeErrors': [],
'writeConcernErrors': []
}
result = self.coll.bulk_write([DeleteOne({})])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.deleted_count)
self.assertEqual(self.coll.count_documents({}), 1)
def test_upsert(self):
expected = {
'nMatched': 0,
'nModified': 0,
'nUpserted': 1,
'nInserted': 0,
'nRemoved': 0,
'upserted': [{'index': 0, '_id': '...'}]
}
result = self.coll.bulk_write([ReplaceOne({},
{'foo': 'bar'},
upsert=True)])
self.assertEqualResponse(expected, result.bulk_api_result)
self.assertEqual(1, result.upserted_count)
self.assertEqual(1, len(result.upserted_ids))
self.assertTrue(isinstance(result.upserted_ids.get(0), ObjectId))
self.assertEqual(self.coll.count_documents({'foo': 'bar'}), 1)
def test_numerous_inserts(self):
# Ensure we don't exceed server's 1000-document batch size limit.
n_docs = 2100
requests = [InsertOne({}) for _ in range(n_docs)]
result = self.coll.bulk_write(requests, ordered=False)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, self.coll.count_documents({}))
# Same with ordered bulk.
self.coll.drop()
result = self.coll.bulk_write(requests)
self.assertEqual(n_docs, result.inserted_count)
self.assertEqual(n_docs, self.coll.count_documents({}))
@client_context.require_version_min(3, 6)
def test_bulk_max_message_size(self):
self.coll.delete_many({})
self.addCleanup(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 = self.coll.insert_many(docs)
self.assertEqual(len(docs), len(result.inserted_ids))
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 = self.coll.insert_many(gen())
self.assertEqual(5, len(result.inserted_ids))
def test_bulk_write_no_results(self):
coll = self.coll.with_options(write_concern=WriteConcern(w=0))
result = coll.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)
def test_bulk_write_invalid_arguments(self):
# The requests argument must be a list.
generator = (InsertOne({}) for _ in range(10))
with self.assertRaises(TypeError):
self.coll.bulk_write(generator)
# Document is not wrapped in a bulk write operation.
with self.assertRaises(TypeError):
self.coll.bulk_write([{}])
class BulkAuthorizationTestBase(BulkTestBase):
@classmethod
@client_context.require_auth
def setUpClass(cls):
super(BulkAuthorizationTestBase, cls).setUpClass()
def setUp(self):
super(BulkAuthorizationTestBase, self).setUp()
client_context.create_user(
self.db.name, 'readonly', 'pw', ['read'])
self.db.command(
'createRole', 'noremove',
privileges=[{
'actions': ['insert', 'update', 'find'],
'resource': {'db': 'pymongo_test', 'collection': 'test'}
}],
roles=[])
client_context.create_user(self.db.name, 'noremove', 'pw', ['noremove'])
def tearDown(self):
self.db.command('dropRole', 'noremove')
remove_all_users(self.db)
class TestBulkAuthorization(BulkAuthorizationTestBase):
def test_readonly(self):
# We test that an authorization failure aborts the batch and is raised
# as OperationFailure.
cli = rs_or_single_client_noauth(username='readonly', password='pw',
authSource='pymongo_test')
coll = cli.pymongo_test.test
coll.find_one()
self.assertRaises(OperationFailure, coll.bulk_write,
[InsertOne({'x': 1})])
def test_no_remove(self):
# We test that an authorization failure aborts the batch and is raised
# as OperationFailure.
cli = rs_or_single_client_noauth(username='noremove', password='pw',
authSource='pymongo_test')
coll = cli.pymongo_test.test
coll.find_one()
requests = [
InsertOne({'x': 1}),
ReplaceOne({'x': 2}, {'x': 2}, upsert=True),
DeleteMany({}), # Prohibited.
InsertOne({'x': 3}), # Never attempted.
]
self.assertRaises(OperationFailure, coll.bulk_write, requests)
self.assertEqual(set([1, 2]), set(self.coll.distinct('x')))
if __name__ == "__main__":
unittest.main()