From eec32c542638f4785b66e2b0bea08eec18a7173d Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Fri, 6 Nov 2026 13:27:39 -0500 Subject: [PATCH] PYTHON-6230 Enable ruff rule UP041 to unify TimeoutErrors --- pymongo/_kms_connect_shared.py | 10 +++---- pymongo/asynchronous/_kms_connect.py | 4 +-- pymongo/asynchronous/encryption.py | 3 +-- pymongo/lock.py | 2 +- pymongo/network_layer.py | 27 ++++++++++--------- pymongo/pool_shared.py | 10 +++---- pymongo/pyopenssl_context.py | 4 +-- pymongo/synchronous/_kms_connect.py | 4 +-- pymongo/synchronous/encryption.py | 3 +-- pyproject.toml | 1 - test/asynchronous/test_async_network_layer.py | 2 +- test/asynchronous/test_load_balancer.py | 2 +- test/asynchronous/test_locks.py | 2 +- test/test_kms_connect.py | 11 ++++---- test/test_load_balancer.py | 2 +- 15 files changed, 42 insertions(+), 45 deletions(-) diff --git a/pymongo/_kms_connect_shared.py b/pymongo/_kms_connect_shared.py index 634619dcdf..396adddec6 100644 --- a/pymongo/_kms_connect_shared.py +++ b/pymongo/_kms_connect_shared.py @@ -94,7 +94,7 @@ def _remaining(deadline: float) -> float: """Seconds left before ``deadline``.""" left = deadline - time.monotonic() if left <= 0: - raise socket.timeout("timed out connecting through the proxy") + raise TimeoutError("timed out connecting through the proxy") return left @@ -423,12 +423,12 @@ def _connect_proxy(self, deadline: float) -> socket.socket: # Propagate the timeout from _remaining rather than report a # connect error. sock.settimeout(_remaining(deadline)) - except socket.timeout: + except TimeoutError: sock.close() raise try: sock.connect(sockaddr) - except socket.timeout: + except TimeoutError: # Preserve the timeout type rather than report a generic # connect error. sock.close() @@ -476,13 +476,13 @@ async def __call__(self, context: KMSConnectContext) -> socket.socket: # type: raise exc from None # The task succeeded right at the deadline. _close_late_bridge_sockets(late_sockets, future) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None if not future.done(): # The thread runs on regardless; close its late sockets. future.add_done_callback( functools.partial(_close_late_bridge_sockets, late_sockets) ) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None # Sphinx documents these classes under pymongo.encryption_options, the public diff --git a/pymongo/asynchronous/_kms_connect.py b/pymongo/asynchronous/_kms_connect.py index ab74919beb..b8d2ad0a67 100644 --- a/pymongo/asynchronous/_kms_connect.py +++ b/pymongo/asynchronous/_kms_connect.py @@ -102,11 +102,11 @@ async def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index e4f91294a4..81eff0dd44 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -18,7 +18,6 @@ import asyncio import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref @@ -212,7 +211,7 @@ async def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" diff --git a/pymongo/lock.py b/pymongo/lock.py index ad990fce3f..5385119d5e 100644 --- a/pymongo/lock.py +++ b/pymongo/lock.py @@ -84,7 +84,7 @@ def _release_locks() -> None: async def _async_cond_wait(condition: Condition, timeout: Optional[float]) -> bool: try: return await wait_for(condition.wait(), timeout) - except asyncio.TimeoutError: + except TimeoutError: return False diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index 5425a68503..76c0d5e7b1 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -87,9 +87,9 @@ async def async_socket_sendall(sock: Union[socket.socket, _sslConn], buf: bytes) await asyncio.wait_for(loop.sock_sendall(sock, buf), timeout=timeout) # type: ignore[arg-type] finally: sock.settimeout(timeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc if sys.platform != "win32": @@ -195,7 +195,7 @@ async def _async_blocking_socket_call( fut = asyncio.shield(inner) try: return await asyncio.wait_for(fut, timeout=timeout) - except (asyncio.CancelledError, asyncio.TimeoutError): + except (asyncio.CancelledError, TimeoutError): # Wait for the worker, shielded from further cancellations, so the # caller does not close the socket under it. while True: @@ -245,8 +245,9 @@ async def async_receive_data_socket( _async_socket_receive(sock, length, loop), # type: ignore[arg-type] timeout=timeout, ) - except asyncio.TimeoutError as err: - raise socket.timeout("timed out") from err + except TimeoutError as err: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from err finally: sock.settimeout(timeout) @@ -298,7 +299,7 @@ def wait_for_read(conn: Connection, deadline: Optional[float]) -> None: if readable: return if timed_out: - raise socket.timeout("timed out") + raise TimeoutError("timed out") def receive_data(conn: Connection, length: int, deadline: Optional[float]) -> memoryview: @@ -333,8 +334,8 @@ def receive_data(conn: Connection, length: int, deadline: Optional[float]) -> me if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None # We reached the true deadline. - raise socket.timeout("timed out") from None - except socket.timeout: + raise TimeoutError("timed out") from None + except TimeoutError: if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None if _WINDOWS or ( @@ -676,9 +677,9 @@ async def wait_closed(self) -> None: async def async_sendall(conn: PyMongoProtocol, buf: bytes) -> None: try: await asyncio.wait_for(conn.write(buf), timeout=conn.gettimeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc async def async_receive_message( @@ -714,7 +715,7 @@ async def async_receive_message( if pending: await asyncio.wait(pending) if len(done) == 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") if read_task in done: data, op_code = read_task.result() try: diff --git a/pymongo/pool_shared.py b/pymongo/pool_shared.py index 48a0a27bf1..d5d96dfbc8 100644 --- a/pymongo/pool_shared.py +++ b/pymongo/pool_shared.py @@ -528,7 +528,7 @@ def _raise_connection_failure( msg = msg_prefix + msg if "configured timeouts" not in msg: msg += format_timeout_details(timeout_details) - if isinstance(error, socket.timeout) or ( + if isinstance(error, TimeoutError) or ( isinstance(error, SSLErrors) and "timed out" in str(error) ): raise NetworkTimeout(msg) from error @@ -645,7 +645,7 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) # Socket needs to be non-blocking during connection to not block the event loop @@ -655,9 +655,9 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s ) sock.settimeout(timeout) return sock - except asyncio.TimeoutError as e: + except TimeoutError as e: sock.close() - err = socket.timeout("timed out") + err = TimeoutError("timed out") err.__cause__ = e except OSError as e: sock.close() @@ -891,7 +891,7 @@ def _create_connection(address: _Address, options: PoolOptions) -> socket.socket if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.settimeout(timeout) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) diff --git a/pymongo/pyopenssl_context.py b/pymongo/pyopenssl_context.py index 452912d686..db18c63b99 100644 --- a/pymongo/pyopenssl_context.py +++ b/pymongo/pyopenssl_context.py @@ -135,7 +135,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: # Check for closed socket. if self.fileno() == -1: if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None raise SSLError("Underlying socket has been closed") from None if isinstance(exc, _SSL.WantReadError): want_read = True @@ -148,7 +148,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: want_write = True self.socket_checker.select(self, want_read, want_write, timeout) if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None continue def do_handshake(self, *args: Any, **kwargs: Any) -> None: diff --git a/pymongo/synchronous/_kms_connect.py b/pymongo/synchronous/_kms_connect.py index 78d8119557..3a04d98d9e 100644 --- a/pymongo/synchronous/_kms_connect.py +++ b/pymongo/synchronous/_kms_connect.py @@ -102,11 +102,11 @@ def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 1626c16f58..8a79ce2e3f 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -17,7 +17,6 @@ from __future__ import annotations import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref @@ -211,7 +210,7 @@ def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" diff --git a/pyproject.toml b/pyproject.toml index b4f3e282c2..91adf5dea7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -243,7 +243,6 @@ ignore = [ "SIM117", # Use a single `with` statement with multiple contexts instead of nested `with` statements "UP045", # Use `X | Y` for union annotation (Enable when we drop 3.9 support) "PLC0415", # `import` should be at the top-level of a file - "UP041", # `asyncio.TimeoutError` is an alias of `TimeoutError` on 3.11+ "ASYNC109", # Async function with a `timeout` parameter (CSOT timeouts are not `asyncio.timeout`) "UP042", # `str, Enum` should be `StrEnum` (changes `__str__` semantics) "UP017", # `timezone.utc` preferred over `datetime.UTC` (keep existing style) diff --git a/test/asynchronous/test_async_network_layer.py b/test/asynchronous/test_async_network_layer.py index ad146e1e79..96abf34240 100644 --- a/test/asynchronous/test_async_network_layer.py +++ b/test/asynchronous/test_async_network_layer.py @@ -265,7 +265,7 @@ def slow(arg): time.sleep(0.4) finished.set() - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await _async_blocking_socket_call(asyncio.get_running_loop(), slow, None, 0.3) self.assertTrue(finished.is_set()) diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index 7866f1f7e6..ea25d43e9b 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -189,7 +189,7 @@ async def wait(self, event: Event, timeout: int): else: try: await asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True diff --git a/test/asynchronous/test_locks.py b/test/asynchronous/test_locks.py index 4d207b509b..19166f309f 100644 --- a/test/asynchronous/test_locks.py +++ b/test/asynchronous/test_locks.py @@ -296,7 +296,7 @@ async def test_context_manager(self): async def test_timeout_in_block(self): condition = _async_create_condition(_async_create_lock()) async with condition: - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await asyncio.wait_for(condition.wait(), timeout=0.5) async def test_cancelled_error_wakeup(self): diff --git a/test/test_kms_connect.py b/test/test_kms_connect.py index f5e79b5048..f0873fcd34 100644 --- a/test/test_kms_connect.py +++ b/test/test_kms_connect.py @@ -839,7 +839,7 @@ def blocker(): task = asyncio.create_task(callback(_kms_context(timeout=1.0))) await asyncio.sleep(0.2) # Let the coroutine queue its connect. assert not task.done(), "connect finished before the deadline" - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await task elapsed = time.monotonic() - start assert elapsed < 2.5, f"the wait outlived the deadline: {elapsed:.1f}s" @@ -928,7 +928,7 @@ async def raced_wait_for(awaitable, timeout=None): with mock.patch.object(HTTPProxyKMSConnect, "_tunnel", spy_tunnel): with mock.patch("asyncio.wait_for", raced_wait_for): callback = api.proxy(f"https://{host}:{port}", _insecure_client_context()) - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await callback(_kms_context()) assert len(tunneled) == 1 @@ -937,12 +937,11 @@ async def raced_wait_for(awaitable, timeout=None): @both_apis async def test_connect_timeout_is_not_reclassified(api): - # A timed-out connect keeps its socket.timeout type. def timeout_connect(self, address): - raise socket.timeout("timed out") + raise TimeoutError("timed out") with mock.patch.object(socket.socket, "connect", timeout_connect): - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): HTTPProxyKMSConnect("http://127.0.0.1:9999")._connect_proxy(time.monotonic() + 10) @@ -991,7 +990,7 @@ async def test_remaining_raises_once_the_deadline_passes(api): from pymongo._kms_connect_shared import _remaining assert _remaining(time.monotonic() + 5) > 0 - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): _remaining(time.monotonic() - 1) diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index 66a410a5f1..8bd4056772 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -189,7 +189,7 @@ def wait(self, event: Event, timeout: int): else: try: asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True