From d9ca03a69888f75ff89751ccdc3b59c1b4e4683b Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Thu, 29 Aug 2024 11:11:23 -0400 Subject: [PATCH 1/7] PYTHON-4590 - Add type guards to async API methods --- pymongo/asynchronous/bulk.py | 28 ++++++++++++++++++++++++++ pymongo/asynchronous/client_session.py | 15 ++++++++++++++ pymongo/asynchronous/collection.py | 6 ++++++ pymongo/asynchronous/database.py | 7 +++++++ pymongo/asynchronous/encryption.py | 25 +++++++++++++++++++++++ pymongo/asynchronous/mongo_client.py | 10 +++++++++ pymongo/asynchronous/pool.py | 7 +++++++ pymongo/asynchronous/server.py | 7 +++++++ pymongo/synchronous/bulk.py | 20 ++++++++++++++++++ pymongo/synchronous/client_session.py | 11 ++++++++++ pymongo/synchronous/collection.py | 6 ++++++ pymongo/synchronous/database.py | 5 +++++ pymongo/synchronous/encryption.py | 23 +++++++++++++++++++++ pymongo/synchronous/mongo_client.py | 8 ++++++++ pymongo/synchronous/pool.py | 5 +++++ pymongo/synchronous/server.py | 5 +++++ test/helpers.py | 10 --------- 17 files changed, 188 insertions(+), 10 deletions(-) diff --git a/pymongo/asynchronous/bulk.py b/pymongo/asynchronous/bulk.py index c200899dd1..61b5044672 100644 --- a/pymongo/asynchronous/bulk.py +++ b/pymongo/asynchronous/bulk.py @@ -239,7 +239,14 @@ async def write_command( docs: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> dict[str, Any]: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + """A proxy for SocketInfo.write_command that handles event publishing.""" + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -324,6 +331,13 @@ async def unack_write( client: AsyncMongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for AsyncConnection.unack_write that handles event publishing.""" + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( _COMMAND_LOGGER, @@ -410,6 +424,13 @@ async def _execute_batch_unack( ops: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> list[Mapping[str, Any]]: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) await bwc.conn.command( # type: ignore[misc] @@ -437,6 +458,13 @@ async def _execute_batch( ops: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> tuple[dict[str, Any], list[Mapping[str, Any]]]: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) result = await bwc.conn.command( # type: ignore[misc] diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 2aff95ee51..48c114249e 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -176,6 +176,7 @@ if TYPE_CHECKING: from types import TracebackType + from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection from pymongo.asynchronous.server import Server from pymongo.typings import ClusterTime, _Address @@ -395,6 +396,13 @@ class _Transaction: """Internal class to hold transaction information in a AsyncClientSession.""" def __init__(self, opts: Optional[TransactionOptions], client: AsyncMongoClient): + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + self.opts = opts self.state = _TxnState.NONE self.sharded = False @@ -502,6 +510,13 @@ def __init__( options: SessionOptions, implicit: bool, ) -> None: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + # An AsyncMongoClient, a _ServerSession, a SessionOptions, and a set. self._client: AsyncMongoClient = client self._server_session = server_session diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index b05a922029..3a6dd30ce8 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -228,6 +228,12 @@ def __init__( ) if not isinstance(name, str): raise TypeError("name must be an instance of str") + from pymongo.asynchronous.database import AsyncDatabase + + if not isinstance(database, AsyncDatabase): + raise TypeError( + f"AsyncCollection requires an AsyncDatabase, {database} is an instance of {type(database)}" + ) if not name or ".." in name: raise InvalidName("collection names cannot be empty") diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index 4bdf0ff51f..25320b3d3a 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -119,9 +119,16 @@ def __init__( read_concern or client.read_concern, ) + from pymongo.asynchronous.mongo_client import AsyncMongoClient + if not isinstance(name, str): raise TypeError("name must be an instance of str") + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + if name != "$external": _check_name(name) diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index b1a36eefa3..c8ad3966a0 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -207,6 +207,11 @@ async def collection_info( :return: The first document from the listCollections command response as BSON. """ + if not isinstance(database, AsyncDatabase): + raise TypeError( + f"collection_info() requires an AsyncDatabase, {database} is an instance of {type(database)}" + ) + async with self.client_ref()[database].list_collections( filter=RawBSONDocument(filter) ) as cursor: @@ -339,6 +344,11 @@ def __init__(self, client: AsyncMongoClient[_DocumentTypeArg], opts: AutoEncrypt :param client: The encrypted AsyncMongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + if opts._schema_map is None: schema_map = None else: @@ -354,6 +364,11 @@ def __init__(self, client: AsyncMongoClient[_DocumentTypeArg], opts: AutoEncrypt def _get_internal_client( encrypter: _Encrypter, mongo_client: AsyncMongoClient[_DocumentTypeArg] ) -> AsyncMongoClient[_DocumentTypeArg]: + if not isinstance(mongo_client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {mongo_client} is an instance of {type(mongo_client)}" + ) + if mongo_client.options.pool_options.max_pool_size is None: # Unlimited pool size, use the same client. return mongo_client @@ -598,6 +613,11 @@ def __init__( if not isinstance(codec_options, CodecOptions): raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions") + if not isinstance(key_vault_client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {key_vault_client} is an instance of {type(key_vault_client)}" + ) + self._kms_providers = kms_providers self._key_vault_namespace = key_vault_namespace self._key_vault_client = key_vault_client @@ -683,6 +703,11 @@ async def create_encrypted_collection( https://mongodb.com/docs/manual/reference/command/create """ + if not isinstance(database, AsyncDatabase): + raise TypeError( + f"create_encrypted_collection() requires an AsyncDatabase, {database} is an instance of {type(database)}" + ) + encrypted_fields = deepcopy(encrypted_fields) for i, field in enumerate(encrypted_fields["fields"]): if isinstance(field, dict) and field.get("keyId") is None: diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index a320249b4d..eaf3bec72b 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -2265,6 +2265,11 @@ class _MongoClientErrorHandler: def __init__( self, client: AsyncMongoClient, server: Server, session: Optional[AsyncClientSession] ): + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + self.client = client self.server_address = server.description.address self.session = session @@ -2339,6 +2344,11 @@ def __init__( retryable: bool = False, operation_id: Optional[int] = None, ): + if not isinstance(mongo_client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {mongo_client} is an instance of {type(mongo_client)}" + ) + self._last_error: Optional[Exception] = None self._retrying = False self._multiple_retries = _csot.get_timeout() is not None diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index a657042423..911a4651c2 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -323,6 +323,13 @@ def set_conn_timeout(self, timeout: Optional[float]) -> None: def apply_timeout( self, client: AsyncMongoClient, cmd: Optional[MutableMapping[str, Any]] ) -> Optional[float]: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + # CSOT: use remaining timeout when set. timeout = _csot.remaining() if timeout is None: diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index 892594c97d..07ffea99d3 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -142,7 +142,14 @@ async def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: An AsyncMongoClient instance. """ + from pymongo.asynchronous.mongo_client import AsyncMongoClient + assert listeners is not None + if not isinstance(client, AsyncMongoClient): + raise TypeError( + f"AsyncMongoClient required but {client} is an instance of {type(client)}" + ) + publish = listeners.enabled_for_commands start = datetime.now() diff --git a/pymongo/synchronous/bulk.py b/pymongo/synchronous/bulk.py index 4da64c4a78..e127bb8b5a 100644 --- a/pymongo/synchronous/bulk.py +++ b/pymongo/synchronous/bulk.py @@ -239,7 +239,12 @@ def write_command( docs: list[Mapping[str, Any]], client: MongoClient, ) -> dict[str, Any]: + from pymongo.synchronous.mongo_client import MongoClient + """A proxy for SocketInfo.write_command that handles event publishing.""" + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -324,6 +329,11 @@ def unack_write( client: MongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for Connection.unack_write that handles event publishing.""" + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( _COMMAND_LOGGER, @@ -410,6 +420,11 @@ def _execute_batch_unack( ops: list[Mapping[str, Any]], client: MongoClient, ) -> list[Mapping[str, Any]]: + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) bwc.conn.command( # type: ignore[misc] @@ -437,6 +452,11 @@ def _execute_batch( ops: list[Mapping[str, Any]], client: MongoClient, ) -> tuple[dict[str, Any], list[Mapping[str, Any]]]: + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) result = bwc.conn.command( # type: ignore[misc] diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index e07298b49a..d68360fb2e 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -175,6 +175,7 @@ if TYPE_CHECKING: from types import TracebackType + from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection from pymongo.synchronous.server import Server from pymongo.typings import ClusterTime, _Address @@ -394,6 +395,11 @@ class _Transaction: """Internal class to hold transaction information in a ClientSession.""" def __init__(self, opts: Optional[TransactionOptions], client: MongoClient): + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + self.opts = opts self.state = _TxnState.NONE self.sharded = False @@ -501,6 +507,11 @@ def __init__( options: SessionOptions, implicit: bool, ) -> None: + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + # A MongoClient, a _ServerSession, a SessionOptions, and a set. self._client: MongoClient = client self._server_session = server_session diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index 5803e34b2a..2484eda1df 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -231,6 +231,12 @@ def __init__( ) if not isinstance(name, str): raise TypeError("name must be an instance of str") + from pymongo.synchronous.database import Database + + if not isinstance(database, Database): + raise TypeError( + f"Collection requires a Database, {database} is an instance of {type(database)}" + ) if not name or ".." in name: raise InvalidName("collection names cannot be empty") diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 3b3a91095a..859e6980a8 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -119,9 +119,14 @@ def __init__( read_concern or client.read_concern, ) + from pymongo.synchronous.mongo_client import MongoClient + if not isinstance(name, str): raise TypeError("name must be an instance of str") + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + if name != "$external": _check_name(name) diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index e06ddad93d..5bb711e726 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -207,6 +207,11 @@ def collection_info( :return: The first document from the listCollections command response as BSON. """ + if not isinstance(database, Database): + raise TypeError( + f"collection_info() requires a Database, {database} is an instance of {type(database)}" + ) + with self.client_ref()[database].list_collections(filter=RawBSONDocument(filter)) as cursor: for doc in cursor: return _dict_to_bson(doc, False, _DATA_KEY_OPTS) @@ -337,6 +342,9 @@ def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOp :param client: The encrypted MongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + if opts._schema_map is None: schema_map = None else: @@ -352,6 +360,11 @@ def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOp def _get_internal_client( encrypter: _Encrypter, mongo_client: MongoClient[_DocumentTypeArg] ) -> MongoClient[_DocumentTypeArg]: + if not isinstance(mongo_client, MongoClient): + raise TypeError( + f"MongoClient required but {mongo_client} is an instance of {type(mongo_client)}" + ) + if mongo_client.options.pool_options.max_pool_size is None: # Unlimited pool size, use the same client. return mongo_client @@ -596,6 +609,11 @@ def __init__( if not isinstance(codec_options, CodecOptions): raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions") + if not isinstance(key_vault_client, MongoClient): + raise TypeError( + f"MongoClient required but {key_vault_client} is an instance of {type(key_vault_client)}" + ) + self._kms_providers = kms_providers self._key_vault_namespace = key_vault_namespace self._key_vault_client = key_vault_client @@ -681,6 +699,11 @@ def create_encrypted_collection( https://mongodb.com/docs/manual/reference/command/create """ + if not isinstance(database, Database): + raise TypeError( + f"create_encrypted_collection() requires a Database, {database} is an instance of {type(database)}" + ) + encrypted_fields = deepcopy(encrypted_fields) for i, field in enumerate(encrypted_fields["fields"]): if isinstance(field, dict) and field.get("keyId") is None: diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index bd14311b5a..c18efeea32 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -2252,6 +2252,9 @@ class _MongoClientErrorHandler: ) def __init__(self, client: MongoClient, server: Server, session: Optional[ClientSession]): + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + self.client = client self.server_address = server.description.address self.session = session @@ -2326,6 +2329,11 @@ def __init__( retryable: bool = False, operation_id: Optional[int] = None, ): + if not isinstance(mongo_client, MongoClient): + raise TypeError( + f"MongoClient required but {mongo_client} is an instance of {type(mongo_client)}" + ) + self._last_error: Optional[Exception] = None self._retrying = False self._multiple_retries = _csot.get_timeout() is not None diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 94a1d10436..6d6fb803e6 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -323,6 +323,11 @@ def set_conn_timeout(self, timeout: Optional[float]) -> None: def apply_timeout( self, client: MongoClient, cmd: Optional[MutableMapping[str, Any]] ) -> Optional[float]: + from pymongo.synchronous.mongo_client import MongoClient + + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + # CSOT: use remaining timeout when set. timeout = _csot.remaining() if timeout is None: diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index 347155784f..947d74ae91 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -142,7 +142,12 @@ def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: A MongoClient instance. """ + from pymongo.synchronous.mongo_client import MongoClient + assert listeners is not None + if not isinstance(client, MongoClient): + raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + publish = listeners.enabled_for_commands start = datetime.now() diff --git a/test/helpers.py b/test/helpers.py index d136e5b8d2..b38b2e2980 100644 --- a/test/helpers.py +++ b/test/helpers.py @@ -35,23 +35,13 @@ HAVE_IPADDRESS = True except ImportError: HAVE_IPADDRESS = False -from contextlib import contextmanager from functools import wraps -from test.version import Version from typing import Any, Callable, Dict, Generator, no_type_check from unittest import SkipTest -from urllib.parse import quote_plus -import pymongo -import pymongo.errors from bson.son import SON from pymongo import common, message -from pymongo.common import partition_node -from pymongo.hello import HelloCompat -from pymongo.server_api import ServerApi from pymongo.ssl_support import HAVE_SSL, _ssl # type:ignore[attr-defined] -from pymongo.synchronous.database import Database -from pymongo.synchronous.mongo_client import MongoClient from pymongo.uri_parser import parse_uri if HAVE_SSL: From efce7c3d8eec9133dd761fa8b490d99f4910a51f Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Thu, 29 Aug 2024 11:37:36 -0400 Subject: [PATCH 2/7] Fix collection_info signature --- pymongo/asynchronous/encryption.py | 9 +-------- pymongo/synchronous/encryption.py | 9 +-------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index 9245cdd4f3..b8a7b5737e 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -194,9 +194,7 @@ async def kms_request(self, kms_context: MongoCryptKmsContext) -> None: # Wrap I/O errors in PyMongo exceptions. _raise_connection_failure((host, port), error) - async def collection_info( - self, database: AsyncDatabase[Mapping[str, Any]], filter: bytes - ) -> Optional[bytes]: + async def collection_info(self, database: str, filter: bytes) -> Optional[bytes]: """Get the collection info for a namespace. The returned collection info is passed to libmongocrypt which reads @@ -207,11 +205,6 @@ async def collection_info( :return: The first document from the listCollections command response as BSON. """ - if not isinstance(database, AsyncDatabase): - raise TypeError( - f"collection_info() requires an AsyncDatabase, {database} is an instance of {type(database)}" - ) - async with await self.client_ref()[database].list_collections( filter=RawBSONDocument(filter) ) as cursor: diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 5bb711e726..8d53474d7f 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -194,9 +194,7 @@ def kms_request(self, kms_context: MongoCryptKmsContext) -> None: # Wrap I/O errors in PyMongo exceptions. _raise_connection_failure((host, port), error) - def collection_info( - self, database: Database[Mapping[str, Any]], filter: bytes - ) -> Optional[bytes]: + def collection_info(self, database: str, filter: bytes) -> Optional[bytes]: """Get the collection info for a namespace. The returned collection info is passed to libmongocrypt which reads @@ -207,11 +205,6 @@ def collection_info( :return: The first document from the listCollections command response as BSON. """ - if not isinstance(database, Database): - raise TypeError( - f"collection_info() requires a Database, {database} is an instance of {type(database)}" - ) - with self.client_ref()[database].list_collections(filter=RawBSONDocument(filter)) as cursor: for doc in cursor: return _dict_to_bson(doc, False, _DATA_KEY_OPTS) From 438b9c9b8ff5743ff5d36f51464f4f188677d341 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Fri, 30 Aug 2024 10:55:34 -0400 Subject: [PATCH 3/7] Consolidate checks --- pymongo/asynchronous/bulk.py | 26 -------------------------- pymongo/asynchronous/client_session.py | 14 -------------- pymongo/asynchronous/encryption.py | 11 +---------- pymongo/asynchronous/mongo_client.py | 5 ----- pymongo/asynchronous/pool.py | 7 ------- pymongo/asynchronous/server.py | 5 ----- pymongo/synchronous/bulk.py | 18 ------------------ pymongo/synchronous/client_session.py | 10 ---------- pymongo/synchronous/encryption.py | 9 +-------- pymongo/synchronous/mongo_client.py | 5 ----- pymongo/synchronous/pool.py | 5 ----- pymongo/synchronous/server.py | 3 --- 12 files changed, 2 insertions(+), 116 deletions(-) diff --git a/pymongo/asynchronous/bulk.py b/pymongo/asynchronous/bulk.py index 61b5044672..44230f4030 100644 --- a/pymongo/asynchronous/bulk.py +++ b/pymongo/asynchronous/bulk.py @@ -239,13 +239,7 @@ async def write_command( docs: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> dict[str, Any]: - from pymongo.asynchronous.mongo_client import AsyncMongoClient - """A proxy for SocketInfo.write_command that handles event publishing.""" - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): @@ -331,12 +325,6 @@ async def unack_write( client: AsyncMongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for AsyncConnection.unack_write that handles event publishing.""" - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -424,13 +412,6 @@ async def _execute_batch_unack( ops: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> list[Mapping[str, Any]]: - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) - if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) await bwc.conn.command( # type: ignore[misc] @@ -458,13 +439,6 @@ async def _execute_batch( ops: list[Mapping[str, Any]], client: AsyncMongoClient, ) -> tuple[dict[str, Any], list[Mapping[str, Any]]]: - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) - if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) result = await bwc.conn.command( # type: ignore[misc] diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 554c69bd20..86db6771a3 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -396,13 +396,6 @@ class _Transaction: """Internal class to hold transaction information in a AsyncClientSession.""" def __init__(self, opts: Optional[TransactionOptions], client: AsyncMongoClient): - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) - self.opts = opts self.state = _TxnState.NONE self.sharded = False @@ -510,13 +503,6 @@ def __init__( options: SessionOptions, implicit: bool, ) -> None: - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) - # An AsyncMongoClient, a _ServerSession, a SessionOptions, and a set. self._client: AsyncMongoClient = client self._server_session = server_session diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index b8a7b5737e..dfb41f3546 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -337,10 +337,6 @@ def __init__(self, client: AsyncMongoClient[_DocumentTypeArg], opts: AutoEncrypt :param client: The encrypted AsyncMongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) if opts._schema_map is None: schema_map = None @@ -357,11 +353,6 @@ def __init__(self, client: AsyncMongoClient[_DocumentTypeArg], opts: AutoEncrypt def _get_internal_client( encrypter: _Encrypter, mongo_client: AsyncMongoClient[_DocumentTypeArg] ) -> AsyncMongoClient[_DocumentTypeArg]: - if not isinstance(mongo_client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {mongo_client} is an instance of {type(mongo_client)}" - ) - if mongo_client.options.pool_options.max_pool_size is None: # Unlimited pool size, use the same client. return mongo_client @@ -698,7 +689,7 @@ async def create_encrypted_collection( """ if not isinstance(database, AsyncDatabase): raise TypeError( - f"create_encrypted_collection() requires an AsyncDatabase, {database} is an instance of {type(database)}" + f"create_encrypted_collection() requires an AsyncDatabase, but {database} is an instance of {type(database)}" ) encrypted_fields = deepcopy(encrypted_fields) diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index 07b01b7f7b..e85099190e 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -2500,11 +2500,6 @@ def __init__( retryable: bool = False, operation_id: Optional[int] = None, ): - if not isinstance(mongo_client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {mongo_client} is an instance of {type(mongo_client)}" - ) - self._last_error: Optional[Exception] = None self._retrying = False self._multiple_retries = _csot.get_timeout() is not None diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index 911a4651c2..a657042423 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -323,13 +323,6 @@ def set_conn_timeout(self, timeout: Optional[float]) -> None: def apply_timeout( self, client: AsyncMongoClient, cmd: Optional[MutableMapping[str, Any]] ) -> Optional[float]: - from pymongo.asynchronous.mongo_client import AsyncMongoClient - - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) - # CSOT: use remaining timeout when set. timeout = _csot.remaining() if timeout is None: diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index dd7e4658fc..e9b85e5637 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -157,13 +157,8 @@ async def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: An AsyncMongoClient instance. """ - from pymongo.asynchronous.mongo_client import AsyncMongoClient assert listeners is not None - if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) publish = listeners.enabled_for_commands start = datetime.now() diff --git a/pymongo/synchronous/bulk.py b/pymongo/synchronous/bulk.py index e127bb8b5a..481a624fe3 100644 --- a/pymongo/synchronous/bulk.py +++ b/pymongo/synchronous/bulk.py @@ -239,11 +239,7 @@ def write_command( docs: list[Mapping[str, Any]], client: MongoClient, ) -> dict[str, Any]: - from pymongo.synchronous.mongo_client import MongoClient - """A proxy for SocketInfo.write_command that handles event publishing.""" - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): @@ -329,10 +325,6 @@ def unack_write( client: MongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for Connection.unack_write that handles event publishing.""" - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -420,11 +412,6 @@ def _execute_batch_unack( ops: list[Mapping[str, Any]], client: MongoClient, ) -> list[Mapping[str, Any]]: - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") - if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) bwc.conn.command( # type: ignore[misc] @@ -452,11 +439,6 @@ def _execute_batch( ops: list[Mapping[str, Any]], client: MongoClient, ) -> tuple[dict[str, Any], list[Mapping[str, Any]]]: - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") - if self.is_encrypted: _, batched_cmd, to_send = bwc.batch_command(cmd, ops) result = bwc.conn.command( # type: ignore[misc] diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index cb3fc30c2a..9f4ec2420d 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -395,11 +395,6 @@ class _Transaction: """Internal class to hold transaction information in a ClientSession.""" def __init__(self, opts: Optional[TransactionOptions], client: MongoClient): - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") - self.opts = opts self.state = _TxnState.NONE self.sharded = False @@ -507,11 +502,6 @@ def __init__( options: SessionOptions, implicit: bool, ) -> None: - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") - # A MongoClient, a _ServerSession, a SessionOptions, and a set. self._client: MongoClient = client self._server_session = server_session diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 8d53474d7f..65405682f4 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -335,8 +335,6 @@ def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOp :param client: The encrypted MongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") if opts._schema_map is None: schema_map = None @@ -353,11 +351,6 @@ def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOp def _get_internal_client( encrypter: _Encrypter, mongo_client: MongoClient[_DocumentTypeArg] ) -> MongoClient[_DocumentTypeArg]: - if not isinstance(mongo_client, MongoClient): - raise TypeError( - f"MongoClient required but {mongo_client} is an instance of {type(mongo_client)}" - ) - if mongo_client.options.pool_options.max_pool_size is None: # Unlimited pool size, use the same client. return mongo_client @@ -694,7 +687,7 @@ def create_encrypted_collection( """ if not isinstance(database, Database): raise TypeError( - f"create_encrypted_collection() requires a Database, {database} is an instance of {type(database)}" + f"create_encrypted_collection() requires a Database, but {database} is an instance of {type(database)}" ) encrypted_fields = deepcopy(encrypted_fields) diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index 489c6da458..85d54b9c2f 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -2485,11 +2485,6 @@ def __init__( retryable: bool = False, operation_id: Optional[int] = None, ): - if not isinstance(mongo_client, MongoClient): - raise TypeError( - f"MongoClient required but {mongo_client} is an instance of {type(mongo_client)}" - ) - self._last_error: Optional[Exception] = None self._retrying = False self._multiple_retries = _csot.get_timeout() is not None diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 6d6fb803e6..94a1d10436 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -323,11 +323,6 @@ def set_conn_timeout(self, timeout: Optional[float]) -> None: def apply_timeout( self, client: MongoClient, cmd: Optional[MutableMapping[str, Any]] ) -> Optional[float]: - from pymongo.synchronous.mongo_client import MongoClient - - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") - # CSOT: use remaining timeout when set. timeout = _csot.remaining() if timeout is None: diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index 4f511ff92b..c982044769 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -157,11 +157,8 @@ def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: A MongoClient instance. """ - from pymongo.synchronous.mongo_client import MongoClient assert listeners is not None - if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") publish = listeners.enabled_for_commands start = datetime.now() From 41574175705b18f7d71f35f085fa458adcbe887d Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Fri, 30 Aug 2024 15:15:25 -0400 Subject: [PATCH 4/7] Remove unneeded import --- pymongo/asynchronous/client_session.py | 1 - pymongo/synchronous/client_session.py | 1 - 2 files changed, 2 deletions(-) diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 86db6771a3..d80495d804 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -176,7 +176,6 @@ if TYPE_CHECKING: from types import TracebackType - from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection from pymongo.asynchronous.server import Server from pymongo.typings import ClusterTime, _Address diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index 9f4ec2420d..f1d680fc0a 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -175,7 +175,6 @@ if TYPE_CHECKING: from types import TracebackType - from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection from pymongo.synchronous.server import Server from pymongo.typings import ClusterTime, _Address From fa489109eaead4f70cfc272bfb357d0ae36a6eb3 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Tue, 3 Sep 2024 09:31:32 -0400 Subject: [PATCH 5/7] Cleanup --- pymongo/asynchronous/bulk.py | 2 -- pymongo/asynchronous/database.py | 4 +--- pymongo/asynchronous/encryption.py | 4 +--- pymongo/asynchronous/mongo_client.py | 4 +--- pymongo/asynchronous/server.py | 1 - pymongo/synchronous/bulk.py | 2 -- pymongo/synchronous/database.py | 2 +- pymongo/synchronous/encryption.py | 4 +--- pymongo/synchronous/mongo_client.py | 2 +- pymongo/synchronous/server.py | 1 - 10 files changed, 6 insertions(+), 20 deletions(-) diff --git a/pymongo/asynchronous/bulk.py b/pymongo/asynchronous/bulk.py index 44230f4030..c200899dd1 100644 --- a/pymongo/asynchronous/bulk.py +++ b/pymongo/asynchronous/bulk.py @@ -240,7 +240,6 @@ async def write_command( client: AsyncMongoClient, ) -> dict[str, Any]: """A proxy for SocketInfo.write_command that handles event publishing.""" - cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -325,7 +324,6 @@ async def unack_write( client: AsyncMongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for AsyncConnection.unack_write that handles event publishing.""" - if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( _COMMAND_LOGGER, diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index d526fdcd4d..d5eec0134d 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -125,9 +125,7 @@ def __init__( raise TypeError("name must be an instance of str") if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) + raise TypeError(f"AsyncMongoClient required but given {type(client)}") if name != "$external": _check_name(name) diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index dfb41f3546..cb0d9ed7cd 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -598,9 +598,7 @@ def __init__( raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions") if not isinstance(key_vault_client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {key_vault_client} is an instance of {type(key_vault_client)}" - ) + raise TypeError(f"AsyncMongoClient required but given {type(key_vault_client)}") self._kms_providers = kms_providers self._key_vault_namespace = key_vault_namespace diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index e85099190e..2af773c440 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -2420,9 +2420,7 @@ def __init__( self, client: AsyncMongoClient, server: Server, session: Optional[AsyncClientSession] ): if not isinstance(client, AsyncMongoClient): - raise TypeError( - f"AsyncMongoClient required but {client} is an instance of {type(client)}" - ) + raise TypeError(f"AsyncMongoClient required but given {type(client)}") self.client = client self.server_address = server.description.address diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index e9b85e5637..b880bcc0af 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -157,7 +157,6 @@ async def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: An AsyncMongoClient instance. """ - assert listeners is not None publish = listeners.enabled_for_commands diff --git a/pymongo/synchronous/bulk.py b/pymongo/synchronous/bulk.py index 481a624fe3..4da64c4a78 100644 --- a/pymongo/synchronous/bulk.py +++ b/pymongo/synchronous/bulk.py @@ -240,7 +240,6 @@ def write_command( client: MongoClient, ) -> dict[str, Any]: """A proxy for SocketInfo.write_command that handles event publishing.""" - cmd[bwc.field] = docs if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( @@ -325,7 +324,6 @@ def unack_write( client: MongoClient, ) -> Optional[Mapping[str, Any]]: """A proxy for Connection.unack_write that handles event publishing.""" - if _COMMAND_LOGGER.isEnabledFor(logging.DEBUG): _debug_log( _COMMAND_LOGGER, diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 829c17a797..1cd8ee643b 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -125,7 +125,7 @@ def __init__( raise TypeError("name must be an instance of str") if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + raise TypeError(f"MongoClient required but given {type(client)}") if name != "$external": _check_name(name) diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 65405682f4..b1640fc003 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -596,9 +596,7 @@ def __init__( raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions") if not isinstance(key_vault_client, MongoClient): - raise TypeError( - f"MongoClient required but {key_vault_client} is an instance of {type(key_vault_client)}" - ) + raise TypeError(f"MongoClient required but given {type(key_vault_client)}") self._kms_providers = kms_providers self._key_vault_namespace = key_vault_namespace diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index 85d54b9c2f..6c5f68b7eb 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -2407,7 +2407,7 @@ class _MongoClientErrorHandler: def __init__(self, client: MongoClient, server: Server, session: Optional[ClientSession]): if not isinstance(client, MongoClient): - raise TypeError(f"MongoClient required but {client} is an instance of {type(client)}") + raise TypeError(f"MongoClient required but given {type(client)}") self.client = client self.server_address = server.description.address diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index c982044769..cdc0b57c56 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -157,7 +157,6 @@ def run_operation( :param unpack_res: A callable that decodes the wire protocol response. :param client: A MongoClient instance. """ - assert listeners is not None publish = listeners.enabled_for_commands From 108ba8e6c53a9824ab73e13671ea9b2feeb875f4 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Tue, 3 Sep 2024 09:34:33 -0400 Subject: [PATCH 6/7] More cleanup --- pymongo/asynchronous/encryption.py | 1 - pymongo/asynchronous/server.py | 1 - pymongo/synchronous/encryption.py | 1 - pymongo/synchronous/server.py | 1 - 4 files changed, 4 deletions(-) diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index cb0d9ed7cd..7b15248354 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -337,7 +337,6 @@ def __init__(self, client: AsyncMongoClient[_DocumentTypeArg], opts: AutoEncrypt :param client: The encrypted AsyncMongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ - if opts._schema_map is None: schema_map = None else: diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index b880bcc0af..72f22584e2 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -158,7 +158,6 @@ async def run_operation( :param client: An AsyncMongoClient instance. """ assert listeners is not None - publish = listeners.enabled_for_commands start = datetime.now() diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index b1640fc003..bbcf0e043e 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -335,7 +335,6 @@ def __init__(self, client: MongoClient[_DocumentTypeArg], opts: AutoEncryptionOp :param client: The encrypted MongoClient. :param opts: The encrypted client's :class:`AutoEncryptionOpts`. """ - if opts._schema_map is None: schema_map = None else: diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index cdc0b57c56..ed48cc6cc8 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -158,7 +158,6 @@ def run_operation( :param client: A MongoClient instance. """ assert listeners is not None - publish = listeners.enabled_for_commands start = datetime.now() From d5ae0d668d4ee3ea022b75e0a3ee7c2582d5dfc4 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Tue, 3 Sep 2024 16:16:13 -0400 Subject: [PATCH 7/7] Fixes --- pymongo/asynchronous/collection.py | 4 +--- pymongo/asynchronous/encryption.py | 2 +- pymongo/synchronous/collection.py | 4 +--- pymongo/synchronous/encryption.py | 2 +- 4 files changed, 4 insertions(+), 8 deletions(-) diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index d8e300cb47..6d8dfaf89a 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -231,9 +231,7 @@ def __init__( from pymongo.asynchronous.database import AsyncDatabase if not isinstance(database, AsyncDatabase): - raise TypeError( - f"AsyncCollection requires an AsyncDatabase, {database} is an instance of {type(database)}" - ) + raise TypeError(f"AsyncCollection requires an AsyncDatabase but {type(database)} given") if not name or ".." in name: raise InvalidName("collection names cannot be empty") diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index 7b15248354..c4cb886df7 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -686,7 +686,7 @@ async def create_encrypted_collection( """ if not isinstance(database, AsyncDatabase): raise TypeError( - f"create_encrypted_collection() requires an AsyncDatabase, but {database} is an instance of {type(database)}" + f"create_encrypted_collection() requires an AsyncDatabase but {type(database)} given" ) encrypted_fields = deepcopy(encrypted_fields) diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index 41924bf4be..93e24432e5 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -234,9 +234,7 @@ def __init__( from pymongo.synchronous.database import Database if not isinstance(database, Database): - raise TypeError( - f"Collection requires a Database, {database} is an instance of {type(database)}" - ) + raise TypeError(f"Collection requires a Database but {type(database)} given") if not name or ".." in name: raise InvalidName("collection names cannot be empty") diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index bbcf0e043e..2efa995978 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -684,7 +684,7 @@ def create_encrypted_collection( """ if not isinstance(database, Database): raise TypeError( - f"create_encrypted_collection() requires a Database, but {database} is an instance of {type(database)}" + f"create_encrypted_collection() requires a Database but {type(database)} given" ) encrypted_fields = deepcopy(encrypted_fields)