-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtest_mongo.py
490 lines (434 loc) · 15 KB
/
test_mongo.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
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime
from unittest import mock
from unittest.mock import AsyncMock, Mock
import pytest
from bson import DBRef, ObjectId
from bson.decimal128 import Decimal128
from pymongo.errors import OperationFailure
from connectors.protocol import Filter
from connectors.source import ConfigurableFieldValueError
from connectors.sources.mongo import MongoAdvancedRulesValidator, MongoDataSource
from tests.commons import AsyncIterator
from tests.sources.support import create_source
@asynccontextmanager
async def create_mongo_source(
host="mongodb://127.0.0.1:27021",
database="db",
collection="col",
ssl_enabled=False,
ssl_ca="",
tls_insecure=False,
):
async with create_source(
MongoDataSource,
host=host,
user="foo",
password="bar",
direct_connection=True,
database=database,
collection=collection,
ssl_enabled=ssl_enabled,
ssl_ca=ssl_ca,
tls_insecure=tls_insecure,
) as source:
yield source
@pytest.mark.asyncio
@pytest.mark.parametrize(
"advanced_rules, is_valid",
[
(
# empty advanced rules
{},
True,
),
(
# valid aggregate
{
"aggregate": {
"allowDiskUse": True,
"maxTimeMS": 1,
"batchSize": 1,
"let": {"key": "value"},
"pipeline": [{"$project": {"name": {"$toUpper": "$name"}}}],
}
},
True,
),
(
# unknown field in aggregate
{"aggregate": {"unknown": True}},
False,
),
(
# empty pipeline
{"aggregate": {"pipeline": []}},
False,
),
(
# wrong type
{"aggregate": {"batchSize": 1.5}},
False,
),
(
# valid find
{
"find": {
"filter": {"key": "value"},
"projection": ["field"],
"skip": 1,
"limit": 10,
"no_cursor_timeout": True,
"allow_partial_results": True,
"batch_size": 5,
"return_key": True,
"show_record_id": False,
"max_time_ms": 10,
"allow_disk_use": True,
}
},
True,
),
(
# projection as object
{"find": {"projection": {"key": "value"}}},
True,
),
(
# empty projection
{"find": {"projection": []}},
False,
),
(
# wrong type
{"find": {"skip": 1.5}},
False,
),
(
# unknown field in find
{"find": {"unknown": 42}},
False,
),
(
# unknown top level field
{"filter": {}},
False,
),
(
# aggregate and find present
{"aggregate": {}, "find": {}},
False,
),
],
)
async def test_advanced_rules_validator(advanced_rules, is_valid):
validation_result = await MongoAdvancedRulesValidator().validate(advanced_rules)
assert validation_result.is_valid == is_valid
def build_resp():
doc1 = {"id": "one", "tuple": (1, 2, 3), "date": datetime.now()}
doc2 = {"id": "two", "dict": {"a": "b"}, "decimal": Decimal128("0.0005")}
class Docs(dict):
def __init__(self):
self["cursor"] = self
self["id"] = "1234"
self["firstBatch"] = [doc1, doc2]
self["nextBatch"] = []
resp = mock.MagicMock()
resp.docs = [Docs()]
return resp
@pytest.mark.asyncio
@mock.patch(
"pymongo.topology.Topology._select_servers_loop", lambda *x: [mock.MagicMock()]
)
@mock.patch(
"pymongo.mongo_client.MongoClient._run_operation", lambda *xi, **kw: build_resp()
)
async def test_get_docs(*args):
async with create_mongo_source() as source:
num = 0
async for doc, _ in source.get_docs():
assert doc["id"] in ("one", "two")
num += 1
assert num == 2
@pytest.mark.asyncio
@mock.patch(
"pymongo.topology.Topology._select_servers_loop", lambda *x: [mock.MagicMock()]
)
@mock.patch(
"pymongo.mongo_client.MongoClient._run_operation", lambda *xi, **kw: build_resp()
)
async def test_ping_when_called_then_does_not_raise(*args):
admin_mock = Mock()
command_mock = AsyncMock()
admin_mock.command = command_mock
class MockedClient:
def __enter__(self):
return self
def __exit__(self, *args):
return
@property
def admin(self):
return admin_mock
async with create_mongo_source() as source:
with mock.patch.object(source, "get_client", return_value=MockedClient()):
await source.ping()
@pytest.mark.asyncio
async def test_mongo_data_source_get_docs_when_advanced_rules_find_present():
async with create_mongo_source() as source:
collection_mock = Mock()
collection_mock.find = AsyncIterator(items=[{"_id": 1}])
source.collection = collection_mock
filtering = Filter(
{
"advanced_snippet": {
"value": {
"find": {
"filter": {"key": "value"},
"projection": ["field"],
"skip": 1,
"limit": 10,
"no_cursor_timeout": True,
"allow_partial_results": True,
"batch_size": 5,
"return_key": True,
"show_record_id": False,
"max_time_ms": 10,
"allow_disk_use": True,
}
}
}
}
)
with mock.patch.object(source, "get_client") as mock_client:
mock_client.__enter__.return_value = Mock()
async for _ in source.get_docs(filtering):
pass
find_call_kwargs = collection_mock.find.call_kwargs
assert find_call_kwargs[0] == filtering.get_advanced_rules().get("find")
@pytest.mark.asyncio
async def test_mongo_data_source_get_docs_when_advanced_rules_aggregate_present():
async with create_mongo_source() as source:
collection_mock = Mock()
collection_mock.aggregate = AsyncIterator(items=[{"_id": 1}])
source.collection = collection_mock
filtering = Filter(
{
"advanced_snippet": {
"value": {
"aggregate": {
"allowDiskUse": True,
"maxTimeMS": 10,
"batchSize": 1,
"let": {"key": "value"},
"pipeline": [
{"$match": {"field1": "value1"}},
{"$group": {"_id": "$field2", "count": {"$sum": 1}}},
],
}
}
}
}
)
with mock.patch.object(source, "get_client") as mock_client:
mock_client.__enter__.return_value = Mock()
async for _ in source.get_docs(filtering):
pass
aggregate_call_kwargs = collection_mock.aggregate.call_kwargs
assert aggregate_call_kwargs[0] == filtering.get_advanced_rules().get(
"aggregate"
)
def future_with_result(result):
future = asyncio.Future()
future.set_result(result)
return future
@pytest.mark.asyncio
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
side_effect=OperationFailure("Unauthorized"),
)
async def test_validate_config_when_database_name_invalid_then_raises_exception(
patch_validate_collection,
):
server_database_names = ["hello", "world"]
configured_database_name = "something"
with mock.patch(
"motor.motor_asyncio.AsyncIOMotorClient.list_database_names",
return_value=future_with_result(server_database_names),
):
async with create_mongo_source(
database=configured_database_name,
collection="something",
) as source:
with pytest.raises(ConfigurableFieldValueError) as e:
await source.validate_config()
# assert that message contains database name from config
assert e.match(configured_database_name)
# assert that message contains database names from the server too
for database_name in server_database_names:
assert e.match(database_name)
@pytest.mark.asyncio
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
side_effect=OperationFailure("Unauthorized"),
)
async def test_validate_config_when_collection_name_invalid_then_raises_exception(
patch_validate_collection,
):
server_database_names = ["hello"]
server_collection_names = ["first", "second"]
configured_database_name = "hello"
configured_collection_name = "third"
with (
mock.patch(
"motor.motor_asyncio.AsyncIOMotorClient.list_database_names",
return_value=future_with_result(server_database_names),
),
mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.list_collection_names",
return_value=future_with_result(server_collection_names),
),
):
async with create_mongo_source(
database=configured_database_name,
collection=configured_collection_name,
) as source:
with pytest.raises(ConfigurableFieldValueError) as e:
await source.validate_config()
# assert that message contains database name from config
assert e.match(configured_collection_name)
# assert that message contains database names from the server too
for collection_name in server_collection_names:
assert e.match(collection_name)
@pytest.mark.asyncio
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
side_effect=OperationFailure("Unauthorized"),
)
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorClient.list_database_names",
return_value=future_with_result(["hello"]),
)
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.list_collection_names",
return_value=future_with_result(["first"]),
)
async def test_validate_config_when_collection_access_unauthorized(
patch_validate_collection, patch_list_database_names, patch_list_collection_names
):
configured_database_name = "hello"
configured_collection_name = "second"
with pytest.raises(ConfigurableFieldValueError) as e:
async with create_mongo_source(
database=configured_database_name,
collection=configured_collection_name,
) as source:
await source.validate_config()
assert e is not None
@pytest.mark.asyncio
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
side_effect=OperationFailure("Unauthorized"),
)
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorClient.list_database_names",
side_effect=OperationFailure("Unauthorized"),
)
async def test_validate_config_when_collection_access_unauthorized_and_no_admin_access(
patch_validate_collection, patch_list_database_names
):
configured_database_name = "hello"
configured_collection_name = "second"
with pytest.raises(ConfigurableFieldValueError) as e:
async with create_mongo_source(
database=configured_database_name,
collection=configured_collection_name,
) as source:
await source.validate_config()
assert e is not None
@pytest.mark.asyncio
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
return_value=future_with_result(None),
)
async def test_validate_config_when_configuration_valid_then_does_not_raise(
patch_validate_connection,
):
configured_database_name = "hello"
configured_collection_name = "second"
async with create_mongo_source(
database=configured_database_name,
collection=configured_collection_name,
) as source:
await source.validate_config()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"raw, output",
[
({"ref": DBRef("foo", "bar")}, {"ref": {"$ref": "foo", "$id": "bar"}}),
({"dec": Decimal128("1.25")}, {"dec": 1.25}),
(
{"id": ObjectId("507f1f77bcf86cd799439011")},
{"id": "507f1f77bcf86cd799439011"},
),
],
)
async def test_serialize(raw, output):
async with create_mongo_source() as source:
assert source.serialize(raw) == output
@pytest.mark.asyncio
@pytest.mark.parametrize(
"certificate_value, tls_insecure",
[
(
# Connection Successful: Certificate: Valid, tls_insecure: False
"-----BEGIN CERTIFICATE----- Valid-Certificate -----END CERTIFICATE-----",
False,
),
(
# Insecure Connection Successful: Certificate: Invalid, tls_insecure: True
"-----BEGIN CERTIFICATE----- Invalid-Certificate -----END CERTIFICATE-----",
True,
),
],
)
@mock.patch("ssl.SSLContext.load_verify_locations")
@mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.validate_collection",
side_effect=OperationFailure("Unauthorized"),
)
async def test_ssl_successful_connection(
patch_validate_collection, mock_ssl, certificate_value, tls_insecure
):
mock_ssl.return_value = True
async with create_mongo_source(
ssl_enabled=True, ssl_ca=certificate_value, tls_insecure=tls_insecure
) as source:
with (
mock.patch(
"motor.motor_asyncio.AsyncIOMotorClient.list_database_names",
return_value=future_with_result(["db"]),
),
mock.patch(
"motor.motor_asyncio.AsyncIOMotorDatabase.list_collection_names",
return_value=future_with_result(["col"]),
),
):
await source.validate_config()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"host_value, ssl_value",
[
("mongodb://127.0.0.1:27021/?ssl=true", False),
("mongodb://127.0.0.1:27021/?ssl=false", True),
],
)
async def test_get_client_when_pass_conflicting_values(host_value, ssl_value):
async with create_mongo_source(host=host_value, ssl_enabled=ssl_value) as source:
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()