forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_client.py
2619 lines (2219 loc) · 106 KB
/
test_client.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 2013-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 mongo_client module."""
from __future__ import annotations
import _thread as thread
import asyncio
import base64
import contextlib
import copy
import datetime
import gc
import logging
import os
import re
import signal
import socket
import struct
import subprocess
import sys
import threading
import time
import uuid
from typing import Any, Iterable, Type, no_type_check
from unittest import mock
from unittest.mock import patch
import pytest
import pytest_asyncio
from bson.binary import CSHARP_LEGACY, JAVA_LEGACY, PYTHON_LEGACY, Binary, UuidRepresentation
from pymongo.operations import _Op
sys.path[0:0] = [""]
from test.asynchronous import (
HAVE_IPADDRESS,
AsyncIntegrationTest,
AsyncMockClientTest,
AsyncUnitTest,
SkipTest,
async_client_context,
client_knobs,
connected,
db_pwd,
db_user,
remove_all_users,
unittest,
)
from test.asynchronous.pymongo_mocks import AsyncMockClient
from test.asynchronous.utils import (
async_get_pool,
async_wait_until,
asyncAssertRaisesExactly,
)
from test.test_binary import BinaryData
from test.utils_shared import (
NTHREADS,
CMAPListener,
FunctionCallRecorder,
delay,
gevent_monkey_patched,
is_greenthread_patched,
lazy_client_trial,
one,
)
import bson
import pymongo
from bson import encode
from bson.codec_options import (
CodecOptions,
DatetimeConversion,
TypeEncoder,
TypeRegistry,
)
from bson.son import SON
from bson.tz_util import utc
from pymongo import event_loggers, message, monitoring
from pymongo.asynchronous.command_cursor import AsyncCommandCursor
from pymongo.asynchronous.cursor import AsyncCursor, CursorType
from pymongo.asynchronous.database import AsyncDatabase
from pymongo.asynchronous.helpers import anext
from pymongo.asynchronous.mongo_client import AsyncMongoClient
from pymongo.asynchronous.pool import (
AsyncConnection,
)
from pymongo.asynchronous.settings import TOPOLOGY_TYPE
from pymongo.asynchronous.topology import _ErrorContext
from pymongo.client_options import ClientOptions
from pymongo.common import _UUID_REPRESENTATIONS, CONNECT_TIMEOUT, MIN_SUPPORTED_WIRE_VERSION, has_c
from pymongo.compression_support import _have_snappy, _have_zstd
from pymongo.driver_info import DriverInfo
from pymongo.errors import (
AutoReconnect,
ConfigurationError,
ConnectionFailure,
InvalidName,
InvalidOperation,
InvalidURI,
NetworkTimeout,
OperationFailure,
ServerSelectionTimeoutError,
WriteConcernError,
)
from pymongo.monitoring import ServerHeartbeatListener, ServerHeartbeatStartedEvent
from pymongo.pool_options import _MAX_METADATA_SIZE, _METADATA, ENV_VAR_K8S, PoolOptions
from pymongo.read_preferences import ReadPreference
from pymongo.server_description import ServerDescription
from pymongo.server_selectors import readable_server_selector, writable_server_selector
from pymongo.server_type import SERVER_TYPE
from pymongo.topology_description import TopologyDescription
from pymongo.write_concern import WriteConcern
_IS_SYNC = False
class AsyncClientUnitTest(AsyncUnitTest):
"""AsyncMongoClient tests that don't require a server."""
client: AsyncMongoClient
async def asyncSetUp(self) -> None:
self.client = await self.async_rs_or_single_client(
connect=False, serverSelectionTimeoutMS=100
)
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog):
self._caplog = caplog
async def test_keyword_arg_defaults(self):
client = self.simple_client(
socketTimeoutMS=None,
connectTimeoutMS=20000,
waitQueueTimeoutMS=None,
replicaSet=None,
read_preference=ReadPreference.PRIMARY,
ssl=False,
tlsCertificateKeyFile=None,
tlsAllowInvalidCertificates=True,
tlsCAFile=None,
connect=False,
serverSelectionTimeoutMS=12000,
)
options = client.options
pool_opts = options.pool_options
self.assertEqual(None, pool_opts.socket_timeout)
# socket.Socket.settimeout takes a float in seconds
self.assertEqual(20.0, pool_opts.connect_timeout)
self.assertEqual(None, pool_opts.wait_queue_timeout)
self.assertEqual(None, pool_opts._ssl_context)
self.assertEqual(None, options.replica_set_name)
self.assertEqual(ReadPreference.PRIMARY, client.read_preference)
self.assertAlmostEqual(12, client.options.server_selection_timeout)
async def test_connect_timeout(self):
client = self.simple_client(connect=False, connectTimeoutMS=None, socketTimeoutMS=None)
pool_opts = client.options.pool_options
self.assertEqual(None, pool_opts.socket_timeout)
self.assertEqual(None, pool_opts.connect_timeout)
client = self.simple_client(connect=False, connectTimeoutMS=0, socketTimeoutMS=0)
pool_opts = client.options.pool_options
self.assertEqual(None, pool_opts.socket_timeout)
self.assertEqual(None, pool_opts.connect_timeout)
client = self.simple_client(
"mongodb://localhost/?connectTimeoutMS=0&socketTimeoutMS=0", connect=False
)
pool_opts = client.options.pool_options
self.assertEqual(None, pool_opts.socket_timeout)
self.assertEqual(None, pool_opts.connect_timeout)
def test_types(self):
self.assertRaises(TypeError, AsyncMongoClient, 1)
self.assertRaises(TypeError, AsyncMongoClient, 1.14)
self.assertRaises(TypeError, AsyncMongoClient, "localhost", "27017")
self.assertRaises(TypeError, AsyncMongoClient, "localhost", 1.14)
self.assertRaises(TypeError, AsyncMongoClient, "localhost", [])
self.assertRaises(ConfigurationError, AsyncMongoClient, [])
async def test_max_pool_size_zero(self):
self.simple_client(maxPoolSize=0)
def test_uri_detection(self):
self.assertRaises(ConfigurationError, AsyncMongoClient, "/foo")
self.assertRaises(ConfigurationError, AsyncMongoClient, "://")
self.assertRaises(ConfigurationError, AsyncMongoClient, "foo/")
def test_get_db(self):
def make_db(base, name):
return base[name]
self.assertRaises(InvalidName, make_db, self.client, "")
self.assertRaises(InvalidName, make_db, self.client, "te$t")
self.assertRaises(InvalidName, make_db, self.client, "te.t")
self.assertRaises(InvalidName, make_db, self.client, "te\\t")
self.assertRaises(InvalidName, make_db, self.client, "te/t")
self.assertRaises(InvalidName, make_db, self.client, "te st")
self.assertTrue(isinstance(self.client.test, AsyncDatabase))
self.assertEqual(self.client.test, self.client["test"])
self.assertEqual(self.client.test, AsyncDatabase(self.client, "test"))
def test_get_database(self):
codec_options = CodecOptions(tz_aware=True)
write_concern = WriteConcern(w=2, j=True)
db = self.client.get_database("foo", codec_options, ReadPreference.SECONDARY, write_concern)
self.assertEqual("foo", db.name)
self.assertEqual(codec_options, db.codec_options)
self.assertEqual(ReadPreference.SECONDARY, db.read_preference)
self.assertEqual(write_concern, db.write_concern)
def test_getattr(self):
self.assertTrue(isinstance(self.client["_does_not_exist"], AsyncDatabase))
with self.assertRaises(AttributeError) as context:
self.client._does_not_exist
# Message should be:
# "AttributeError: AsyncMongoClient has no attribute '_does_not_exist'. To
# access the _does_not_exist database, use client['_does_not_exist']".
self.assertIn("has no attribute '_does_not_exist'", str(context.exception))
def test_iteration(self):
client = self.client
msg = "'AsyncMongoClient' object is not iterable"
# Iteration fails
with self.assertRaisesRegex(TypeError, msg):
for _ in client: # type: ignore[misc] # error: "None" not callable [misc]
break
# Index fails
with self.assertRaises(TypeError):
_ = client[0]
# next fails
with self.assertRaisesRegex(TypeError, "'AsyncMongoClient' object is not iterable"):
_ = next(client)
# .next() fails
with self.assertRaisesRegex(TypeError, "'AsyncMongoClient' object is not iterable"):
_ = client.next()
# Do not implement typing.Iterable.
self.assertNotIsInstance(client, Iterable)
async def test_get_default_database(self):
c = await self.async_rs_or_single_client(
"mongodb://%s:%d/foo"
% (await async_client_context.host, await async_client_context.port),
connect=False,
)
self.assertEqual(AsyncDatabase(c, "foo"), c.get_default_database())
# Test that default doesn't override the URI value.
self.assertEqual(AsyncDatabase(c, "foo"), c.get_default_database("bar"))
codec_options = CodecOptions(tz_aware=True)
write_concern = WriteConcern(w=2, j=True)
db = c.get_default_database(None, codec_options, ReadPreference.SECONDARY, write_concern)
self.assertEqual("foo", db.name)
self.assertEqual(codec_options, db.codec_options)
self.assertEqual(ReadPreference.SECONDARY, db.read_preference)
self.assertEqual(write_concern, db.write_concern)
c = await self.async_rs_or_single_client(
"mongodb://%s:%d/" % (await async_client_context.host, await async_client_context.port),
connect=False,
)
self.assertEqual(AsyncDatabase(c, "foo"), c.get_default_database("foo"))
async def test_get_default_database_error(self):
# URI with no database.
c = await self.async_rs_or_single_client(
"mongodb://%s:%d/" % (await async_client_context.host, await async_client_context.port),
connect=False,
)
self.assertRaises(ConfigurationError, c.get_default_database)
async def test_get_default_database_with_authsource(self):
# Ensure we distinguish database name from authSource.
uri = "mongodb://%s:%d/foo?authSource=src" % (
await async_client_context.host,
await async_client_context.port,
)
c = await self.async_rs_or_single_client(uri, connect=False)
self.assertEqual(AsyncDatabase(c, "foo"), c.get_default_database())
async def test_get_database_default(self):
c = await self.async_rs_or_single_client(
"mongodb://%s:%d/foo"
% (await async_client_context.host, await async_client_context.port),
connect=False,
)
self.assertEqual(AsyncDatabase(c, "foo"), c.get_database())
async def test_get_database_default_error(self):
# URI with no database.
c = await self.async_rs_or_single_client(
"mongodb://%s:%d/" % (await async_client_context.host, await async_client_context.port),
connect=False,
)
self.assertRaises(ConfigurationError, c.get_database)
async def test_get_database_default_with_authsource(self):
# Ensure we distinguish database name from authSource.
uri = "mongodb://%s:%d/foo?authSource=src" % (
await async_client_context.host,
await async_client_context.port,
)
c = await self.async_rs_or_single_client(uri, connect=False)
self.assertEqual(AsyncDatabase(c, "foo"), c.get_database())
async def test_primary_read_pref_with_tags(self):
# No tags allowed with "primary".
with self.assertRaises(ConfigurationError):
await self.async_single_client("mongodb://host/?readpreferencetags=dc:east")
with self.assertRaises(ConfigurationError):
await self.async_single_client(
"mongodb://host/?readpreference=primary&readpreferencetags=dc:east"
)
async def test_read_preference(self):
c = await self.async_rs_or_single_client(
"mongodb://host", connect=False, readpreference=ReadPreference.NEAREST.mongos_mode
)
self.assertEqual(c.read_preference, ReadPreference.NEAREST)
async def test_metadata(self):
metadata = copy.deepcopy(_METADATA)
if has_c():
metadata["driver"]["name"] = "PyMongo|c|async"
else:
metadata["driver"]["name"] = "PyMongo|async"
metadata["application"] = {"name": "foobar"}
client = self.simple_client("mongodb://foo:27017/?appname=foobar&connect=false")
options = client.options
self.assertEqual(options.pool_options.metadata, metadata)
client = self.simple_client("foo", 27017, appname="foobar", connect=False)
options = client.options
self.assertEqual(options.pool_options.metadata, metadata)
# No error
self.simple_client(appname="x" * 128)
with self.assertRaises(ValueError):
self.simple_client(appname="x" * 129)
# Bad "driver" options.
self.assertRaises(TypeError, DriverInfo, "Foo", 1, "a")
self.assertRaises(TypeError, DriverInfo, version="1", platform="a")
self.assertRaises(TypeError, DriverInfo)
with self.assertRaises(TypeError):
self.simple_client(driver=1)
with self.assertRaises(TypeError):
self.simple_client(driver="abc")
with self.assertRaises(TypeError):
self.simple_client(driver=("Foo", "1", "a"))
# Test appending to driver info.
if has_c():
metadata["driver"]["name"] = "PyMongo|c|async|FooDriver"
else:
metadata["driver"]["name"] = "PyMongo|async|FooDriver"
metadata["driver"]["version"] = "{}|1.2.3".format(_METADATA["driver"]["version"])
client = self.simple_client(
"foo",
27017,
appname="foobar",
driver=DriverInfo("FooDriver", "1.2.3", None),
connect=False,
)
options = client.options
self.assertEqual(options.pool_options.metadata, metadata)
metadata["platform"] = "{}|FooPlatform".format(_METADATA["platform"])
client = self.simple_client(
"foo",
27017,
appname="foobar",
driver=DriverInfo("FooDriver", "1.2.3", "FooPlatform"),
connect=False,
)
options = client.options
self.assertEqual(options.pool_options.metadata, metadata)
# Test truncating driver info metadata.
client = self.simple_client(
driver=DriverInfo(name="s" * _MAX_METADATA_SIZE),
connect=False,
)
options = client.options
self.assertLessEqual(
len(bson.encode(options.pool_options.metadata)),
_MAX_METADATA_SIZE,
)
client = self.simple_client(
driver=DriverInfo(name="s" * _MAX_METADATA_SIZE, version="s" * _MAX_METADATA_SIZE),
connect=False,
)
options = client.options
self.assertLessEqual(
len(bson.encode(options.pool_options.metadata)),
_MAX_METADATA_SIZE,
)
@mock.patch.dict("os.environ", {ENV_VAR_K8S: "1"})
def test_container_metadata(self):
metadata = copy.deepcopy(_METADATA)
metadata["driver"]["name"] = "PyMongo|async"
metadata["env"] = {}
metadata["env"]["container"] = {"orchestrator": "kubernetes"}
client = self.simple_client("mongodb://foo:27017/?appname=foobar&connect=false")
options = client.options
self.assertEqual(options.pool_options.metadata["env"], metadata["env"])
async def test_kwargs_codec_options(self):
class MyFloatType:
def __init__(self, x):
self.__x = x
@property
def x(self):
return self.__x
class MyFloatAsIntEncoder(TypeEncoder):
python_type = MyFloatType
def transform_python(self, value):
return int(value)
# Ensure codec options are passed in correctly
document_class: Type[SON] = SON
type_registry = TypeRegistry([MyFloatAsIntEncoder()])
tz_aware = True
uuid_representation_label = "javaLegacy"
unicode_decode_error_handler = "ignore"
tzinfo = utc
c = self.simple_client(
document_class=document_class,
type_registry=type_registry,
tz_aware=tz_aware,
uuidrepresentation=uuid_representation_label,
unicode_decode_error_handler=unicode_decode_error_handler,
tzinfo=tzinfo,
connect=False,
)
self.assertEqual(c.codec_options.document_class, document_class)
self.assertEqual(c.codec_options.type_registry, type_registry)
self.assertEqual(c.codec_options.tz_aware, tz_aware)
self.assertEqual(
c.codec_options.uuid_representation,
_UUID_REPRESENTATIONS[uuid_representation_label],
)
self.assertEqual(c.codec_options.unicode_decode_error_handler, unicode_decode_error_handler)
self.assertEqual(c.codec_options.tzinfo, tzinfo)
async def test_uri_codec_options(self):
# Ensure codec options are passed in correctly
uuid_representation_label = "javaLegacy"
unicode_decode_error_handler = "ignore"
datetime_conversion = "DATETIME_CLAMP"
uri = (
"mongodb://%s:%d/foo?tz_aware=true&uuidrepresentation="
"%s&unicode_decode_error_handler=%s"
"&datetime_conversion=%s"
% (
await async_client_context.host,
await async_client_context.port,
uuid_representation_label,
unicode_decode_error_handler,
datetime_conversion,
)
)
c = self.simple_client(uri, connect=False)
self.assertEqual(c.codec_options.tz_aware, True)
self.assertEqual(
c.codec_options.uuid_representation,
_UUID_REPRESENTATIONS[uuid_representation_label],
)
self.assertEqual(c.codec_options.unicode_decode_error_handler, unicode_decode_error_handler)
self.assertEqual(
c.codec_options.datetime_conversion, DatetimeConversion[datetime_conversion]
)
# Change the passed datetime_conversion to a number and re-assert.
uri = uri.replace(datetime_conversion, f"{int(DatetimeConversion[datetime_conversion])}")
c = self.simple_client(uri, connect=False)
self.assertEqual(
c.codec_options.datetime_conversion, DatetimeConversion[datetime_conversion]
)
async def test_uri_option_precedence(self):
# Ensure kwarg options override connection string options.
uri = "mongodb://localhost/?ssl=true&replicaSet=name&readPreference=primary"
c = self.simple_client(
uri, ssl=False, replicaSet="newname", readPreference="secondaryPreferred"
)
clopts = c.options
opts = clopts._options
self.assertEqual(opts["tls"], False)
self.assertEqual(clopts.replica_set_name, "newname")
self.assertEqual(clopts.read_preference, ReadPreference.SECONDARY_PREFERRED)
async def test_connection_timeout_ms_propagates_to_DNS_resolver(self):
# Patch the resolver.
from pymongo.srv_resolver import _resolve
patched_resolver = FunctionCallRecorder(_resolve)
pymongo.srv_resolver._resolve = patched_resolver
def reset_resolver():
pymongo.srv_resolver._resolve = _resolve
self.addCleanup(reset_resolver)
# Setup.
base_uri = "mongodb+srv://test5.test.build.10gen.cc"
connectTimeoutMS = 5000
expected_kw_value = 5.0
uri_with_timeout = base_uri + "/?connectTimeoutMS=6000"
expected_uri_value = 6.0
async def test_scenario(args, kwargs, expected_value):
patched_resolver.reset()
self.simple_client(*args, **kwargs)
for _, kw in patched_resolver.call_list():
self.assertAlmostEqual(kw["lifetime"], expected_value)
# No timeout specified.
await test_scenario((base_uri,), {}, CONNECT_TIMEOUT)
# Timeout only specified in connection string.
await test_scenario((uri_with_timeout,), {}, expected_uri_value)
# Timeout only specified in keyword arguments.
kwarg = {"connectTimeoutMS": connectTimeoutMS}
await test_scenario((base_uri,), kwarg, expected_kw_value)
# Timeout specified in both kwargs and connection string.
await test_scenario((uri_with_timeout,), kwarg, expected_kw_value)
async def test_uri_security_options(self):
# Ensure that we don't silently override security-related options.
with self.assertRaises(InvalidURI):
self.simple_client("mongodb://localhost/?ssl=true", tls=False, connect=False)
# Matching SSL and TLS options should not cause errors.
c = self.simple_client("mongodb://localhost/?ssl=false", tls=False, connect=False)
self.assertEqual(c.options._options["tls"], False)
# Conflicting tlsInsecure options should raise an error.
with self.assertRaises(InvalidURI):
self.simple_client(
"mongodb://localhost/?tlsInsecure=true",
connect=False,
tlsAllowInvalidHostnames=True,
)
# Conflicting legacy tlsInsecure options should also raise an error.
with self.assertRaises(InvalidURI):
self.simple_client(
"mongodb://localhost/?tlsInsecure=true",
connect=False,
tlsAllowInvalidCertificates=False,
)
# Conflicting kwargs should raise InvalidURI
with self.assertRaises(InvalidURI):
self.simple_client(ssl=True, tls=False)
async def test_event_listeners(self):
c = self.simple_client(event_listeners=[], connect=False)
self.assertEqual(c.options.event_listeners, [])
listeners = [
event_loggers.CommandLogger(),
event_loggers.HeartbeatLogger(),
event_loggers.ServerLogger(),
event_loggers.TopologyLogger(),
event_loggers.ConnectionPoolLogger(),
]
c = self.simple_client(event_listeners=listeners, connect=False)
self.assertEqual(c.options.event_listeners, listeners)
async def test_client_options(self):
c = self.simple_client(connect=False)
self.assertIsInstance(c.options, ClientOptions)
self.assertIsInstance(c.options.pool_options, PoolOptions)
self.assertEqual(c.options.server_selection_timeout, 30)
self.assertEqual(c.options.pool_options.max_idle_time_seconds, None)
self.assertIsInstance(c.options.retry_writes, bool)
self.assertIsInstance(c.options.retry_reads, bool)
def test_validate_suggestion(self):
"""Validate kwargs in constructor."""
for typo in ["auth", "Auth", "AUTH"]:
expected = f"Unknown option: {typo}. Did you mean one of (authsource, authmechanism, authoidcallowedhosts) or maybe a camelCase version of one? Refer to docstring."
expected = re.escape(expected)
with self.assertRaisesRegex(ConfigurationError, expected):
AsyncMongoClient(**{typo: "standard"}) # type: ignore[arg-type]
@patch("pymongo.srv_resolver._SrvResolver.get_hosts")
def test_detected_environment_logging(self, mock_get_hosts):
normal_hosts = [
"normal.host.com",
"host.cosmos.azure.com",
"host.docdb.amazonaws.com",
"host.docdb-elastic.amazonaws.com",
]
srv_hosts = ["mongodb+srv://<test>:<test>@" + s for s in normal_hosts]
multi_host = (
"host.cosmos.azure.com,host.docdb.amazonaws.com,host.docdb-elastic.amazonaws.com"
)
with self.assertLogs("pymongo", level="INFO") as cm:
for host in normal_hosts:
AsyncMongoClient(host, connect=False)
for host in srv_hosts:
mock_get_hosts.return_value = [(host, 1)]
AsyncMongoClient(host, connect=False)
AsyncMongoClient(multi_host, connect=False)
logs = [record.getMessage() for record in cm.records if record.name == "pymongo.client"]
self.assertEqual(len(logs), 7)
@patch("pymongo.srv_resolver._SrvResolver.get_hosts")
async def test_detected_environment_warning(self, mock_get_hosts):
with self._caplog.at_level(logging.WARN):
normal_hosts = [
"host.cosmos.azure.com",
"host.docdb.amazonaws.com",
"host.docdb-elastic.amazonaws.com",
]
srv_hosts = ["mongodb+srv://<test>:<test>@" + s for s in normal_hosts]
multi_host = (
"host.cosmos.azure.com,host.docdb.amazonaws.com,host.docdb-elastic.amazonaws.com"
)
for host in normal_hosts:
with self.assertWarns(UserWarning):
self.simple_client(host)
for host in srv_hosts:
mock_get_hosts.return_value = [(host, 1)]
with self.assertWarns(UserWarning):
self.simple_client(host)
with self.assertWarns(UserWarning):
self.simple_client(multi_host)
class TestClient(AsyncIntegrationTest):
def test_multiple_uris(self):
with self.assertRaises(ConfigurationError):
AsyncMongoClient(
host=[
"mongodb+srv://cluster-a.abc12.mongodb.net",
"mongodb+srv://cluster-b.abc12.mongodb.net",
"mongodb+srv://cluster-c.abc12.mongodb.net",
]
)
async def test_max_idle_time_reaper_default(self):
with client_knobs(kill_cursor_frequency=0.1):
# Assert reaper doesn't remove connections when maxIdleTimeMS not set
client = await self.async_rs_or_single_client()
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn:
pass
self.assertEqual(1, len(server._pool.conns))
self.assertTrue(conn in server._pool.conns)
async def test_max_idle_time_reaper_removes_stale_minPoolSize(self):
with client_knobs(kill_cursor_frequency=0.1):
# Assert reaper removes idle socket and replaces it with a new one
client = await self.async_rs_or_single_client(maxIdleTimeMS=500, minPoolSize=1)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn:
pass
# When the reaper runs at the same time as the get_socket, two
# connections could be created and checked into the pool.
self.assertGreaterEqual(len(server._pool.conns), 1)
await async_wait_until(lambda: conn not in server._pool.conns, "remove stale socket")
await async_wait_until(lambda: len(server._pool.conns) >= 1, "replace stale socket")
async def test_max_idle_time_reaper_does_not_exceed_maxPoolSize(self):
with client_knobs(kill_cursor_frequency=0.1):
# Assert reaper respects maxPoolSize when adding new connections.
client = await self.async_rs_or_single_client(
maxIdleTimeMS=500, minPoolSize=1, maxPoolSize=1
)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn:
pass
# When the reaper runs at the same time as the get_socket,
# maxPoolSize=1 should prevent two connections from being created.
self.assertEqual(1, len(server._pool.conns))
await async_wait_until(lambda: conn not in server._pool.conns, "remove stale socket")
await async_wait_until(lambda: len(server._pool.conns) == 1, "replace stale socket")
async def test_max_idle_time_reaper_removes_stale(self):
with client_knobs(kill_cursor_frequency=0.1):
# Assert reaper has removed idle socket and NOT replaced it
client = await self.async_rs_or_single_client(maxIdleTimeMS=500)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn_one:
pass
# Assert that the pool does not close connections prematurely.
await asyncio.sleep(0.300)
async with server._pool.checkout() as conn_two:
pass
self.assertIs(conn_one, conn_two)
await async_wait_until(
lambda: len(server._pool.conns) == 0,
"stale socket reaped and new one NOT added to the pool",
)
async def test_min_pool_size(self):
with client_knobs(kill_cursor_frequency=0.1):
client = await self.async_rs_or_single_client()
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
self.assertEqual(0, len(server._pool.conns))
# Assert that pool started up at minPoolSize
client = await self.async_rs_or_single_client(minPoolSize=10)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
await async_wait_until(
lambda: len(server._pool.conns) == 10,
"pool initialized with 10 connections",
)
# Assert that if a socket is closed, a new one takes its place
async with server._pool.checkout() as conn:
conn.close_conn(None)
await async_wait_until(
lambda: len(server._pool.conns) == 10,
"a closed socket gets replaced from the pool",
)
self.assertFalse(conn in server._pool.conns)
async def test_max_idle_time_checkout(self):
# Use high frequency to test _get_socket_no_auth.
with client_knobs(kill_cursor_frequency=99999999):
client = await self.async_rs_or_single_client(maxIdleTimeMS=500)
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn:
pass
self.assertEqual(1, len(server._pool.conns))
await asyncio.sleep(1) # Sleep so that the socket becomes stale.
async with server._pool.checkout() as new_con:
self.assertNotEqual(conn, new_con)
self.assertEqual(1, len(server._pool.conns))
self.assertFalse(conn in server._pool.conns)
self.assertTrue(new_con in server._pool.conns)
# Test that connections are reused if maxIdleTimeMS is not set.
client = await self.async_rs_or_single_client()
server = await (await client._get_topology()).select_server(
readable_server_selector, _Op.TEST
)
async with server._pool.checkout() as conn:
pass
self.assertEqual(1, len(server._pool.conns))
await asyncio.sleep(1)
async with server._pool.checkout() as new_con:
self.assertEqual(conn, new_con)
self.assertEqual(1, len(server._pool.conns))
async def test_constants(self):
"""This test uses AsyncMongoClient explicitly to make sure that host and
port are not overloaded.
"""
host, port = await async_client_context.host, await async_client_context.port
kwargs: dict = async_client_context.default_client_options.copy()
if async_client_context.auth_enabled:
kwargs["username"] = db_user
kwargs["password"] = db_pwd
# Set bad defaults.
AsyncMongoClient.HOST = "somedomainthatdoesntexist.org"
AsyncMongoClient.PORT = 123456789
with self.assertRaises(AutoReconnect):
c = self.simple_client(serverSelectionTimeoutMS=10, **kwargs)
await connected(c)
c = self.simple_client(host, port, **kwargs)
# Override the defaults. No error.
await connected(c)
# Set good defaults.
AsyncMongoClient.HOST = host
AsyncMongoClient.PORT = port
# No error.
c = self.simple_client(**kwargs)
await connected(c)
async def test_init_disconnected(self):
host, port = await async_client_context.host, await async_client_context.port
c = await self.async_rs_or_single_client(connect=False)
# is_primary causes client to block until connected
self.assertIsInstance(await c.is_primary, bool)
c = await self.async_rs_or_single_client(connect=False)
self.assertIsInstance(await c.is_mongos, bool)
c = await self.async_rs_or_single_client(connect=False)
self.assertIsInstance(c.options.pool_options.max_pool_size, int)
self.assertIsInstance(c.nodes, frozenset)
c = await self.async_rs_or_single_client(connect=False)
self.assertEqual(c.codec_options, CodecOptions())
c = await self.async_rs_or_single_client(connect=False)
self.assertFalse(await c.primary)
self.assertFalse(await c.secondaries)
c = await self.async_rs_or_single_client(connect=False)
self.assertIsInstance(c.topology_description, TopologyDescription)
self.assertEqual(c.topology_description, c._topology._description)
if async_client_context.is_rs:
# The primary's host and port are from the replica set config.
self.assertIsNotNone(await c.address)
else:
self.assertEqual(await c.address, (host, port))
bad_host = "somedomainthatdoesntexist.org"
c = self.simple_client(bad_host, port, connectTimeoutMS=1, serverSelectionTimeoutMS=10)
with self.assertRaises(ConnectionFailure):
await c.pymongo_test.test.find_one()
async def test_init_disconnected_with_auth(self):
uri = "mongodb://user:pass@somedomainthatdoesntexist"
c = self.simple_client(uri, connectTimeoutMS=1, serverSelectionTimeoutMS=10)
with self.assertRaises(ConnectionFailure):
await c.pymongo_test.test.find_one()
async def test_equality(self):
seed = "{}:{}".format(*list(self.client._topology_settings.seeds)[0])
c = await self.async_rs_or_single_client(seed, connect=False)
self.assertEqual(async_client_context.client, c)
# Explicitly test inequality
self.assertFalse(async_client_context.client != c)
c = await self.async_rs_or_single_client("invalid.com", connect=False)
self.assertNotEqual(async_client_context.client, c)
self.assertTrue(async_client_context.client != c)
c1 = self.simple_client("a", connect=False)
c2 = self.simple_client("b", connect=False)
# Seeds differ:
self.assertNotEqual(c1, c2)
c1 = self.simple_client(["a", "b", "c"], connect=False)
c2 = self.simple_client(["c", "a", "b"], connect=False)
# Same seeds but out of order still compares equal:
self.assertEqual(c1, c2)
async def test_hashable(self):
seed = "{}:{}".format(*list(self.client._topology_settings.seeds)[0])
c = await self.async_rs_or_single_client(seed, connect=False)
self.assertIn(c, {async_client_context.client})
c = await self.async_rs_or_single_client("invalid.com", connect=False)
self.assertNotIn(c, {async_client_context.client})
async def test_host_w_port(self):
with self.assertRaises(ValueError):
host = await async_client_context.host
await connected(
AsyncMongoClient(
f"{host}:1234567",
connectTimeoutMS=1,
serverSelectionTimeoutMS=10,
)
)
async def test_repr(self):
# Used to test 'eval' below.
import bson
client = AsyncMongoClient( # type: ignore[type-var]
"mongodb://localhost:27017,localhost:27018/?replicaSet=replset"
"&connectTimeoutMS=12345&w=1&wtimeoutms=100",
connect=False,
document_class=SON,
)
the_repr = repr(client)
self.assertIn("AsyncMongoClient(host=", the_repr)
self.assertIn("document_class=bson.son.SON, tz_aware=False, connect=False, ", the_repr)
self.assertIn("connecttimeoutms=12345", the_repr)
self.assertIn("replicaset='replset'", the_repr)
self.assertIn("w=1", the_repr)
self.assertIn("wtimeoutms=100", the_repr)
async with eval(the_repr) as client_two:
self.assertEqual(client_two, client)
client = self.simple_client(
"localhost:27017,localhost:27018",
replicaSet="replset",
connectTimeoutMS=12345,
socketTimeoutMS=None,
w=1,
wtimeoutms=100,
connect=False,
)
the_repr = repr(client)
self.assertIn("AsyncMongoClient(host=", the_repr)
self.assertIn("document_class=dict, tz_aware=False, connect=False, ", the_repr)
self.assertIn("connecttimeoutms=12345", the_repr)
self.assertIn("replicaset='replset'", the_repr)
self.assertIn("sockettimeoutms=None", the_repr)
self.assertIn("w=1", the_repr)
self.assertIn("wtimeoutms=100", the_repr)
async with eval(the_repr) as client_two:
self.assertEqual(client_two, client)
async def test_getters(self):
await async_wait_until(
lambda: async_client_context.nodes == self.client.nodes, "find all nodes"
)
async def test_list_databases(self):
cmd_docs = (await self.client.admin.command("listDatabases"))["databases"]
cursor = await self.client.list_databases()
self.assertIsInstance(cursor, AsyncCommandCursor)
helper_docs = await cursor.to_list()
self.assertTrue(len(helper_docs) > 0)
self.assertEqual(len(helper_docs), len(cmd_docs))
# PYTHON-3529 Some fields may change between calls, just compare names.
for helper_doc, cmd_doc in zip(helper_docs, cmd_docs):
self.assertIs(type(helper_doc), dict)
self.assertEqual(helper_doc.keys(), cmd_doc.keys())
client = await self.async_rs_or_single_client(document_class=SON)
async for doc in await client.list_databases():
self.assertIs(type(doc), dict)
await self.client.pymongo_test.test.insert_one({})
cursor = await self.client.list_databases(filter={"name": "admin"})
docs = await cursor.to_list()
self.assertEqual(1, len(docs))
self.assertEqual(docs[0]["name"], "admin")
cursor = await self.client.list_databases(nameOnly=True)
async for doc in cursor:
self.assertEqual(["name"], list(doc))
async def test_list_database_names(self):
await self.client.pymongo_test.test.insert_one({"dummy": "object"})
await self.client.pymongo_test_mike.test.insert_one({"dummy": "object"})
cmd_docs = (await self.client.admin.command("listDatabases"))["databases"]
cmd_names = [doc["name"] for doc in cmd_docs]
db_names = await self.client.list_database_names()
self.assertTrue("pymongo_test" in db_names)
self.assertTrue("pymongo_test_mike" in db_names)
self.assertEqual(db_names, cmd_names)
async def test_drop_database(self):
with self.assertRaises(TypeError):
await self.client.drop_database(5) # type: ignore[arg-type]
with self.assertRaises(TypeError):
await self.client.drop_database(None) # type: ignore[arg-type]
await self.client.pymongo_test.test.insert_one({"dummy": "object"})
await self.client.pymongo_test2.test.insert_one({"dummy": "object"})
dbs = await self.client.list_database_names()
self.assertIn("pymongo_test", dbs)
self.assertIn("pymongo_test2", dbs)
await self.client.drop_database("pymongo_test")
if async_client_context.is_rs:
wc_client = await self.async_rs_or_single_client(w=len(async_client_context.nodes) + 1)
with self.assertRaises(WriteConcernError):
await wc_client.drop_database("pymongo_test2")
await self.client.drop_database(self.client.pymongo_test2)
dbs = await self.client.list_database_names()
self.assertNotIn("pymongo_test", dbs)
self.assertNotIn("pymongo_test2", dbs)
async def test_close(self):
test_client = await self.async_rs_or_single_client()