Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions bson/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}"
Expand Down
8 changes: 4 additions & 4 deletions bson/datetime_ms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 0 additions & 1 deletion pymongo/_asyncio_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 3 additions & 4 deletions pymongo/asynchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand Down
36 changes: 17 additions & 19 deletions pymongo/asynchronous/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
3 changes: 1 addition & 2 deletions pymongo/client_session_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
34 changes: 19 additions & 15 deletions pymongo/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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

Expand All @@ -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

Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 3 additions & 4 deletions pymongo/network_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pymongo/pool_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion pymongo/pyopenssl_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 3 additions & 4 deletions pymongo/synchronous/mongo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand Down
36 changes: 17 additions & 19 deletions pymongo/synchronous/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
26 changes: 21 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions test/asynchronous/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 3 additions & 4 deletions test/asynchronous/test_auth_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 7 additions & 10 deletions test/asynchronous/test_discovery_and_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading