From c55d3ace5e0030465a517244db75f199b61fa9b4 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Tue, 17 Nov 2026 10:30:43 -0500 Subject: [PATCH] PYTHON-6280 Enable non-design PLR ruff rules --- bson/binary.py | 5 ++- bson/datetime_ms.py | 8 ++--- pymongo/_asyncio_lock.py | 1 - pymongo/asynchronous/mongo_client.py | 7 ++-- pymongo/asynchronous/pool.py | 36 +++++++++---------- pymongo/client_session_shared.py | 3 +- pymongo/common.py | 34 ++++++++++-------- pymongo/network_layer.py | 7 ++-- pymongo/pool_shared.py | 4 +-- pymongo/pyopenssl_context.py | 2 +- pymongo/synchronous/mongo_client.py | 7 ++-- pymongo/synchronous/pool.py | 36 +++++++++---------- pyproject.toml | 26 +++++++++++--- test/__init__.py | 5 ++- test/asynchronous/__init__.py | 5 ++- test/asynchronous/test_auth_spec.py | 7 ++-- .../test_discovery_and_monitoring.py | 17 ++++----- test/asynchronous/test_dns.py | 2 +- test/asynchronous/test_read_preferences.py | 4 +-- .../test_read_write_concern_spec.py | 2 +- test/asynchronous/test_ssl.py | 2 +- test/asynchronous/unified_format.py | 4 +-- test/test_auth_spec.py | 7 ++-- test/test_discovery_and_monitoring.py | 17 ++++----- test/test_dns.py | 2 +- test/test_kms_connect.py | 1 - test/test_read_preferences.py | 4 +-- test/test_read_write_concern_spec.py | 2 +- test/test_ssl.py | 2 +- test/test_ssl_support.py | 2 +- test/unified_format.py | 4 +-- test/unified_format_shared.py | 15 ++++---- test/utils_shared.py | 4 +-- 33 files changed, 140 insertions(+), 144 deletions(-) diff --git a/bson/binary.py b/bson/binary.py index 4409fa4b7a..54fc152d47 100644 --- a/bson/binary.py +++ b/bson/binary.py @@ -417,10 +417,9 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI elif uuid_representation == UuidRepresentation.CSHARP_LEGACY: if self.subtype == OLD_UUID_SUBTYPE: return UUID(bytes_le=self) - else: + elif self.subtype == UUID_SUBTYPE: # uuid_representation == UuidRepresentation.STANDARD - if self.subtype == UUID_SUBTYPE: - return UUID(bytes=self) + return UUID(bytes=self) raise ValueError( f"cannot decode subtype {self.subtype} to {UUID_REPRESENTATION_NAMES[uuid_representation]}" diff --git a/bson/datetime_ms.py b/bson/datetime_ms.py index d659323717..7fe5312445 100644 --- a/bson/datetime_ms.py +++ b/bson/datetime_ms.py @@ -148,10 +148,10 @@ def _max_datetime_ms(tz: datetime.tzinfo = utc) -> int: def _millis_to_datetime(millis: int, opts: CodecOptions[Any]) -> datetime.datetime | DatetimeMS: """Convert milliseconds since epoch UTC to datetime.""" - if ( - opts.datetime_conversion == DatetimeConversion.DATETIME - or opts.datetime_conversion == DatetimeConversion.DATETIME_CLAMP - or opts.datetime_conversion == DatetimeConversion.DATETIME_AUTO + if opts.datetime_conversion in ( + DatetimeConversion.DATETIME, + DatetimeConversion.DATETIME_CLAMP, + DatetimeConversion.DATETIME_AUTO, ): tz = opts.tzinfo or utc if opts.datetime_conversion == DatetimeConversion.DATETIME_CLAMP: diff --git a/pymongo/_asyncio_lock.py b/pymongo/_asyncio_lock.py index 18d97e6beb..4d26db8b1d 100644 --- a/pymongo/_asyncio_lock.py +++ b/pymongo/_asyncio_lock.py @@ -39,7 +39,6 @@ async def __aenter__(self) -> None: await self.acquire() # type: ignore[attr-defined] # We have no use for the "as ..." clause in the with # statement for locks. - return async def __aexit__( self, diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index 520beafa72..366582cf11 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -1430,7 +1430,7 @@ def option_repr(option: str, value: Any) -> str: options.extend( option_repr(key, self._options._options[key]) for key in self._options._options - if key not in set(self._constructor_args) and key != "username" and key != "password" + if key not in set(self._constructor_args) and key not in {"username", "password"} ) return ", ".join(options) @@ -2631,10 +2631,9 @@ async def bulk_write( if write_concern: raise InvalidOperation("Cannot set write concern after starting a transaction") write_concern = session._transaction.opts.write_concern # type: ignore[union-attr] - else: + elif not write_concern: # Inherit the client's write concern if none is provided. - if not write_concern: - write_concern = self.write_concern + write_concern = self.write_concern if write_concern and not write_concern.acknowledged and verbose_results: raise InvalidOperation( diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index e154d912a9..2cccd57c56 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -520,15 +520,14 @@ async def _reset( for conn in sockets: await conn.close_conn(ConnectionClosedReason.POOL_CLOSED) self._telemetry.pool_closed() + elif not _IS_SYNC: + await asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] + return_exceptions=True, + ) else: - if not _IS_SYNC: - await asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, - ) - else: - for conn in sockets: - await conn.close_conn(ConnectionClosedReason.STALE) + for conn in sockets: + await conn.close_conn(ConnectionClosedReason.STALE) async def update_is_writable(self, is_writable: bool | None) -> None: """Updates the is_writable attribute on all sockets currently in the @@ -1014,14 +1013,13 @@ async def __aexit__( pinned = conn.pinned_txn or conn.pinned_cursor if not pinned and conn.active: await pool.checkin(conn) - else: - if conn.pinned_txn: - async with pool.lock: - pool._pinned_sockets.add(conn) - pool.ntxns += 1 - elif conn.pinned_cursor: - async with pool.lock: - pool._pinned_sockets.add(conn) - pool.ncursors += 1 - elif conn.active: - await pool.checkin(conn) + elif conn.pinned_txn: + async with pool.lock: + pool._pinned_sockets.add(conn) + pool.ntxns += 1 + elif conn.pinned_cursor: + async with pool.lock: + pool._pinned_sockets.add(conn) + pool.ncursors += 1 + elif conn.active: + await pool.checkin(conn) diff --git a/pymongo/client_session_shared.py b/pymongo/client_session_shared.py index 6e4ac0378f..1c285d1e1b 100644 --- a/pymongo/client_session_shared.py +++ b/pymongo/client_session_shared.py @@ -565,8 +565,7 @@ def _advance_operation_time(self, operation_time: Timestamp | None) -> None: if self._operation_time is None: self._operation_time = operation_time elif operation_time is not None: - if operation_time > self._operation_time: - self._operation_time = operation_time + self._operation_time = max(self._operation_time, operation_time) def advance_operation_time(self, operation_time: Timestamp) -> None: """Update the operation time for this session. diff --git a/pymongo/common.py b/pymongo/common.py index 81e3fa6d9b..d160e28235 100644 --- a/pymongo/common.py +++ b/pymongo/common.py @@ -296,7 +296,7 @@ def validate_positive_float_or_zero(option: str, value: Any) -> float: """Validates that 'value' is 0 or a positive float, or can be converted to 0 or a positive float. """ - if value == 0 or value == "0": + if value in (0, "0"): return 0 return validate_positive_float(option, value) @@ -318,7 +318,7 @@ def validate_timeout_or_zero(option: str, value: Any) -> float: """ if value is None: raise ConfigurationError(f"{option} cannot be None") - if value == 0 or value == "0": + if value in (0, "0"): return 0 return validate_positive_float(option, value) / 1000.0 @@ -328,7 +328,7 @@ def validate_timeout_or_none_or_zero(option: Any, value: Any) -> float | None: a value in floating point seconds. value=0 and value="0" are treated the same as value=None which means unlimited timeout. """ - if value is None or value == 0 or value == "0": + if value in (None, 0, "0"): return None return validate_positive_float(option, value) / 1000.0 @@ -344,7 +344,7 @@ def validate_timeoutms(option: Any, value: Any) -> float | None: def validate_max_staleness(option: str, value: Any) -> int: """Validates maxStalenessSeconds according to the Max Staleness Spec.""" - if value == -1 or value == "-1": + if value in (-1, "-1"): # Default: No maximum staleness. return -1 return validate_positive_integer(option, value) @@ -457,21 +457,25 @@ def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, boo raise TypeError( f"Auth mechanism properties must be given as a string or a dictionary, not {type(value)}" ) - for key, value in value.items(): # noqa: B020 - if isinstance(value, str): - props[key] = value - elif isinstance(value, bool): - props[key] = str(value).lower() - elif key in ["ALLOWED_HOSTS"] and isinstance(value, list): - props[key] = value + for key, prop_value in value.items(): + if isinstance(prop_value, str): + props[key] = prop_value + elif isinstance(prop_value, bool): + props[key] = str(prop_value).lower() + elif key in ["ALLOWED_HOSTS"] and isinstance(prop_value, list): + props[key] = prop_value elif key in ["OIDC_CALLBACK", "OIDC_HUMAN_CALLBACK"]: from pymongo.auth_oidc_shared import OIDCCallback - if not isinstance(value, OIDCCallback): - raise TypeError(f"callback must be an OIDCCallback object, not {type(value)}") - props[key] = value + if not isinstance(prop_value, OIDCCallback): + raise TypeError( + f"callback must be an OIDCCallback object, not {type(prop_value)}" + ) + props[key] = prop_value else: - raise TypeError(f"Invalid type for auth mechanism property {key}, {type(value)}") + raise TypeError( + f"Invalid type for auth mechanism property {key}, {type(prop_value)}" + ) return props value = validate_string(option, value) diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index f60e27738c..931ec26112 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -689,11 +689,10 @@ async def async_receive_message( timeout = conn.conn.gettimeout if _csot.get_timeout(): deadline = _csot.get_deadline() + elif timeout: + deadline = time.monotonic() + timeout else: - if timeout: - deadline = time.monotonic() + timeout - else: - deadline = None + deadline = None if deadline: # When the timeout has expired perform one final check to # see if the socket is readable. This helps avoid spurious diff --git a/pymongo/pool_shared.py b/pymongo/pool_shared.py index 83a10ef5ae..a7a221f269 100644 --- a/pymongo/pool_shared.py +++ b/pymongo/pool_shared.py @@ -576,8 +576,8 @@ def inc(self, service_id: ObjectId | None) -> None: """Increment the generation for the given service_id.""" self._generation += 1 if service_id is None: - for service_id in self._generations: - self._generations[service_id] += 1 + for sid in self._generations: + self._generations[sid] += 1 else: self._generations[service_id] += 1 diff --git a/pymongo/pyopenssl_context.py b/pymongo/pyopenssl_context.py index 10e8af1d0b..7fc8086e93 100644 --- a/pymongo/pyopenssl_context.py +++ b/pymongo/pyopenssl_context.py @@ -27,8 +27,8 @@ from ipaddress import ip_address as _ip_address from typing import TYPE_CHECKING, Any, TypeVar -import cryptography.x509 as x509 import service_identity +from cryptography import x509 from OpenSSL import SSL as _SSL from OpenSSL import crypto as _crypto diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index a4c29cb671..7e13d7c6fb 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -1430,7 +1430,7 @@ def option_repr(option: str, value: Any) -> str: options.extend( option_repr(key, self._options._options[key]) for key in self._options._options - if key not in set(self._constructor_args) and key != "username" and key != "password" + if key not in set(self._constructor_args) and key not in {"username", "password"} ) return ", ".join(options) @@ -2619,10 +2619,9 @@ def bulk_write( if write_concern: raise InvalidOperation("Cannot set write concern after starting a transaction") write_concern = session._transaction.opts.write_concern # type: ignore[union-attr] - else: + elif not write_concern: # Inherit the client's write concern if none is provided. - if not write_concern: - write_concern = self.write_concern + write_concern = self.write_concern if write_concern and not write_concern.acknowledged and verbose_results: raise InvalidOperation( diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index 45f8af4ec6..c919f9409e 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -520,15 +520,14 @@ def _reset( for conn in sockets: conn.close_conn(ConnectionClosedReason.POOL_CLOSED) self._telemetry.pool_closed() + elif not _IS_SYNC: + asyncio.gather( + *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] + return_exceptions=True, + ) else: - if not _IS_SYNC: - asyncio.gather( - *[conn.close_conn(ConnectionClosedReason.STALE) for conn in sockets], # type: ignore[func-returns-value] - return_exceptions=True, - ) - else: - for conn in sockets: - conn.close_conn(ConnectionClosedReason.STALE) + for conn in sockets: + conn.close_conn(ConnectionClosedReason.STALE) def update_is_writable(self, is_writable: bool | None) -> None: """Updates the is_writable attribute on all sockets currently in the @@ -1012,14 +1011,13 @@ def __exit__( pinned = conn.pinned_txn or conn.pinned_cursor if not pinned and conn.active: pool.checkin(conn) - else: - if conn.pinned_txn: - with pool.lock: - pool._pinned_sockets.add(conn) - pool.ntxns += 1 - elif conn.pinned_cursor: - with pool.lock: - pool._pinned_sockets.add(conn) - pool.ncursors += 1 - elif conn.active: - pool.checkin(conn) + elif conn.pinned_txn: + with pool.lock: + pool._pinned_sockets.add(conn) + pool.ntxns += 1 + elif conn.pinned_cursor: + with pool.lock: + pool._pinned_sockets.add(conn) + pool.ncursors += 1 + elif conn.active: + pool.checkin(conn) diff --git a/pyproject.toml b/pyproject.toml index baac84b775..a7c4cdce84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -210,13 +210,29 @@ extend-select = [ "ASYNC", # flake8-async "TC", # flake8-type-checking "PERF", # perflint - "D202", # pydocstyle: no blank lines between docstring and function body. - "D209", # pydocstyle: closing quotes go on their own line. - "D301", # pydocstyle: docstrings containing \ are defined as string literals. - "D403", # pydocstyle: docstrings start with a capital letter. + # Non-design pylint rules. + "PLR0124", # pylint: comparison of a name with itself + "PLR0133", # pylint: comparison between two constants + "PLR0206", # pylint: property with parameters + "PLR0402", # pylint: `import a.b as b` should be `from a import b` + "PLR1704", # pylint: local variable redefines an argument + "PLR1708", # pylint: `raise StopIteration` in a generator should be `return` + "PLR1711", # pylint: useless `return` at the end of a function + "PLR1714", # pylint: repeated equality comparison should use `in` + "PLR1716", # pylint: chained comparison can be simplified + "PLR1722", # pylint: use `sys.exit()` instead of `exit()` or `quit()` + "PLR1730", # pylint: `if` statement can be replaced by `min()` or `max()` + "PLR1733", # pylint: unnecessary dict index lookup while iterating `.items()` + "PLR1736", # pylint: unnecessary list index lookup while iterating `enumerate()` + "PLR2044", # pylint: empty comment + "PLR5501", # pylint: `else: if` should be `elif` + "D202", # pydocstyle: no blank lines between docstring and function body + "D209", # pydocstyle: closing quotes go on their own line + "D301", # pydocstyle: docstrings containing \ are defined as string literals + "D403", # pydocstyle: docstrings start with a capital letter ] ignore = [ - "PLR", # Design related pylint codes + "PLR", # Design related pylint rules "E501", # Line too long "EM101", # Exception must not use a string literal, assign to variable first "EM102", # Exception must not use an f-string literal, assign to variable first diff --git a/test/__init__.py b/test/__init__.py index 5a2a5d7ea3..2bdfb8332f 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -430,9 +430,8 @@ def _server_started_with_ipv6(self): if "parsed" in self.cmd_line: if not self.cmd_line["parsed"].get("net", {}).get("ipv6"): return False - else: - if "--ipv6" not in self.cmd_line["argv"]: - return False + elif "--ipv6" not in self.cmd_line["argv"]: + return False # The server was started with --ipv6. Is there an IPv6 route to it? try: diff --git a/test/asynchronous/__init__.py b/test/asynchronous/__init__.py index 62d684cd76..4a899a016e 100644 --- a/test/asynchronous/__init__.py +++ b/test/asynchronous/__init__.py @@ -430,9 +430,8 @@ async def _server_started_with_ipv6(self): if "parsed" in self.cmd_line: if not self.cmd_line["parsed"].get("net", {}).get("ipv6"): return False - else: - if "--ipv6" not in self.cmd_line["argv"]: - return False + elif "--ipv6" not in self.cmd_line["argv"]: + return False # The server was started with --ipv6. Is there an IPv6 route to it? try: diff --git a/test/asynchronous/test_auth_spec.py b/test/asynchronous/test_auth_spec.py index 4a011b4aab..f2299f907d 100644 --- a/test/asynchronous/test_auth_spec.py +++ b/test/asynchronous/test_auth_spec.py @@ -80,11 +80,10 @@ def run_test(self): actual = credentials.mechanism_properties for key, value in expected.items(): self.assertEqual(getattr(actual, key.lower()), value) + elif credential["mechanism"] == "MONGODB-AWS": + self.assertIsNone(credentials.mechanism_properties.aws_session_token) else: - if credential["mechanism"] == "MONGODB-AWS": - self.assertIsNone(credentials.mechanism_properties.aws_session_token) - else: - self.assertIsNone(credentials.mechanism_properties) + self.assertIsNone(credentials.mechanism_properties) return run_test diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index e686dd1926..9467db391f 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -565,16 +565,13 @@ def predicate(): if _IS_SYNC: if monitor._rtt_monitor._executor._thread is None: return False - else: - if monitor._rtt_monitor._executor._task is None: - return False - else: - if _IS_SYNC: - if monitor._rtt_monitor._executor._thread is not None: - return False - else: - if monitor._rtt_monitor._executor._task is not None: - return False + elif monitor._rtt_monitor._executor._task is None: + return False + elif _IS_SYNC: + if monitor._rtt_monitor._executor._thread is not None: + return False + elif monitor._rtt_monitor._executor._task is not None: + return False return True await async_wait_until(predicate, "find all RTT monitors") diff --git a/test/asynchronous/test_dns.py b/test/asynchronous/test_dns.py index fb66d45f35..6077dbac93 100644 --- a/test/asynchronous/test_dns.py +++ b/test/asynchronous/test_dns.py @@ -134,7 +134,7 @@ async def run_test(self): self.assertEqual(result["username"], expected) elif opt == "password": self.assertEqual(result["password"], expected) - elif opt == "auth_database" or opt == "db": + elif opt in {"auth_database", "db"}: self.assertEqual(result["database"], expected) hostname = next(iter(async_client_context.client.nodes))[0] diff --git a/test/asynchronous/test_read_preferences.py b/test/asynchronous/test_read_preferences.py index 5ff9de30f7..8ac49032ef 100644 --- a/test/asynchronous/test_read_preferences.py +++ b/test/asynchronous/test_read_preferences.py @@ -336,9 +336,9 @@ async def _conn_for_reads(self, read_preference, session, operation): @contextlib.asynccontextmanager async def _conn_from_server(self, read_preference, server, session): # type: ignore[override] context = super()._conn_from_server(read_preference, server, session) - async with context as (conn, read_preference): + async with context as (conn, read_pref): await self.record_a_read(conn.address) - yield conn, read_preference + yield conn, read_pref async def record_a_read(self, address): server = await (await self._get_topology()).select_server_by_address(address, _Op.TEST, 0) diff --git a/test/asynchronous/test_read_write_concern_spec.py b/test/asynchronous/test_read_write_concern_spec.py index 776c843552..345a71c488 100644 --- a/test/asynchronous/test_read_write_concern_spec.py +++ b/test/asynchronous/test_read_write_concern_spec.py @@ -301,7 +301,7 @@ def create_tests(): for dirpath, _, filenames in os.walk(_TEST_PATH): dirname = os.path.split(dirpath)[-1] - if dirname == "operation" or dirname == "write-concern-errors": + if dirname in {"operation", "write-concern-errors"}: # These directories have their tests generated below by generate_test_classes(). continue elif dirname == "connection-string": diff --git a/test/asynchronous/test_ssl.py b/test/asynchronous/test_ssl.py index a27308a64a..07b6805a3c 100644 --- a/test/asynchronous/test_ssl.py +++ b/test/asynchronous/test_ssl.py @@ -21,7 +21,7 @@ import pathlib import socket import sys -import unittest.mock as mock +from unittest import mock sys.path[0:0] = [""] diff --git a/test/asynchronous/unified_format.py b/test/asynchronous/unified_format.py index edcc43ad3c..6f320f6105 100644 --- a/test/asynchronous/unified_format.py +++ b/test/asynchronous/unified_format.py @@ -666,7 +666,7 @@ def maybe_skip_test(self, spec): if name == "listIndexNames": self.skipTest("PyMongo does not support list_index_names()") if not async_client_context.test_commands_enabled: - if name == "failPoint" or name == "targetedFailPoint": + if name in {"failPoint", "targetedFailPoint"}: self.skipTest("Test commands must be enabled to use fail points") if name == "modifyCollection": self.skipTest("PyMongo does not support modifyCollection") @@ -1552,7 +1552,7 @@ async def _run_scenario(self, spec, uri=None): # operations during test set up and tear down. for op in spec["operations"]: name = op["name"] - if name == "startTransaction" or name == "withTransaction": + if name in {"startTransaction", "withTransaction"}: self.addAsyncCleanup(self.kill_all_sessions) break diff --git a/test/test_auth_spec.py b/test/test_auth_spec.py index a165beac92..75d542e90a 100644 --- a/test/test_auth_spec.py +++ b/test/test_auth_spec.py @@ -78,11 +78,10 @@ def run_test(self): actual = credentials.mechanism_properties for key, value in expected.items(): self.assertEqual(getattr(actual, key.lower()), value) + elif credential["mechanism"] == "MONGODB-AWS": + self.assertIsNone(credentials.mechanism_properties.aws_session_token) else: - if credential["mechanism"] == "MONGODB-AWS": - self.assertIsNone(credentials.mechanism_properties.aws_session_token) - else: - self.assertIsNone(credentials.mechanism_properties) + self.assertIsNone(credentials.mechanism_properties) return run_test diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index 7407f61664..ab4119103f 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -562,16 +562,13 @@ def predicate(): if _IS_SYNC: if monitor._rtt_monitor._executor._thread is None: return False - else: - if monitor._rtt_monitor._executor._task is None: - return False - else: - if _IS_SYNC: - if monitor._rtt_monitor._executor._thread is not None: - return False - else: - if monitor._rtt_monitor._executor._task is not None: - return False + elif monitor._rtt_monitor._executor._task is None: + return False + elif _IS_SYNC: + if monitor._rtt_monitor._executor._thread is not None: + return False + elif monitor._rtt_monitor._executor._task is not None: + return False return True wait_until(predicate, "find all RTT monitors") diff --git a/test/test_dns.py b/test/test_dns.py index 2b37dc2fcf..0889d44ab7 100644 --- a/test/test_dns.py +++ b/test/test_dns.py @@ -134,7 +134,7 @@ def run_test(self): self.assertEqual(result["username"], expected) elif opt == "password": self.assertEqual(result["password"], expected) - elif opt == "auth_database" or opt == "db": + elif opt in {"auth_database", "db"}: self.assertEqual(result["database"], expected) hostname = next(iter(client_context.client.nodes))[0] diff --git a/test/test_kms_connect.py b/test/test_kms_connect.py index 084cfae266..91a48e944a 100644 --- a/test/test_kms_connect.py +++ b/test/test_kms_connect.py @@ -1032,7 +1032,6 @@ async def test_non_coroutine_callback_is_rejected(api): def callback(context): entered.append(context) - return None with pytest.raises(ConfigurationError, match="coroutine function"): await api.connect(_KMS_ADDRESS, _pool_options(), callback, 10.0) diff --git a/test/test_read_preferences.py b/test/test_read_preferences.py index fdd1bd9f8b..a9741e3301 100644 --- a/test/test_read_preferences.py +++ b/test/test_read_preferences.py @@ -316,9 +316,9 @@ def _conn_for_reads(self, read_preference, session, operation): @contextlib.contextmanager def _conn_from_server(self, read_preference, server, session): # type: ignore[override] context = super()._conn_from_server(read_preference, server, session) - with context as (conn, read_preference): + with context as (conn, read_pref): self.record_a_read(conn.address) - yield conn, read_preference + yield conn, read_pref def record_a_read(self, address): server = (self._get_topology()).select_server_by_address(address, _Op.TEST, 0) diff --git a/test/test_read_write_concern_spec.py b/test/test_read_write_concern_spec.py index 30b1325e13..2caf0e02b1 100644 --- a/test/test_read_write_concern_spec.py +++ b/test/test_read_write_concern_spec.py @@ -297,7 +297,7 @@ def create_tests(): for dirpath, _, filenames in os.walk(_TEST_PATH): dirname = os.path.split(dirpath)[-1] - if dirname == "operation" or dirname == "write-concern-errors": + if dirname in {"operation", "write-concern-errors"}: # These directories have their tests generated below by generate_test_classes(). continue elif dirname == "connection-string": diff --git a/test/test_ssl.py b/test/test_ssl.py index 66f285abf3..08011d29fa 100644 --- a/test/test_ssl.py +++ b/test/test_ssl.py @@ -21,7 +21,7 @@ import pathlib import socket import sys -import unittest.mock as mock +from unittest import mock sys.path[0:0] = [""] diff --git a/test/test_ssl_support.py b/test/test_ssl_support.py index e4bfef2e05..72bd9597e0 100644 --- a/test/test_ssl_support.py +++ b/test/test_ssl_support.py @@ -22,7 +22,7 @@ import os import sys -import unittest.mock as mock +from unittest import mock sys.path[0:0] = [""] diff --git a/test/unified_format.py b/test/unified_format.py index 809b92b258..313b7eda20 100644 --- a/test/unified_format.py +++ b/test/unified_format.py @@ -665,7 +665,7 @@ def maybe_skip_test(self, spec): if name == "listIndexNames": self.skipTest("PyMongo does not support list_index_names()") if not client_context.test_commands_enabled: - if name == "failPoint" or name == "targetedFailPoint": + if name in {"failPoint", "targetedFailPoint"}: self.skipTest("Test commands must be enabled to use fail points") if name == "modifyCollection": self.skipTest("PyMongo does not support modifyCollection") @@ -1539,7 +1539,7 @@ def _run_scenario(self, spec, uri=None): # operations during test set up and tear down. for op in spec["operations"]: name = op["name"] - if name == "startTransaction" or name == "withTransaction": + if name in {"startTransaction", "withTransaction"}: self.addCleanup(self.kill_all_sessions) break diff --git a/test/unified_format_shared.py b/test/unified_format_shared.py index 7e5595baac..803dfea05d 100644 --- a/test/unified_format_shared.py +++ b/test/unified_format_shared.py @@ -556,12 +556,11 @@ def match_result(self, expectation, actual, in_recursive_call=False, test=True): self.test.assertEqual(expectation, actual) else: return expectation == actual + elif test: + self.test.assertIsInstance(actual, type(expectation)) + self.test.assertEqual(expectation, actual) else: - if test: - self.test.assertIsInstance(actual, type(expectation)) - self.test.assertEqual(expectation, actual) - else: - return isinstance(actual, type(expectation)) and expectation == actual + return isinstance(actual, type(expectation)) and expectation == actual return True def match_server_description(self, actual: ServerDescription, spec: dict) -> None: @@ -606,13 +605,11 @@ def match_event_fields(self, actual: Any, spec: dict) -> None: continue if field in ("previousDescription", "newDescription"): if isinstance(actual, ServerDescriptionChangedEvent): - self.match_server_description( - getattr(actual, camel_to_snake(field)), spec[field] - ) + self.match_server_description(getattr(actual, camel_to_snake(field)), expected) continue if isinstance(actual, TopologyDescriptionChangedEvent): self.match_topology_description( - getattr(actual, camel_to_snake(field)), spec[field] + getattr(actual, camel_to_snake(field)), expected ) continue diff --git a/test/utils_shared.py b/test/utils_shared.py index 13ea464949..9ad97aa1cf 100644 --- a/test/utils_shared.py +++ b/test/utils_shared.py @@ -703,7 +703,7 @@ def prepare_spec_arguments(spec, arguments, opname, entity_map, with_txn_callbac if arg_name == "fieldName": arguments["key"] = arguments.pop(arg_name) # Aggregate uses "batchSize", while find uses batch_size. - elif (arg_name == "batchSize" or arg_name == "allowDiskUse") and opname == "aggregate": + elif arg_name in {"batchSize", "allowDiskUse"} and opname == "aggregate": continue elif arg_name == "bypassDocumentValidation" and ( opname == "aggregate" or "find_one_and" in opname @@ -714,7 +714,7 @@ def prepare_spec_arguments(spec, arguments, opname, entity_map, with_txn_callbac # Requires boolean returnDocument. elif arg_name == "returnDocument": arguments[c2s] = getattr(ReturnDocument, arguments.pop(arg_name).upper()) - elif "bulk_write" in opname and (c2s == "requests" or c2s == "models"): + elif "bulk_write" in opname and c2s in {"requests", "models"}: # Parse each request into a bulk write model. requests = [] for request in arguments[c2s]: