Skip to content

Commit b3300f6

Browse files
committed
https://github.com/krylosov-aa/context-async-sqlalchemy/issues/8
1 parent b677fd8 commit b3300f6

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

exmaples/fastapi_example/tests/transactional/conftest.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import pytest_asyncio
1616

17-
from sqlalchemy.ext.asyncio import AsyncSession
17+
from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession
1818

1919
from exmaples.fastapi_example.database import master
2020
from context_async_sqlalchemy import (
@@ -24,6 +24,18 @@
2424
)
2525

2626

27+
@pytest_asyncio.fixture
28+
async def db_session_test(
29+
session_maker_test: async_sessionmaker[AsyncSession],
30+
) -> AsyncGenerator[AsyncSession]:
31+
"""The session that is used inside the test"""
32+
async with session_maker_test() as session:
33+
try:
34+
yield session
35+
finally:
36+
await session.rollback()
37+
38+
2739
@pytest_asyncio.fixture(autouse=True)
2840
async def db_session_override(
2941
db_session_test: AsyncSession,
@@ -34,7 +46,15 @@ async def db_session_override(
3446
if it already exists.
3547
"""
3648
token = init_db_session_ctx()
37-
put_db_session_to_context(master.context_key, db_session_test)
49+
50+
# Here we create a new session with save point behavior.
51+
# This means that committing within the application will save and
52+
# release the save point, rather than committing the entire transaction.
53+
conn = await db_session_test.connection()
54+
new_session = AsyncSession(
55+
bind=conn, join_transaction_mode="create_savepoint"
56+
)
57+
put_db_session_to_context(master.context_key, new_session)
3858
try:
3959
yield
4060
finally:

exmaples/fastapi_example/tests/transactional/test_routes.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,25 @@ async def test_example_with_db_session(
3636
result = await db_session_test.execute(select(ExampleTable))
3737
row = result.scalar_one()
3838
assert row.text == "example_with_db_session"
39+
40+
41+
@pytest.mark.asyncio
42+
async def test_example_with_db_session_and_atomic(
43+
client: AsyncClient,
44+
db_session_test: AsyncSession,
45+
) -> None:
46+
"""
47+
Since the handler involves manual session management,
48+
such a handler should only be tested in non-transactional tests.
49+
"""
50+
# Act
51+
response = await client.post(
52+
"/example_with_db_session_and_atomic",
53+
)
54+
55+
# Assert
56+
assert response.status_code == HTTPStatus.OK
57+
58+
result = await db_session_test.execute(select(ExampleTable))
59+
row = result.scalar_one()
60+
assert row.text == "example_with_db_session_and_atomic"

0 commit comments

Comments
 (0)