From bc5c7a44bfb583318835c3a83f09f131a4b946fd Mon Sep 17 00:00:00 2001 From: Gabor Boros Date: Mon, 16 Nov 2026 18:03:56 +0100 Subject: [PATCH] feat: implement async context managers Signed-off-by: Gabor Boros --- rethinkdb/net.py | 121 +++++++++++++++++++++---- rethinkdb/net_asyncio.py | 31 ++++--- rethinkdb/net_gevent.py | 25 ++++-- rethinkdb/net_tornado.py | 25 +++++- rethinkdb/net_trio.py | 23 ++++- rethinkdb/net_twisted.py | 46 ++++++++-- tests/integration/test_net_asyncio.py | 47 ++++++++++ tests/integration/test_net_gevent.py | 46 ++++++++++ tests/integration/test_net_tornado.py | 49 +++++++++++ tests/integration/test_net_trio.py | 47 ++++++++++ tests/integration/test_net_twisted.py | 55 ++++++++++++ tests/integration/test_queries.py | 43 +++++++++ tests/test_net.py | 122 ++++++++++++++++++++++++++ 13 files changed, 635 insertions(+), 45 deletions(-) diff --git a/rethinkdb/net.py b/rethinkdb/net.py index 07df7e1..c30d065 100644 --- a/rethinkdb/net.py +++ b/rethinkdb/net.py @@ -27,7 +27,8 @@ import ssl import struct import time -from typing import Any, Union +from types import TracebackType +from typing import Any, Protocol, Self, Union, cast from urllib.parse import parse_qs, urlparse from rethinkdb.ast import DB, RqlQuery, expr @@ -56,9 +57,13 @@ __all__ = [ "DEFAULT_PORT", + "AsyncConnectionContextManager", + "AsyncContextManager", "Connection", "Cursor", "DefaultConnection", + "SyncConnectionContextManager", + "SyncContextManager", "make_connection", ] @@ -190,10 +195,101 @@ def make_error(self, query: Query) -> ReqlError: return error +class _Closes(Protocol): + """Object that can be closed by a context manager.""" + + def close(self, *args: Any, **kwargs: Any) -> Any: + """Close the object.""" + + +class SyncContextManager: + """Synchronous context manager that closes the object on exit. + + Use ``with`` for drivers whose ``close`` method is synchronous. + """ + + def __enter__(self) -> Self: + """Enter the context and return this object.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + """Close the object. Exceptions raised in the block propagate.""" + cast(_Closes, self).close() + + +class SyncConnectionContextManager: + """Synchronous context manager that closes a connection on exit. + + Use ``with`` for drivers whose ``close`` method is synchronous. + Exit calls ``close(noreply_wait=False)``. + """ + + def __enter__(self) -> Self: + """Enter the context and return this connection.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + """Close the connection. Exceptions raised in the block propagate.""" + cast(_Closes, self).close(noreply_wait=False) + + +class AsyncContextManager: + """Asynchronous context manager that closes the object on exit. + + Use ``async with`` for drivers whose ``close`` method is awaitable. + """ + + async def __aenter__(self) -> Self: + """Enter the context and return this object.""" + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + """Close the object. Exceptions raised in the block propagate.""" + await cast(_Closes, self).close() + + +class AsyncConnectionContextManager: + """Asynchronous context manager that closes a connection on exit. + + Use ``async with`` for drivers whose ``close`` method is awaitable. + Exit calls ``close(noreply_wait=False)``. + """ + + async def __aenter__(self) -> Self: + """Enter the context and return this connection.""" + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + """Close the connection. Exceptions raised in the block propagate.""" + await cast(_Closes, self).close(noreply_wait=False) + + class Cursor: """Shared behavior for every cursor implementation. Callers iterate with ``iter`` or advance one result at a time with ``next``. + Concrete cursors add the context manager for their driver: ``with`` when + ``close`` is synchronous, and ``async with`` when ``close`` is awaitable. * ``query`` is the original query that produced this cursor. @@ -242,12 +338,6 @@ def __init__( self._maybe_fetch_batch() self._extend_internal(first_response) - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.close() - @staticmethod def _empty_error() -> type[ReqlCursorEmpty]: """ @@ -384,9 +474,11 @@ class DefaultCursorEmpty(ReqlCursorEmpty, StopIteration): """ -class DefaultCursor(Cursor): +class DefaultCursor(Cursor, SyncContextManager): """ Default cursor used to get data. + + Use ``with`` to close the cursor when the block exits. """ def __iter__(self): @@ -838,6 +930,9 @@ class Connection: # pylint: disable=too-many-instance-attributes """ Handle connection lifecycle, managing the connection instance, connect, reconnect, connection close and more. + + Concrete connections add the context manager for their driver: ``with`` when + ``close`` is synchronous, and ``async with`` when ``close`` is awaitable. """ _r = None @@ -947,12 +1042,6 @@ def repl(self) -> "Connection": self._repl.set_connection(self) return self - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.close(noreply_wait=False) - def use(self, db: str): """ Set the encapsulated database to use. @@ -1054,9 +1143,11 @@ def get_json_encoder(self, query): return (query.json_encoder or self._json_encoder)() -class DefaultConnection(Connection): +class DefaultConnection(Connection, SyncConnectionContextManager): """ Default connection without async handlers. + + Use ``with`` to close the connection when the block exits. """ def __init__(self, *args, **kwargs): diff --git a/rethinkdb/net_asyncio.py b/rethinkdb/net_asyncio.py index 59e9ed2..35c891a 100644 --- a/rethinkdb/net_asyncio.py +++ b/rethinkdb/net_asyncio.py @@ -27,8 +27,15 @@ ReqlDriverError, ReqlTimeoutError, ) +from rethinkdb.net import ( + AsyncConnectionContextManager, + AsyncContextManager, + Cursor, + Query, + Response, + maybe_profile, +) from rethinkdb.net import Connection as ConnectionBase -from rethinkdb.net import Cursor, Query, Response, maybe_profile from rethinkdb.ql2_pb2 import Query as PbQuery from rethinkdb.ql2_pb2 import Response as PbResponse @@ -88,8 +95,12 @@ def translate_timeout_errors(): # to grab the next result. In addition, the waiting coroutine will schedule a # timeout at the given deadline (if provided), at which point the future will be # errored. -class AsyncioCursor(Cursor): - """The asyncio implementation of the Cursor object.""" +class AsyncioCursor(Cursor, AsyncContextManager): + """ + The asyncio implementation of the Cursor object. + + Use ``async with`` to close the cursor when the block exits. + """ def __init__(self, *args, **kwargs): self.new_response = asyncio.Future() @@ -378,8 +389,12 @@ async def _reader(self): await self.close(exception=ex) -class Connection(ConnectionBase): - """The asyncio implementation of the RethinkDB connection.""" +class Connection(ConnectionBase, AsyncConnectionContextManager): + """ + The asyncio implementation of the RethinkDB connection. + + Use ``async with`` to close the connection when the block exits. + """ def __init__(self, *args, **kwargs): super().__init__(ConnectionInstance, *args, **kwargs) @@ -390,12 +405,6 @@ def __init__(self, *args, **kwargs): f"Could not convert port {self.port} to an integer." ) from exc - async def __aenter__(self): - return self - - async def __aexit__(self, exception_type, exception_val, traceback): - await self.close(False) - async def reconnect( # pylint: disable=invalid-overridden-method self, noreply_wait=True, timeout=None ): diff --git a/rethinkdb/net_gevent.py b/rethinkdb/net_gevent.py index d762041..8de5bb8 100644 --- a/rethinkdb/net_gevent.py +++ b/rethinkdb/net_gevent.py @@ -32,7 +32,14 @@ ReqlTimeoutError, ) from rethinkdb.net import Connection as ConnectionBase -from rethinkdb.net import Cursor, Query, Response, maybe_profile +from rethinkdb.net import ( + Cursor, + Query, + Response, + SyncConnectionContextManager, + SyncContextManager, + maybe_profile, +) from rethinkdb.net import SocketWrapper as SocketWrapperBase from rethinkdb.ql2_pb2 import Query as PbQuery from rethinkdb.ql2_pb2 import Response as PbResponse @@ -40,8 +47,12 @@ __all__ = ["Connection"] -class GeventCursor(Cursor): - """Gevent-based cursor implementation for RethinkDB queries.""" +class GeventCursor(Cursor, SyncContextManager): + """ + Gevent-based cursor implementation for RethinkDB queries. + + Use ``with`` to close the cursor when the block exits. + """ def __init__(self, *args, **kwargs): self.new_response = Event() @@ -340,8 +351,12 @@ def _reader(self): self.close(exception=exc) -class Connection(ConnectionBase): - """Gevent-based RethinkDB connection.""" +class Connection(ConnectionBase, SyncConnectionContextManager): + """ + Gevent-based RethinkDB connection. + + Use ``with`` to close the connection when the block exits. + """ def __init__(self, *args, **kwargs): super().__init__(ConnectionInstance, *args, **kwargs) diff --git a/rethinkdb/net_tornado.py b/rethinkdb/net_tornado.py index 1417160..dbdd420 100644 --- a/rethinkdb/net_tornado.py +++ b/rethinkdb/net_tornado.py @@ -31,8 +31,15 @@ ReqlDriverError, ReqlTimeoutError, ) +from rethinkdb.net import ( + AsyncConnectionContextManager, + AsyncContextManager, + Cursor, + Query, + Response, + maybe_profile, +) from rethinkdb.net import Connection as ConnectionBase -from rethinkdb.net import Cursor, Query, Response, maybe_profile from rethinkdb.ql2_pb2 import Query as PbQuery from rethinkdb.ql2_pb2 import Response as PbResponse @@ -58,9 +65,11 @@ async def with_absolute_timeout(deadline, generator, **kwargs): # to grab the next result. In addition, the waiting coroutine will schedule a # timeout at the given deadline (if provided), at which point the future will be # errored. -class TornadoCursor(Cursor): +class TornadoCursor(Cursor, AsyncContextManager): """ The Tornado implementation of the Cursor object. + + Use ``async with`` to close the cursor when the block exits. """ def __init__(self, *args, **kwargs): @@ -85,6 +94,14 @@ async def __anext__(self): except ReqlCursorEmpty as exc: raise StopAsyncIteration from exc + async def close(self): # pylint: disable=invalid-overridden-method + """Close the cursor and wait for the STOP query.""" + if self.error is None: + self.error = self._empty_error() + if self.conn.is_open(): + self.outstanding_requests += 1 + await self.conn.parent.stop(self) + def extend(self, res_buf): Cursor.extend(self, res_buf) self.new_response.set_result(True) @@ -382,9 +399,11 @@ async def _handle_response(self, token: int, buf: bytes) -> None: # Wrap functions from the base connection class that may throw - these will # put any exception inside a Future and return it. -class Connection(ConnectionBase): +class Connection(ConnectionBase, AsyncConnectionContextManager): """ A RethinkDB connection using the Tornado event loop. + + Use ``async with`` to close the connection when the block exits. """ def __init__(self, *args, **kwargs): diff --git a/rethinkdb/net_trio.py b/rethinkdb/net_trio.py index 796a202..f1ec6d6 100644 --- a/rethinkdb/net_trio.py +++ b/rethinkdb/net_trio.py @@ -31,8 +31,15 @@ ReqlDriverError, ReqlTimeoutError, ) +from rethinkdb.net import ( + AsyncConnectionContextManager, + Cursor, + Query, + Response, + make_connection, + maybe_profile, +) from rethinkdb.net import Connection as ConnectionBase -from rethinkdb.net import Cursor, Query, Response, make_connection, maybe_profile __all__ = ["Connection"] # pylint: disable=missing-class-docstring,missing-function-docstring @@ -108,7 +115,11 @@ def _reql_timeout(seconds): class TrioCursor(Cursor, trio.abc.AsyncResource): - """A cursor that allows async iteration within the Trio framework.""" + """ + A cursor that allows async iteration within the Trio framework. + + Use ``async with`` to close the cursor when the block exits. + """ def __init__(self, *args, **kwargs): """Constructor""" @@ -410,7 +421,13 @@ async def _reader_task(self): self._reader_ended_event.set() -class Connection(ConnectionBase): +class Connection(ConnectionBase, AsyncConnectionContextManager): + """ + A RethinkDB connection using the Trio event loop. + + Use ``async with`` to close the connection when the block exits. + """ + def __init__(self, *args, **kwargs): self._nursery = kwargs.pop("nursery", None) super().__init__(ConnectionInstance, *args, **kwargs) diff --git a/rethinkdb/net_twisted.py b/rethinkdb/net_twisted.py index 93b8ad2..86e80d9 100644 --- a/rethinkdb/net_twisted.py +++ b/rethinkdb/net_twisted.py @@ -38,8 +38,15 @@ ReqlDriverError, ReqlTimeoutError, ) +from rethinkdb.net import ( + AsyncConnectionContextManager, + AsyncContextManager, + Cursor, + Query, + Response, + maybe_profile, +) from rethinkdb.net import Connection as ConnectionBase -from rethinkdb.net import Cursor, Query, Response, maybe_profile from rethinkdb.ql2_pb2 import Query as PbQuery from rethinkdb.ql2_pb2 import Response as PbResponse @@ -214,14 +221,27 @@ def __iter__(self): return iter(self.pending) -class TwistedCursor(Cursor): - """Cursor implementation backed by Twisted Deferreds.""" +class TwistedCursor(Cursor, AsyncContextManager): + """ + Cursor implementation backed by Twisted Deferreds. + + Use ``async with`` to close the cursor when the block exits. + """ def __init__(self, *args: Any, **kwargs: Any) -> None: kwargs.setdefault("items_type", CursorItems) super().__init__(*args, **kwargs) self.waiting: list[Deferred[Any]] = [] + @inlineCallbacks + def close(self) -> Generator: # pylint: disable=invalid-overridden-method + """Close the cursor and wait for the STOP query.""" + if self.error is None: + self.error = self._empty_error() + if self.conn.is_open(): + self.outstanding_requests += 1 + yield self.conn.parent._stop(self) # pylint: disable=protected-access + def extend(self, res_buf: bytes) -> None: super().extend(res_buf) @@ -486,8 +506,11 @@ def run_query(self, query: Query, noreply: bool) -> Generator: return res -class Connection(ConnectionBase): - """A RethinkDB connection using the Twisted event loop.""" +class Connection(ConnectionBase, AsyncConnectionContextManager): + """A RethinkDB connection using the Twisted event loop. + + Use ``async with`` to close the connection when the block exits. + """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(ConnectionInstance, *args, **kwargs) @@ -501,9 +524,16 @@ def reconnect( return res @inlineCallbacks - def close(self, *args: Any, **kwargs: Any) -> Generator: - res = yield super().close(*args, **kwargs) or None - return res + def close(self, noreply_wait: bool = True) -> Generator: + """Close the connection and wait for the transport to finish.""" + if self._instance is None: + return + + token = self._new_token() if noreply_wait else None + instance = self._instance + self._next_token = 0 + self._instance = None + yield instance.close(noreply_wait, token) @inlineCallbacks def noreply_wait(self) -> Generator: diff --git a/tests/integration/test_net_asyncio.py b/tests/integration/test_net_asyncio.py index 29eda1a..510b9d3 100644 --- a/tests/integration/test_net_asyncio.py +++ b/tests/integration/test_net_asyncio.py @@ -27,6 +27,7 @@ def cleanup_test_dbs(): test_dbs = [ "test_asyncio_between_db", + "test_asyncio_cursor_cm_db", "test_asyncio_cursor_db", "test_asyncio_helpers_db", "test_asyncio_db", @@ -320,3 +321,49 @@ async def test_asyncio_with_test_helpers(conn): await assert_test_table_async(lambda *args: args[0], connection, scenarios) await drop_db_async(db_name, connection) + + +@pytest.mark.asyncio +@pytest.mark.integration +async def test_asyncio_connection_context_manager(conn): + """async with closes the asyncio connection.""" + connection = await conn + async with connection: + assert connection.is_open() + result = await connection.start(query.db_list()) + assert isinstance(result, list) + + assert connection.is_open() is False + + +@pytest.mark.asyncio +@pytest.mark.integration +async def test_asyncio_cursor_context_manager(conn): + """async with closes the asyncio cursor, and a second close is safe.""" + connection = await conn + db_name = "test_asyncio_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass + + await connection.start(query.db_create(db_name)) + await connection.start(query.db(db_name).table_create(table_name)) + inserted = await connection.start( + query.db(db_name).table(table_name).insert([{"id": i} for i in range(5)]) + ) + assert inserted["inserted"] == 5 + + cursor = await connection.start(query.db(db_name).table(table_name)) + async with cursor: + async for _row in cursor: + break + assert cursor.error is not None + await cursor.close() + finally: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass diff --git a/tests/integration/test_net_gevent.py b/tests/integration/test_net_gevent.py index e6fe519..c496abc 100644 --- a/tests/integration/test_net_gevent.py +++ b/tests/integration/test_net_gevent.py @@ -25,6 +25,7 @@ def cleanup_test_dbs(): test_dbs = [ "test_gevent_between_db", + "test_gevent_cursor_cm_db", "test_gevent_cursor_db", "test_gevent_helpers_db", "test_gevent_db", @@ -384,3 +385,48 @@ def test_gevent_database_and_table_operations(conn): connection.start(query.db_drop(db_name)) except Exception: pass + + +@pytest.mark.gevent +@pytest.mark.integration +def test_gevent_connection_context_manager(conn): + """with closes the gevent connection.""" + connection = conn + assert connection.is_open() + with connection: + result = connection.start(query.db_list()) + assert isinstance(result, list) + + assert connection.is_open() is False + + +@pytest.mark.gevent +@pytest.mark.integration +def test_gevent_cursor_context_manager(conn): + """with closes the gevent cursor, and a second close is safe.""" + connection = conn + db_name = "test_gevent_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + connection.start(query.db_drop(db_name)) + except Exception: + pass + + connection.start(query.db_create(db_name)) + connection.start(query.db(db_name).table_create(table_name)) + inserted = connection.start( + query.db(db_name).table(table_name).insert([{"id": i} for i in range(5)]) + ) + assert inserted["inserted"] == 5 + + cursor = connection.start(query.db(db_name).table(table_name)) + with cursor: + next(cursor) + assert cursor.error is not None + cursor.close() + finally: + try: + connection.start(query.db_drop(db_name)) + except Exception: + pass diff --git a/tests/integration/test_net_tornado.py b/tests/integration/test_net_tornado.py index e0ba153..e345f3a 100644 --- a/tests/integration/test_net_tornado.py +++ b/tests/integration/test_net_tornado.py @@ -25,6 +25,7 @@ def cleanup_test_dbs(): test_dbs = [ "test_tornado_between_db", + "test_tornado_cursor_cm_db", "test_tornado_cursor_db", "test_tornado_helpers_db", "test_tornado_db", @@ -309,3 +310,51 @@ async def test_tornado_with_test_helpers(conn): await assert_test_table_async(lambda *args: args[0], connection, scenarios) await drop_db_async(db_name, connection) + + +@pytest.mark.tornado +@pytest.mark.integration +@pytest.mark.asyncio +async def test_tornado_connection_context_manager(conn): + """async with closes the Tornado connection.""" + connection = await conn + async with connection: + assert connection.is_open() + result = await connection.start(query.db_list()) + assert isinstance(result, list) + + assert connection.is_open() is False + + +@pytest.mark.tornado +@pytest.mark.integration +@pytest.mark.asyncio +async def test_tornado_cursor_context_manager(conn): + """async with closes the Tornado cursor, and a second close is safe.""" + connection = await conn + db_name = "test_tornado_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass + + await connection.start(query.db_create(db_name)) + await connection.start(query.db(db_name).table_create(table_name)) + inserted = await connection.start( + query.db(db_name).table(table_name).insert([{"id": i} for i in range(5)]) + ) + assert inserted["inserted"] == 5 + + cursor = await connection.start(query.db(db_name).table(table_name)) + async with cursor: + async for _row in cursor: + break + assert cursor.error is not None + await cursor.close() + finally: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass diff --git a/tests/integration/test_net_trio.py b/tests/integration/test_net_trio.py index b492e0e..a0c1e87 100644 --- a/tests/integration/test_net_trio.py +++ b/tests/integration/test_net_trio.py @@ -26,6 +26,7 @@ def cleanup_test_dbs(): test_dbs = [ "test_trio_between_db", + "test_trio_cursor_cm_db", "test_trio_cursor_db", "test_trio_helpers_db", "test_trio_db", @@ -305,3 +306,49 @@ async def test_trio_with_test_helpers(conn): await assert_test_table_async(lambda *args: args[0], connection, scenarios) await drop_db_async(db_name, connection) + + +@pytest.mark.trio +@pytest.mark.integration +async def test_trio_connection_context_manager(conn): + """async with closes the Trio connection.""" + connection = await conn + async with connection: + assert connection.is_open() + result = await connection.start(query.db_list()) + assert isinstance(result, list) + + assert connection.is_open() is False + + +@pytest.mark.trio +@pytest.mark.integration +async def test_trio_cursor_context_manager(conn): + """async with closes the Trio cursor, and a second close is safe.""" + connection = await conn + db_name = "test_trio_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass + + await connection.start(query.db_create(db_name)) + await connection.start(query.db(db_name).table_create(table_name)) + inserted = await connection.start( + query.db(db_name).table(table_name).insert([{"id": i} for i in range(5)]) + ) + assert inserted["inserted"] == 5 + + cursor = await connection.start(query.db(db_name).table(table_name)) + async with cursor: + async for _row in cursor: + break + assert cursor.error is not None + await cursor.close() + finally: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass diff --git a/tests/integration/test_net_twisted.py b/tests/integration/test_net_twisted.py index 517bec3..b00626b 100644 --- a/tests/integration/test_net_twisted.py +++ b/tests/integration/test_net_twisted.py @@ -25,6 +25,7 @@ def cleanup_test_dbs(): test_dbs = [ "test_twisted_between_db", + "test_twisted_cursor_cm_db", "test_twisted_cursor_db", "test_twisted_helpers_db", "test_twisted_db", @@ -317,3 +318,57 @@ def run_test(): yield connection.start(query.db_drop(db_name)) return run_test() + + +@pytest.mark.twisted +@pytest.mark.integration +def test_twisted_connection_context_manager(conn): + """async with closes the Twisted connection.""" + + async def run_test(): + connection = await conn + async with connection: + assert connection.is_open() + result = await connection.start(query.db_list()) + assert isinstance(result, list) + assert connection.is_open() is False + + return defer.ensureDeferred(run_test()) + + +@pytest.mark.twisted +@pytest.mark.integration +def test_twisted_cursor_context_manager(conn): + """async with closes the Twisted cursor, and a second close is safe.""" + + async def run_test(): + connection = await conn + db_name = "test_twisted_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass + + await connection.start(query.db_create(db_name)) + await connection.start(query.db(db_name).table_create(table_name)) + inserted = await connection.start( + query.db(db_name) + .table(table_name) + .insert([{"id": i} for i in range(5)]) + ) + assert inserted["inserted"] == 5 + + cursor = await connection.start(query.db(db_name).table(table_name)) + async with cursor: + await cursor.next() + assert cursor.error is not None + await cursor.close() + finally: + try: + await connection.start(query.db_drop(db_name)) + except Exception: + pass + + return defer.ensureDeferred(run_test()) diff --git a/tests/integration/test_queries.py b/tests/integration/test_queries.py index d7eb1c7..0e1b36d 100644 --- a/tests/integration/test_queries.py +++ b/tests/integration/test_queries.py @@ -1256,3 +1256,46 @@ def test_js(conn): ] assert_test_table(query.js, conn, scenarios) + + +@pytest.mark.integration +def test_default_connection_context_manager(conn): + """with closes the default connection.""" + assert conn.is_open() + with conn: + result = query.db_list().run(conn) + assert isinstance(result, list) + assert conn.is_open() is False + + +@pytest.mark.integration +def test_default_cursor_context_manager(conn): + """with closes the default cursor, and a second close is safe.""" + db_name = "test_default_cursor_cm_db" + table_name = "test_cursor_cm_table" + try: + try: + query.db_drop(db_name).run(conn) + except Exception: + pass + + query.db_create(db_name).run(conn) + query.db(db_name).table_create(table_name).run(conn) + inserted = ( + query.db(db_name) + .table(table_name) + .insert([{"id": i} for i in range(5)]) + .run(conn) + ) + assert inserted["inserted"] == 5 + + cursor = query.db(db_name).table(table_name).run(conn) + with cursor: + next(cursor) + assert cursor.error is not None + cursor.close() + finally: + try: + query.db_drop(db_name).run(conn) + except Exception: + pass diff --git a/tests/test_net.py b/tests/test_net.py index a51991b..a8194c7 100644 --- a/tests/test_net.py +++ b/tests/test_net.py @@ -250,3 +250,125 @@ def test_make_connection_with_ssl(conn_params): conn_params["ssl"], conn_params["handshake_version"], ) + + +def _assert_sync_context_manager(cls: type) -> None: + """The class supports ``with`` and not ``async with``.""" + assert callable(getattr(cls, "__enter__", None)) + assert callable(getattr(cls, "__exit__", None)) + assert getattr(cls, "__aenter__", None) is None + assert getattr(cls, "__aexit__", None) is None + + +def _assert_async_context_manager(cls: type) -> None: + """The class supports ``async with`` and not ``with``.""" + assert callable(getattr(cls, "__aenter__", None)) + assert callable(getattr(cls, "__aexit__", None)) + assert getattr(cls, "__enter__", None) is None + assert getattr(cls, "__exit__", None) is None + + +def test_sync_context_manager_closes_and_propagates(): + """A synchronous context manager closes on exit and does not swallow errors.""" + from rethinkdb.net import SyncConnectionContextManager, SyncContextManager + + class Cursor(SyncContextManager): + def __init__(self) -> None: + self.closed = False + + def close(self) -> None: + self.closed = True + + cursor = Cursor() + with cursor: + assert cursor.closed is False + assert cursor.closed is True + + cursor.closed = False + with pytest.raises(RuntimeError, match="boom"), cursor: + raise RuntimeError("boom") + assert cursor.closed is True + + class Conn(SyncConnectionContextManager): + def __init__(self) -> None: + self.noreply_wait: bool | None = None + + def close(self, noreply_wait: bool = True) -> None: + self.noreply_wait = noreply_wait + + conn = Conn() + with pytest.raises(RuntimeError, match="boom"), conn: + raise RuntimeError("boom") + assert conn.noreply_wait is False + + +@pytest.mark.asyncio +async def test_async_context_manager_closes_and_propagates(): + """An asynchronous context manager awaits close and does not swallow errors.""" + from rethinkdb.net import AsyncConnectionContextManager, AsyncContextManager + + class Cursor(AsyncContextManager): + def __init__(self) -> None: + self.closed = False + + async def close(self) -> None: + self.closed = True + + cursor = Cursor() + async with cursor: + assert cursor.closed is False + assert cursor.closed is True + + cursor.closed = False + with pytest.raises(RuntimeError, match="boom"): + async with cursor: + raise RuntimeError("boom") + assert cursor.closed is True + + class Conn(AsyncConnectionContextManager): + def __init__(self) -> None: + self.noreply_wait: bool | None = None + + async def close(self, noreply_wait: bool = True) -> None: + self.noreply_wait = noreply_wait + + conn = Conn() + async with conn: + pass + assert conn.noreply_wait is False + + conn.noreply_wait = None + with pytest.raises(RuntimeError, match="boom"): + async with conn: + raise RuntimeError("boom") + assert conn.noreply_wait is False + + +def test_driver_context_manager_protocols(): + """Each driver exposes only the context manager its close method can honor.""" + from rethinkdb.net import DefaultConnection, DefaultCursor + from rethinkdb.net_asyncio import AsyncioCursor + from rethinkdb.net_asyncio import Connection as AsyncioConnection + from rethinkdb.net_gevent import Connection as GeventConnection + from rethinkdb.net_gevent import GeventCursor + from rethinkdb.net_tornado import Connection as TornadoConnection + from rethinkdb.net_tornado import TornadoCursor + from rethinkdb.net_trio import Connection as TrioConnection + from rethinkdb.net_trio import TrioCursor + from rethinkdb.net_twisted import Connection as TwistedConnection + from rethinkdb.net_twisted import TwistedCursor + + for cls in (DefaultCursor, DefaultConnection, GeventCursor, GeventConnection): + _assert_sync_context_manager(cls) + + for cls in ( + AsyncioCursor, + AsyncioConnection, + TornadoCursor, + TornadoConnection, + TrioCursor, + TrioConnection, + TwistedCursor, + TwistedConnection, + ): + _assert_async_context_manager(cls)