|
| 1 | +"""Utilities to use during testing""" |
| 2 | + |
| 3 | +from contextlib import asynccontextmanager |
| 4 | +from typing import AsyncGenerator |
| 5 | + |
| 6 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 7 | + |
| 8 | +from context_async_sqlalchemy import ( |
| 9 | + DBConnect, |
| 10 | + init_db_session_ctx, |
| 11 | + put_db_session_to_context, |
| 12 | + reset_db_session_ctx, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +@asynccontextmanager |
| 17 | +async def rollback_session( |
| 18 | + connection: DBConnect, |
| 19 | +) -> AsyncGenerator[AsyncSession]: |
| 20 | + """A session that always rolls back""" |
| 21 | + session_maker = await connection.get_session_maker() |
| 22 | + async with session_maker() as session: |
| 23 | + try: |
| 24 | + yield session |
| 25 | + finally: |
| 26 | + await session.rollback() |
| 27 | + |
| 28 | + |
| 29 | +@asynccontextmanager |
| 30 | +async def set_test_context() -> AsyncGenerator[None]: |
| 31 | + """ |
| 32 | + Opens a context similar to middleware, but doesn't commit or |
| 33 | + rollback automatically. This task falls to the fixture in tests. |
| 34 | + """ |
| 35 | + token = init_db_session_ctx() |
| 36 | + try: |
| 37 | + yield |
| 38 | + finally: |
| 39 | + await reset_db_session_ctx( |
| 40 | + token, |
| 41 | + # Don't close the session here, as you opened in fixture. |
| 42 | + with_close=False, |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +@asynccontextmanager |
| 47 | +async def put_savepoint_session_in_ctx( |
| 48 | + connection: DBConnect, |
| 49 | + session: AsyncSession, |
| 50 | +) -> AsyncGenerator[None]: |
| 51 | + """ |
| 52 | + Sets the context to a session that uses a save point instead of creating |
| 53 | + a transaction. You need to pass the session you're using inside |
| 54 | + your tests to attach a new session to the same connection. |
| 55 | +
|
| 56 | + It is also important to use this function inside set_test_context. |
| 57 | + """ |
| 58 | + session_maker = await connection.get_session_maker() |
| 59 | + async with session_maker( |
| 60 | + # Bind to the same connection |
| 61 | + bind=await session.connection(), |
| 62 | + # Instead of opening a transaction, it creates a save point |
| 63 | + join_transaction_mode="create_savepoint", |
| 64 | + ) as session: |
| 65 | + put_db_session_to_context(connection, session) |
| 66 | + yield |
0 commit comments