forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunified_format.py
1553 lines (1337 loc) · 62.5 KB
/
unified_format.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 2020-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.
"""Unified test format runner.
https://github.com/mongodb/specifications/blob/master/source/unified-test-format/unified-test-format.md
"""
from __future__ import annotations
import asyncio
import binascii
import copy
import functools
import os
import re
import sys
import time
import traceback
from asyncio import iscoroutinefunction
from collections import defaultdict
from test import (
IntegrationTest,
client_context,
client_knobs,
unittest,
)
from test.unified_format_shared import (
KMS_TLS_OPTS,
PLACEHOLDER_MAP,
SKIP_CSOT_TESTS,
EventListenerUtil,
MatchEvaluatorUtil,
coerce_result,
parse_bulk_write_error_result,
parse_bulk_write_result,
parse_client_bulk_write_error_result,
parse_collection_or_database_options,
with_metaclass,
)
from test.utils import (
camel_to_snake,
camel_to_snake_args,
get_pool,
parse_spec_options,
prepare_spec_arguments,
snake_to_camel,
wait_until,
)
from test.utils_spec_runner import SpecRunnerThread
from test.version import Version
from typing import Any, Dict, List, Mapping, Optional
import pymongo
from bson import SON, json_util
from bson.codec_options import DEFAULT_CODEC_OPTIONS
from bson.objectid import ObjectId
from gridfs import GridFSBucket, GridOut
from pymongo import ASCENDING, CursorType, MongoClient, _csot
from pymongo.encryption_options import _HAVE_PYMONGOCRYPT
from pymongo.errors import (
AutoReconnect,
BulkWriteError,
ClientBulkWriteException,
ConfigurationError,
ConnectionFailure,
EncryptionError,
InvalidOperation,
NotPrimaryError,
OperationFailure,
PyMongoError,
)
from pymongo.monitoring import (
CommandStartedEvent,
)
from pymongo.operations import (
SearchIndexModel,
)
from pymongo.read_concern import ReadConcern
from pymongo.read_preferences import ReadPreference
from pymongo.server_api import ServerApi
from pymongo.server_selectors import Selection, writable_server_selector
from pymongo.server_type import SERVER_TYPE
from pymongo.synchronous.change_stream import ChangeStream
from pymongo.synchronous.client_session import ClientSession, TransactionOptions, _TxnState
from pymongo.synchronous.collection import Collection
from pymongo.synchronous.command_cursor import CommandCursor
from pymongo.synchronous.database import Database
from pymongo.synchronous.encryption import ClientEncryption
from pymongo.synchronous.helpers import next
from pymongo.topology_description import TopologyDescription
from pymongo.typings import _Address
from pymongo.write_concern import WriteConcern
_IS_SYNC = True
IS_INTERRUPTED = False
def interrupt_loop():
global IS_INTERRUPTED
IS_INTERRUPTED = True
def is_run_on_requirement_satisfied(requirement):
topology_satisfied = True
req_topologies = requirement.get("topologies")
if req_topologies:
topology_satisfied = client_context.is_topology_type(req_topologies)
server_version = Version(*client_context.version[:3])
min_version_satisfied = True
req_min_server_version = requirement.get("minServerVersion")
if req_min_server_version:
min_version_satisfied = Version.from_string(req_min_server_version) <= server_version
max_version_satisfied = True
req_max_server_version = requirement.get("maxServerVersion")
if req_max_server_version:
max_version_satisfied = Version.from_string(req_max_server_version) >= server_version
serverless = requirement.get("serverless")
if serverless == "require":
serverless_satisfied = client_context.serverless
elif serverless == "forbid":
serverless_satisfied = not client_context.serverless
else: # unset or "allow"
serverless_satisfied = True
params_satisfied = True
params = requirement.get("serverParameters")
if params:
for param, val in params.items():
if param not in client_context.server_parameters:
params_satisfied = False
elif client_context.server_parameters[param] != val:
params_satisfied = False
auth_satisfied = True
req_auth = requirement.get("auth")
if req_auth is not None:
if req_auth:
auth_satisfied = client_context.auth_enabled
if auth_satisfied and "authMechanism" in requirement:
auth_satisfied = client_context.check_auth_type(requirement["authMechanism"])
else:
auth_satisfied = not client_context.auth_enabled
csfle_satisfied = True
req_csfle = requirement.get("csfle")
if req_csfle is True:
min_version_satisfied = Version.from_string("4.2") <= server_version
csfle_satisfied = _HAVE_PYMONGOCRYPT and min_version_satisfied
return (
topology_satisfied
and min_version_satisfied
and max_version_satisfied
and serverless_satisfied
and params_satisfied
and auth_satisfied
and csfle_satisfied
)
class NonLazyCursor:
"""A find cursor proxy that creates the remote cursor when initialized."""
def __init__(self, find_cursor, client):
self.client = client
self.find_cursor = find_cursor
# Create the server side cursor.
self.first_result = None
@classmethod
def create(cls, find_cursor, client):
cursor = cls(find_cursor, client)
try:
cursor.first_result = next(cursor.find_cursor)
except StopIteration:
cursor.first_result = None
return cursor
@property
def alive(self):
return self.first_result is not None or self.find_cursor.alive
def __next__(self):
if self.first_result is not None:
first = self.first_result
self.first_result = None
return first
return next(self.find_cursor)
# Added to support the iterateOnce operation.
try_next = __next__
def close(self):
self.find_cursor.close()
self.client = None
class EntityMapUtil:
"""Utility class that implements an entity map as per the unified
test format specification.
"""
def __init__(self, test_class):
self._entities: Dict[str, Any] = {}
self._listeners: Dict[str, EventListenerUtil] = {}
self._session_lsids: Dict[str, Mapping[str, Any]] = {}
self.test: UnifiedSpecTestMixinV1 = test_class
self._cluster_time: Mapping[str, Any] = {}
def __contains__(self, item):
return item in self._entities
def __len__(self):
return len(self._entities)
def __getitem__(self, item):
try:
return self._entities[item]
except KeyError:
self.test.fail(f"Could not find entity named {item} in map")
def __setitem__(self, key, value):
if not isinstance(key, str):
self.test.fail("Expected entity name of type str, got %s" % (type(key)))
if key in self._entities:
self.test.fail(f"Entity named {key} already in map")
self._entities[key] = value
def _handle_placeholders(self, spec: dict, current: dict, path: str) -> Any:
if "$$placeholder" in current:
if path not in PLACEHOLDER_MAP:
raise ValueError(f"Could not find a placeholder value for {path}")
return PLACEHOLDER_MAP[path]
for key in list(current):
value = current[key]
if isinstance(value, dict):
subpath = f"{path}/{key}"
current[key] = self._handle_placeholders(spec, value, subpath)
return current
def _create_entity(self, entity_spec, uri=None):
if len(entity_spec) != 1:
self.test.fail(f"Entity spec {entity_spec} did not contain exactly one top-level key")
entity_type, spec = next(iter(entity_spec.items()))
spec = self._handle_placeholders(spec, spec, "")
if entity_type == "client":
kwargs: dict = {}
observe_events = spec.get("observeEvents", [])
# The unified tests use topologyOpeningEvent, we use topologyOpenedEvent
for i in range(len(observe_events)):
if "topologyOpeningEvent" == observe_events[i]:
observe_events[i] = "topologyOpenedEvent"
ignore_commands = spec.get("ignoreCommandMonitoringEvents", [])
observe_sensitive_commands = spec.get("observeSensitiveCommands", False)
ignore_commands = [cmd.lower() for cmd in ignore_commands]
listener = EventListenerUtil(
observe_events,
ignore_commands,
observe_sensitive_commands,
spec.get("storeEventsAsEntities"),
self,
)
self._listeners[spec["id"]] = listener
kwargs["event_listeners"] = [listener]
if spec.get("useMultipleMongoses"):
if client_context.load_balancer or client_context.serverless:
kwargs["h"] = client_context.MULTI_MONGOS_LB_URI
elif client_context.is_mongos:
kwargs["h"] = client_context.mongos_seeds()
kwargs.update(spec.get("uriOptions", {}))
server_api = spec.get("serverApi")
if "waitQueueSize" in kwargs:
raise unittest.SkipTest("PyMongo does not support waitQueueSize")
if "waitQueueMultiple" in kwargs:
raise unittest.SkipTest("PyMongo does not support waitQueueMultiple")
if server_api:
kwargs["server_api"] = ServerApi(
server_api["version"],
strict=server_api.get("strict"),
deprecation_errors=server_api.get("deprecationErrors"),
)
if uri:
kwargs["h"] = uri
client = self.test.rs_or_single_client(**kwargs)
self[spec["id"]] = client
return
elif entity_type == "database":
client = self[spec["client"]]
if type(client).__name__ != "MongoClient":
self.test.fail(
"Expected entity {} to be of type MongoClient, got {}".format(
spec["client"], type(client)
)
)
options = parse_collection_or_database_options(spec.get("databaseOptions", {}))
self[spec["id"]] = client.get_database(spec["databaseName"], **options)
return
elif entity_type == "collection":
database = self[spec["database"]]
if not isinstance(database, Database):
self.test.fail(
"Expected entity {} to be of type Database, got {}".format(
spec["database"], type(database)
)
)
options = parse_collection_or_database_options(spec.get("collectionOptions", {}))
self[spec["id"]] = database.get_collection(spec["collectionName"], **options)
return
elif entity_type == "session":
client = self[spec["client"]]
if type(client).__name__ != "MongoClient":
self.test.fail(
"Expected entity {} to be of type MongoClient, got {}".format(
spec["client"], type(client)
)
)
opts = camel_to_snake_args(spec.get("sessionOptions", {}))
if "default_transaction_options" in opts:
txn_opts = parse_spec_options(opts["default_transaction_options"])
txn_opts = TransactionOptions(**txn_opts)
opts = copy.deepcopy(opts)
opts["default_transaction_options"] = txn_opts
session = client.start_session(**dict(opts))
self[spec["id"]] = session
self._session_lsids[spec["id"]] = copy.deepcopy(session.session_id)
self.test.addCleanup(session.end_session)
return
elif entity_type == "bucket":
db = self[spec["database"]]
kwargs = parse_spec_options(spec.get("bucketOptions", {}).copy())
bucket = GridFSBucket(db, **kwargs)
# PyMongo does not support GridFSBucket.drop(), emulate it.
@_csot.apply
def drop(self: GridFSBucket, *args: Any, **kwargs: Any) -> None:
self._files.drop(*args, **kwargs)
self._chunks.drop(*args, **kwargs)
if not hasattr(bucket, "drop"):
bucket.drop = drop.__get__(bucket)
self[spec["id"]] = bucket
return
elif entity_type == "clientEncryption":
opts = camel_to_snake_args(spec["clientEncryptionOpts"].copy())
if isinstance(opts["key_vault_client"], str):
opts["key_vault_client"] = self[opts["key_vault_client"]]
# Set TLS options for providers like "kmip:name1".
kms_tls_options = {}
for provider in opts["kms_providers"]:
provider_type = provider.split(":")[0]
if provider_type in KMS_TLS_OPTS:
kms_tls_options[provider] = KMS_TLS_OPTS[provider_type]
self[spec["id"]] = ClientEncryption(
opts["kms_providers"],
opts["key_vault_namespace"],
opts["key_vault_client"],
DEFAULT_CODEC_OPTIONS,
opts.get("kms_tls_options", kms_tls_options),
)
return
elif entity_type == "thread":
name = spec["id"]
thread = SpecRunnerThread(name)
thread.start()
self[name] = thread
return
self.test.fail(f"Unable to create entity of unknown type {entity_type}")
def create_entities_from_spec(self, entity_spec, uri=None):
for spec in entity_spec:
self._create_entity(spec, uri=uri)
def get_listener_for_client(self, client_name: str) -> EventListenerUtil:
client = self[client_name]
if type(client).__name__ != "MongoClient":
self.test.fail(
f"Expected entity {client_name} to be of type MongoClient, got {type(client)}"
)
listener = self._listeners.get(client_name)
if not listener:
self.test.fail(f"No listeners configured for client {client_name}")
return listener
def get_lsid_for_session(self, session_name):
session = self[session_name]
if not isinstance(session, ClientSession):
self.test.fail(
f"Expected entity {session_name} to be of type ClientSession, got {type(session)}"
)
try:
return session.session_id
except InvalidOperation:
# session has been closed.
return self._session_lsids[session_name]
def advance_cluster_times(self) -> None:
"""Manually synchronize entities when desired"""
if not self._cluster_time:
self._cluster_time = (self.test.client.admin.command("ping")).get("$clusterTime")
for entity in self._entities.values():
if isinstance(entity, ClientSession) and self._cluster_time:
entity.advance_cluster_time(self._cluster_time)
class UnifiedSpecTestMixinV1(IntegrationTest):
"""Mixin class to run test cases from test specification files.
Assumes that tests conform to the `unified test format
<https://github.com/mongodb/specifications/blob/master/source/unified-test-format/unified-test-format.md>`_.
Specification of the test suite being currently run is available as
a class attribute ``TEST_SPEC``.
"""
SCHEMA_VERSION = Version.from_string("1.21")
RUN_ON_LOAD_BALANCER = True
RUN_ON_SERVERLESS = True
TEST_SPEC: Any
TEST_PATH = "" # This gets filled in by generate_test_classes
mongos_clients: list[MongoClient] = []
@staticmethod
def should_run_on(run_on_spec):
if not run_on_spec:
# Always run these tests.
return True
for req in run_on_spec:
if is_run_on_requirement_satisfied(req):
return True
return False
def insert_initial_data(self, initial_data):
for i, collection_data in enumerate(initial_data):
coll_name = collection_data["collectionName"]
db_name = collection_data["databaseName"]
opts = collection_data.get("createOptions", {})
documents = collection_data["documents"]
# Setup the collection with as few majority writes as possible.
db = self.client[db_name]
db.drop_collection(coll_name)
# Only use majority wc only on the final write.
if i == len(initial_data) - 1:
wc = WriteConcern(w="majority")
else:
wc = WriteConcern(w=1)
if documents:
if opts:
db.create_collection(coll_name, **opts)
db.get_collection(coll_name, write_concern=wc).insert_many(documents)
else:
# Ensure collection exists
db.create_collection(coll_name, write_concern=wc, **opts)
@classmethod
def setUpClass(cls) -> None:
# Speed up the tests by decreasing the heartbeat frequency.
cls.knobs = client_knobs(
heartbeat_frequency=0.1,
min_heartbeat_interval=0.1,
kill_cursor_frequency=0.1,
events_queue_frequency=0.1,
)
cls.knobs.enable()
@classmethod
def tearDownClass(cls) -> None:
cls.knobs.disable()
def setUp(self):
# super call creates internal client cls.client
super().setUp()
# process file-level runOnRequirements
run_on_spec = self.TEST_SPEC.get("runOnRequirements", [])
if not self.should_run_on(run_on_spec):
raise unittest.SkipTest(f"{self.__class__.__name__} runOnRequirements not satisfied")
# add any special-casing for skipping tests here
if client_context.storage_engine == "mmapv1":
if "retryable-writes" in self.TEST_SPEC["description"] or "retryable_writes" in str(
self.TEST_PATH
):
raise unittest.SkipTest("MMAPv1 does not support retryWrites=True")
# Handle mongos_clients for transactions tests.
self.mongos_clients = []
if (
client_context.supports_transactions()
and not client_context.load_balancer
and not client_context.serverless
):
for address in client_context.mongoses:
self.mongos_clients.append(self.single_client("{}:{}".format(*address)))
# process schemaVersion
# note: we check major schema version during class generation
version = Version.from_string(self.TEST_SPEC["schemaVersion"])
self.assertLessEqual(
version,
self.SCHEMA_VERSION,
f"expected schema version {self.SCHEMA_VERSION} or lower, got {version}",
)
# initialize internals
self.match_evaluator = MatchEvaluatorUtil(self)
def maybe_skip_test(self, spec):
# add any special-casing for skipping tests here
if client_context.storage_engine == "mmapv1":
if (
"Dirty explicit session is discarded" in spec["description"]
or "Dirty implicit session is discarded" in spec["description"]
or "Cancel server check" in spec["description"]
):
self.skipTest("MMAPv1 does not support retryWrites=True")
if "Client side error in command starting transaction" in spec["description"]:
self.skipTest("Implement PYTHON-1894")
if "timeoutMS applied to entire download" in spec["description"]:
self.skipTest("PyMongo's open_download_stream does not cap the stream's lifetime")
class_name = self.__class__.__name__.lower()
description = spec["description"].lower()
if "csot" in class_name:
if "gridfs" in class_name and sys.platform == "win32":
self.skipTest("PYTHON-3522 CSOT GridFS tests are flaky on Windows")
if client_context.storage_engine == "mmapv1":
self.skipTest(
"MMAPv1 does not support retryable writes which is required for CSOT tests"
)
if "change" in description or "change" in class_name:
self.skipTest("CSOT not implemented for watch()")
if "cursors" in class_name:
self.skipTest("CSOT not implemented for cursors")
if "tailable" in class_name:
self.skipTest("CSOT not implemented for tailable cursors")
if "sessions" in class_name:
self.skipTest("CSOT not implemented for sessions")
if "withtransaction" in description:
self.skipTest("CSOT not implemented for with_transaction")
if "transaction" in class_name or "transaction" in description:
self.skipTest("CSOT not implemented for transactions")
# Some tests need to be skipped based on the operations they try to run.
for op in spec["operations"]:
name = op["name"]
if name == "count":
self.skipTest("PyMongo does not support count()")
if name == "listIndexNames":
self.skipTest("PyMongo does not support list_index_names()")
if client_context.storage_engine == "mmapv1":
if name == "createChangeStream":
self.skipTest("MMAPv1 does not support change streams")
if name == "withTransaction" or name == "startTransaction":
self.skipTest("MMAPv1 does not support document-level locking")
if not client_context.test_commands_enabled:
if name == "failPoint" or name == "targetedFailPoint":
self.skipTest("Test commands must be enabled to use fail points")
if name == "modifyCollection":
self.skipTest("PyMongo does not support modifyCollection")
if "timeoutMode" in op.get("arguments", {}):
self.skipTest("PyMongo does not support timeoutMode")
def process_error(self, exception, spec):
if isinstance(exception, unittest.SkipTest):
raise
is_error = spec.get("isError")
is_client_error = spec.get("isClientError")
is_timeout_error = spec.get("isTimeoutError")
error_contains = spec.get("errorContains")
error_code = spec.get("errorCode")
error_code_name = spec.get("errorCodeName")
error_labels_contain = spec.get("errorLabelsContain")
error_labels_omit = spec.get("errorLabelsOmit")
expect_result = spec.get("expectResult")
error_response = spec.get("errorResponse")
if error_response:
if isinstance(exception, ClientBulkWriteException):
self.match_evaluator.match_result(error_response, exception.error.details)
else:
self.match_evaluator.match_result(error_response, exception.details)
if is_error:
# already satisfied because exception was raised
pass
if is_client_error:
if isinstance(exception, ClientBulkWriteException):
error = exception.error
else:
error = exception
# Connection errors are considered client errors.
if isinstance(error, ConnectionFailure):
self.assertNotIsInstance(error, NotPrimaryError)
elif isinstance(error, (InvalidOperation, ConfigurationError, EncryptionError)):
pass
else:
self.assertNotIsInstance(error, PyMongoError)
if is_timeout_error:
self.assertIsInstance(exception, PyMongoError)
if not exception.timeout:
# Re-raise the exception for better diagnostics.
raise exception
if error_contains:
if isinstance(exception, BulkWriteError):
errmsg = str(exception.details).lower()
elif isinstance(exception, ClientBulkWriteException):
errmsg = str(exception.details).lower()
else:
errmsg = str(exception).lower()
self.assertIn(error_contains.lower(), errmsg)
if error_code:
if isinstance(exception, ClientBulkWriteException):
self.assertEqual(error_code, exception.error.details.get("code"))
else:
self.assertEqual(error_code, exception.details.get("code"))
if error_code_name:
if isinstance(exception, ClientBulkWriteException):
self.assertEqual(error_code, exception.error.details.get("codeName"))
else:
self.assertEqual(error_code_name, exception.details.get("codeName"))
if error_labels_contain:
if isinstance(exception, ClientBulkWriteException):
error = exception.error
else:
error = exception
labels = [
err_label for err_label in error_labels_contain if error.has_error_label(err_label)
]
self.assertEqual(labels, error_labels_contain)
if error_labels_omit:
for err_label in error_labels_omit:
if exception.has_error_label(err_label):
self.fail(f"Exception '{exception}' unexpectedly had label '{err_label}'")
if expect_result:
if isinstance(exception, BulkWriteError):
result = parse_bulk_write_error_result(exception)
self.match_evaluator.match_result(expect_result, result)
elif isinstance(exception, ClientBulkWriteException):
result = parse_client_bulk_write_error_result(exception)
self.match_evaluator.match_result(expect_result, result)
else:
self.fail(
f"expectResult can only be specified with {BulkWriteError} or {ClientBulkWriteException} exceptions"
)
return exception
def __raise_if_unsupported(self, opname, target, *target_types):
if not isinstance(target, target_types):
self.fail(f"Operation {opname} not supported for entity of type {type(target)}")
def __entityOperation_createChangeStream(self, target, *args, **kwargs):
if client_context.storage_engine == "mmapv1":
self.skipTest("MMAPv1 does not support change streams")
self.__raise_if_unsupported("createChangeStream", target, MongoClient, Database, Collection)
stream = target.watch(*args, **kwargs)
self.addCleanup(stream.close)
return stream
def _clientOperation_createChangeStream(self, target, *args, **kwargs):
return self.__entityOperation_createChangeStream(target, *args, **kwargs)
def _databaseOperation_createChangeStream(self, target, *args, **kwargs):
return self.__entityOperation_createChangeStream(target, *args, **kwargs)
def _collectionOperation_createChangeStream(self, target, *args, **kwargs):
return self.__entityOperation_createChangeStream(target, *args, **kwargs)
def _databaseOperation_runCommand(self, target, **kwargs):
self.__raise_if_unsupported("runCommand", target, Database)
# Ensure the first key is the command name.
ordered_command = SON([(kwargs.pop("command_name"), 1)])
ordered_command.update(kwargs["command"])
kwargs["command"] = ordered_command
return target.command(**kwargs)
def _databaseOperation_runCursorCommand(self, target, **kwargs):
return (self._databaseOperation_createCommandCursor(target, **kwargs)).to_list()
def _databaseOperation_createCommandCursor(self, target, **kwargs):
self.__raise_if_unsupported("createCommandCursor", target, Database)
# Ensure the first key is the command name.
ordered_command = SON([(kwargs.pop("command_name"), 1)])
ordered_command.update(kwargs["command"])
kwargs["command"] = ordered_command
batch_size = 0
cursor_type = kwargs.pop("cursor_type", "nonTailable")
if cursor_type == CursorType.TAILABLE:
ordered_command["tailable"] = True
elif cursor_type == CursorType.TAILABLE_AWAIT:
ordered_command["tailable"] = True
ordered_command["awaitData"] = True
elif cursor_type != "nonTailable":
self.fail(f"unknown cursorType: {cursor_type}")
if "maxTimeMS" in kwargs:
kwargs["max_await_time_ms"] = kwargs.pop("maxTimeMS")
if "batch_size" in kwargs:
batch_size = kwargs.pop("batch_size")
cursor = target.cursor_command(**kwargs)
if batch_size > 0:
cursor.batch_size(batch_size)
return cursor
def kill_all_sessions(self):
if getattr(self, "client", None) is None:
return
clients = self.mongos_clients if self.mongos_clients else [self.client]
for client in clients:
try:
client.admin.command("killAllSessions", [])
except (OperationFailure, AutoReconnect):
# "operation was interrupted" by killing the command's
# own session.
# On 8.0+ killAllSessions sometimes returns a network error.
pass
def _databaseOperation_listCollections(self, target, *args, **kwargs):
if "batch_size" in kwargs:
kwargs["cursor"] = {"batchSize": kwargs.pop("batch_size")}
cursor = target.list_collections(*args, **kwargs)
return cursor.to_list()
def _databaseOperation_createCollection(self, target, *args, **kwargs):
# PYTHON-1936 Ignore the listCollections event from create_collection.
kwargs["check_exists"] = False
ret = target.create_collection(*args, **kwargs)
return ret
def __entityOperation_aggregate(self, target, *args, **kwargs):
self.__raise_if_unsupported("aggregate", target, Database, Collection)
return (target.aggregate(*args, **kwargs)).to_list()
def _databaseOperation_aggregate(self, target, *args, **kwargs):
return self.__entityOperation_aggregate(target, *args, **kwargs)
def _collectionOperation_aggregate(self, target, *args, **kwargs):
return self.__entityOperation_aggregate(target, *args, **kwargs)
def _collectionOperation_find(self, target, *args, **kwargs):
self.__raise_if_unsupported("find", target, Collection)
find_cursor = target.find(*args, **kwargs)
return find_cursor.to_list()
def _collectionOperation_createFindCursor(self, target, *args, **kwargs):
self.__raise_if_unsupported("find", target, Collection)
if "filter" not in kwargs:
self.fail('createFindCursor requires a "filter" argument')
cursor = NonLazyCursor.create(target.find(*args, **kwargs), target.database.client)
self.addCleanup(cursor.close)
return cursor
def _collectionOperation_count(self, target, *args, **kwargs):
self.skipTest("PyMongo does not support collection.count()")
def _collectionOperation_listIndexes(self, target, *args, **kwargs):
if "batch_size" in kwargs:
self.skipTest("PyMongo does not support batch_size for list_indexes")
return (target.list_indexes(*args, **kwargs)).to_list()
def _collectionOperation_listIndexNames(self, target, *args, **kwargs):
self.skipTest("PyMongo does not support list_index_names")
def _collectionOperation_createSearchIndexes(self, target, *args, **kwargs):
models = [SearchIndexModel(**i) for i in kwargs["models"]]
return target.create_search_indexes(models)
def _collectionOperation_listSearchIndexes(self, target, *args, **kwargs):
name = kwargs.get("name")
agg_kwargs = kwargs.get("aggregation_options", dict())
return (target.list_search_indexes(name, **agg_kwargs)).to_list()
def _sessionOperation_withTransaction(self, target, *args, **kwargs):
if client_context.storage_engine == "mmapv1":
self.skipTest("MMAPv1 does not support document-level locking")
self.__raise_if_unsupported("withTransaction", target, ClientSession)
return target.with_transaction(*args, **kwargs)
def _sessionOperation_startTransaction(self, target, *args, **kwargs):
if client_context.storage_engine == "mmapv1":
self.skipTest("MMAPv1 does not support document-level locking")
self.__raise_if_unsupported("startTransaction", target, ClientSession)
return target.start_transaction(*args, **kwargs)
def _changeStreamOperation_iterateUntilDocumentOrError(self, target, *args, **kwargs):
self.__raise_if_unsupported("iterateUntilDocumentOrError", target, ChangeStream)
return next(target)
def _cursor_iterateUntilDocumentOrError(self, target, *args, **kwargs):
self.__raise_if_unsupported(
"iterateUntilDocumentOrError", target, NonLazyCursor, CommandCursor
)
while target.alive:
try:
return next(target)
except StopIteration:
pass
return None
def _cursor_close(self, target, *args, **kwargs):
self.__raise_if_unsupported("close", target, NonLazyCursor, CommandCursor)
return target.close()
def _clientEncryptionOperation_createDataKey(self, target, *args, **kwargs):
if "opts" in kwargs:
kwargs.update(camel_to_snake_args(kwargs.pop("opts")))
return target.create_data_key(*args, **kwargs)
def _clientEncryptionOperation_getKeys(self, target, *args, **kwargs):
return target.get_keys(*args, **kwargs).to_list()
def _clientEncryptionOperation_deleteKey(self, target, *args, **kwargs):
result = target.delete_key(*args, **kwargs)
response = result.raw_result
response["deletedCount"] = result.deleted_count
return response
def _clientEncryptionOperation_rewrapManyDataKey(self, target, *args, **kwargs):
if "opts" in kwargs:
kwargs.update(camel_to_snake_args(kwargs.pop("opts")))
data = target.rewrap_many_data_key(*args, **kwargs)
if data.bulk_write_result:
return {"bulkWriteResult": parse_bulk_write_result(data.bulk_write_result)}
return {}
def _clientEncryptionOperation_encrypt(self, target, *args, **kwargs):
if "opts" in kwargs:
kwargs.update(camel_to_snake_args(kwargs.pop("opts")))
return target.encrypt(*args, **kwargs)
def _bucketOperation_download(self, target: GridFSBucket, *args: Any, **kwargs: Any) -> bytes:
with target.open_download_stream(*args, **kwargs) as gout:
return gout.read()
def _bucketOperation_downloadByName(
self, target: GridFSBucket, *args: Any, **kwargs: Any
) -> bytes:
with target.open_download_stream_by_name(*args, **kwargs) as gout:
return gout.read()
def _bucketOperation_upload(self, target: GridFSBucket, *args: Any, **kwargs: Any) -> ObjectId:
kwargs["source"] = binascii.unhexlify(kwargs.pop("source")["$$hexBytes"])
if "content_type" in kwargs:
kwargs.setdefault("metadata", {})["contentType"] = kwargs.pop("content_type")
return target.upload_from_stream(*args, **kwargs)
def _bucketOperation_uploadWithId(self, target: GridFSBucket, *args: Any, **kwargs: Any) -> Any:
kwargs["source"] = binascii.unhexlify(kwargs.pop("source")["$$hexBytes"])
if "content_type" in kwargs:
kwargs.setdefault("metadata", {})["contentType"] = kwargs.pop("content_type")
return target.upload_from_stream_with_id(*args, **kwargs)
def _bucketOperation_find(
self, target: GridFSBucket, *args: Any, **kwargs: Any
) -> List[GridOut]:
return target.find(*args, **kwargs).to_list()
def run_entity_operation(self, spec):
target = self.entity_map[spec["object"]]
opname = spec["name"]
opargs = spec.get("arguments")
expect_error = spec.get("expectError")
save_as_entity = spec.get("saveResultAsEntity")
expect_result = spec.get("expectResult")
ignore = spec.get("ignoreResultAndError")
if ignore and (expect_error or save_as_entity or expect_result):
raise ValueError(
"ignoreResultAndError is incompatible with saveResultAsEntity"
", expectError, and expectResult"
)
if opargs:
arguments = parse_spec_options(copy.deepcopy(opargs))
prepare_spec_arguments(
spec,
arguments,
camel_to_snake(opname),
self.entity_map,
self.run_operations_and_throw,
)
else:
arguments = {}
if isinstance(target, MongoClient):
method_name = f"_clientOperation_{opname}"
elif isinstance(target, Database):
method_name = f"_databaseOperation_{opname}"
elif isinstance(target, Collection):
method_name = f"_collectionOperation_{opname}"
# contentType is always stored in metadata in pymongo.
if target.name.endswith(".files") and opname == "find":
for doc in spec.get("expectResult", []):
if "contentType" in doc:
doc.setdefault("metadata", {})["contentType"] = doc.pop("contentType")
elif isinstance(target, ChangeStream):
method_name = f"_changeStreamOperation_{opname}"
elif isinstance(target, (NonLazyCursor, CommandCursor)):
method_name = f"_cursor_{opname}"
elif isinstance(target, ClientSession):
method_name = f"_sessionOperation_{opname}"
elif isinstance(target, GridFSBucket):
method_name = f"_bucketOperation_{opname}"
if "id" in arguments:
arguments["file_id"] = arguments.pop("id")
# MD5 is always disabled in pymongo.
arguments.pop("disable_md5", None)
elif isinstance(target, ClientEncryption):
method_name = f"_clientEncryptionOperation_{opname}"
else:
method_name = "doesNotExist"
try:
method = getattr(self, method_name)
except AttributeError:
target_opname = camel_to_snake(opname)
if target_opname == "iterate_once":
target_opname = "try_next"
if target_opname == "client_bulk_write":
target_opname = "bulk_write"
try:
cmd = getattr(target, target_opname)
except AttributeError:
self.fail(f"Unsupported operation {opname} on entity {target}")
else:
cmd = functools.partial(method, target)
try:
# CSOT: Translate the spec test "timeout" arg into pymongo's context timeout API.
if "timeout" in arguments:
timeout = arguments.pop("timeout")
with pymongo.timeout(timeout):
result = cmd(**dict(arguments))
else:
result = cmd(**dict(arguments))
except Exception as exc:
# Ignore all operation errors but to avoid masking bugs don't
# ignore things like TypeError and ValueError.
if ignore and isinstance(exc, (PyMongoError,)):
return exc
if expect_error:
if method_name == "_collectionOperation_bulkWrite":
self.skipTest("Skipping test pending PYTHON-4598")
return self.process_error(exc, expect_error)
raise
else:
if method_name == "_collectionOperation_bulkWrite":
self.skipTest("Skipping test pending PYTHON-4598")
if expect_error:
self.fail(f'Excepted error {expect_error} but "{opname}" succeeded: {result}')
if expect_result:
actual = coerce_result(opname, result)
self.match_evaluator.match_result(expect_result, actual)
if save_as_entity:
self.entity_map[save_as_entity] = result
return None
return None
def __set_fail_point(self, client, command_args):
if not client_context.test_commands_enabled:
self.skipTest("Test commands must be enabled")