- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
You replace session.commit() with a no-op so your integration tests stop leaving rows behind. The suite goes green and stays green. Then someone deletes the commit() line from the adapter. The suite is still green, because the test reads the order back through the same session, and by default a session sees its own uncommitted work. Production saves nothing.
Emptying the tables after each test avoids that trap, at the price of cleanup you have to keep in step with the schema. SQLAlchemy documents a third way: open a transaction outside the session, let the adapter call commit() for real inside a savepoint (a mark in the transaction that you can roll back to), then roll back the outer transaction. The recipe is in the 2.0 docs and the 2.1 docs, and both say it runs in SQLAlchemy's own CI. 2.1.9 is the current release, and the code below targets it.
An adapter that owns its commit
Here is a small project on PostgreSQL with psycopg 3. The SQLAlchemy dialect for psycopg has a sync and an async implementation under the same name, so one URL covers both. The async extra is spelled out because 2.1 no longer installs greenlet by default.
pip install "sqlalchemy[asyncio]>=2.1.9" "psycopg[binary]>=3.2.4" \
fastapi httpx pytest pytest-asyncio
export TEST_DATABASE_URL=postgresql+psycopg:///shop_test
The schema is two tables:
# app/db.py
from sqlalchemy import ForeignKey, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from sqlalchemy.orm import (
DeclarativeBase, Mapped, Session, mapped_column, sessionmaker,
)
NOTIFY = text("SELECT pg_notify('orders', :id)")
class Base(DeclarativeBase):
pass
class CustomerRow(Base):
__tablename__ = "customers"
id: Mapped[str] = mapped_column(primary_key=True)
class OrderRow(Base):
__tablename__ = "orders"
id: Mapped[str] = mapped_column(primary_key=True)
customer_id: Mapped[str] = mapped_column(
ForeignKey(
"customers.id", deferrable=True, initially="DEFERRED"
)
)
The sync and async adapters have the same shape:
# app/db.py, continued
class SqlOrders:
def __init__(self, sessions: sessionmaker[Session]) -> None:
self._sessions = sessions
def add(self, order_id: str, customer_id: str) -> None:
with self._sessions() as s:
s.add(OrderRow(id=order_id, customer_id=customer_id))
s.execute(NOTIFY, {"id": order_id})
s.commit()
def exists(self, order_id: str) -> bool:
with self._sessions() as s:
return s.get(OrderRow, order_id) is not None
class AsyncSqlOrders:
def __init__(
self, sessions: async_sessionmaker[AsyncSession]
) -> None:
self._sessions = sessions
async def add(self, order_id: str, customer_id: str) -> None:
async with self._sessions() as s:
s.add(OrderRow(id=order_id, customer_id=customer_id))
await s.execute(NOTIFY, {"id": order_id})
await s.commit()
async def exists(self, order_id: str) -> bool:
async with self._sessions() as s:
return await s.get(OrderRow, order_id) is not None
Each adapter takes a session factory and opens a fresh session per call. That makes the read in exists() go to the database. The deferred foreign key and the pg_notify call are there for the limits section, where both cause trouble.
If a unit of work owns your commit instead, hand it the same factory. The fixture doesn't care which object calls commit().
The sync fixture
One engine serves the whole run. Its fixture drops and recreates the tables, so point it at a throwaway database:
# tests/conftest.py
import os
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine, delete
from sqlalchemy.ext.asyncio import (
async_sessionmaker, create_async_engine,
)
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import NullPool
from app.db import Base, CustomerRow, OrderRow
from app.main import app, get_sessions
URL = os.environ["TEST_DATABASE_URL"]
if not URL.endswith("_test"):
raise RuntimeError("these fixtures drop tables")
@pytest.fixture(scope="session")
def engine():
engine = create_engine(URL)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add(CustomerRow(id="c-1"))
s.commit()
yield engine
engine.dispose()
The isolation itself is two short fixtures that run once per test:
# tests/conftest.py, continued
@pytest.fixture
def connection(engine):
with engine.connect() as conn:
outer = conn.begin()
yield conn
outer.rollback()
@pytest.fixture
def sessions(connection):
return sessionmaker(
bind=connection,
join_transaction_mode="create_savepoint",
)
The documented recipe binds one Session to the connection. This one binds the factory, so every session the adapter opens joins the same outer transaction. With create_savepoint, a session uses Connection.begin_nested() in all cases to create its own transaction. Its commit() becomes RELEASE SAVEPOINT, which merges the changes into the surrounding transaction. The outer rollback() then discards all of it.

The adapter paints for real, on a sheet of glass the test takes away afterwards.
Two tests show what you get:
# tests/test_orders.py
import pytest
from sqlalchemy.exc import IntegrityError
from app.db import AsyncSqlOrders, SqlOrders
@pytest.mark.parametrize("run", [1, 2])
def test_add_is_visible_to_a_new_session(sessions, run):
orders = SqlOrders(sessions)
orders.add("o-1", "c-1")
assert orders.exists("o-1")
def test_duplicate_keeps_the_first_order(sessions):
orders = SqlOrders(sessions)
orders.add("o-1", "c-1")
with pytest.raises(IntegrityError):
orders.add("o-1", "c-1")
assert orders.exists("o-1")
The first test runs twice with the same primary key, so if run 1 leaked its row, run 2 would raise. It also catches the bug from the opening. Delete s.commit() from add() and the with block closes the session, which rolls back its savepoint, and exists() returns False.
The second test is why the argument matters. Leave it out and you get conditional_savepoint, which creates savepoints only when the connection is already inside one. On a plain conn.begin() it behaves as rollback_only: commits are not propagated, but rollbacks are. The duplicate insert would then roll back your outer transaction, and the first order would go with it. Worse, going by the session source, the next session finds no transaction on the connection, begins its own, and its commit() is a real one.
The async fixture and a FastAPI endpoint on the same connection
The FastAPI app builds its engine in the lifespan and hands out the factory through a dependency:
# app/main.py
import os
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI, Request
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import (
AsyncSession, async_sessionmaker, create_async_engine,
)
from app.db import AsyncSqlOrders
@asynccontextmanager
async def lifespan(app: FastAPI):
engine = create_async_engine(os.environ["DATABASE_URL"])
app.state.sessions = async_sessionmaker(engine)
yield
await engine.dispose()
app = FastAPI(lifespan=lifespan)
async def get_sessions(
request: Request,
) -> async_sessionmaker[AsyncSession]:
return request.app.state.sessions
The endpoint builds its adapter from whatever factory that dependency returns:
# app/main.py, continued
Sessions = Annotated[
async_sessionmaker[AsyncSession], Depends(get_sessions)
]
class OrderIn(BaseModel):
order_id: str
customer_id: str
@app.post("/orders", status_code=201)
async def create_order(body: OrderIn, sessions: Sessions) -> OrderIn:
orders = AsyncSqlOrders(sessions)
await orders.add(body.order_id, body.customer_id)
return body
The async fixtures go at the bottom of conftest.py. AsyncSession passes extra keyword arguments to the sync Session it wraps, so the mode works unchanged:
# tests/conftest.py, continued
@pytest.fixture
async def async_sessions(engine):
db = create_async_engine(URL, poolclass=NullPool)
async with db.connect() as conn:
outer = await conn.begin()
yield async_sessionmaker(
bind=conn,
join_transaction_mode="create_savepoint",
)
await outer.rollback()
await db.dispose()
@pytest.fixture
async def client(async_sessions):
app.dependency_overrides[get_sessions] = lambda: async_sessions
transport = ASGITransport(app=app)
async with AsyncClient(
transport=transport, base_url="http://test"
) as c:
yield c
app.dependency_overrides.clear()
# tests/test_orders.py, continued
@pytest.mark.parametrize("run", [1, 2])
async def test_post_saves_the_order(client, async_sessions, run):
body = {"order_id": "o-1", "customer_id": "c-1"}
response = await client.post("/orders", json=body)
assert response.status_code == 201
assert await AsyncSqlOrders(async_sessions).exists("o-1")
# pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
asyncio_mode = "auto"
pytest-asyncio gives each test its own event loop by default, so the async engine is built per test with NullPool and no connection outlives its loop. HTTPX's AsyncClient replaces TestClient, which FastAPI says you can't use inside async test functions. The same page says AsyncClient won't trigger lifespan events. Here that helps: the test never reads DATABASE_URL, and the dependency override supplies the factory instead.
On Windows, psycopg's async side doesn't work with the default ProactorEventLoop.
Don't fire two requests with asyncio.gather in such a test. Both would stack savepoints on one connection, and releasing a savepoint also releases every one created after it.
Four limits, four failing tests
On PostgreSQL, nothing an adapter does through sessions reaches a real COMMIT, and some database behaviour only happens there. SQLite has the opposite problem: with Python's default driver settings, it commits too early. The first three limits assert what production does. The fourth asserts what the fixture promises, on a driver that breaks the promise.
Each is marked as an expected failure. With strict=True, a test that starts passing fails the suite, so you find out when a limit goes away. The marker can't tell you the test failed for the right reason, which is why the last section adds versions that commit.
# tests/test_limits.py
import psycopg
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.db import Base, CustomerRow, OrderRow, SqlOrders
def limit(reason):
return pytest.mark.xfail(
strict=True, raises=AssertionError, reason=reason
)
A second connection. PostgreSQL's default isolation level never shows uncommitted data to another session. A worker or a thread with its own connection finds nothing. If it tries to write the same key, it gets no error either: the insert waits for the other transaction to end, which in your test looks like a hang.
@limit("another connection can't see uncommitted rows")
def test_second_connection_sees_the_order(engine, sessions):
SqlOrders(sessions).add("o-1", "c-1")
with Session(engine) as other:
assert other.get(OrderRow, "o-1") is not None
Deferred constraints. They are not checked until transaction commit, so an order for a customer who doesn't exist goes straight through. This one has a workaround, in the second test. SET CONSTRAINTS ALL IMMEDIATE applies retroactively and fails if a pending check is violated:
@limit("deferred constraints are checked at COMMIT")
def test_unknown_customer_is_rejected(sessions):
try:
SqlOrders(sessions).add("o-1", "nobody")
except IntegrityError:
return
raise AssertionError("the order was accepted")
def test_unknown_customer_is_caught_early(connection, sessions):
SqlOrders(sessions).add("o-1", "nobody")
with pytest.raises(IntegrityError):
connection.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
Anything that happens on commit. Notifications are not delivered until and unless the transaction commits, and here it never does. The install line asks for psycopg 3.2.4 because earlier versions lost notifications that arrived between LISTEN and the start of the generator, and this test would then fail for the wrong reason:
def heard(engine, sessions):
url = engine.url.set(drivername="postgresql")
dsn = url.render_as_string(hide_password=False)
with psycopg.connect(dsn, autocommit=True) as listener:
listener.execute("LISTEN orders")
SqlOrders(sessions).add("o-1", "c-1")
got = listener.notifies(timeout=1, stop_after=1)
return [n.payload for n in got]
@limit("NOTIFY is delivered at COMMIT")
def test_listener_hears_about_the_order(engine, sessions):
assert heard(engine, sessions) == ["o-1"]
Temporary tables declared ON COMMIT DELETE ROWS or ON COMMIT DROP have the same problem. An adapter that relies on the table being emptied or dropped between commits will find it still there, rows included.
SQLite. Python's sqlite3 driver still defaults to legacy transaction control. In that mode it begins a transaction for DML but not for SAVEPOINT. To SQLite, a savepoint outside a transaction acts like BEGIN DEFERRED TRANSACTION, and releasing the outermost one is the same as COMMIT. Your outer rollback has nothing left to undo:
@pytest.mark.parametrize("args", [
pytest.param({}, marks=limit("RELEASE commits on SQLite")),
{"autocommit": False},
])
def test_sqlite_outer_rollback(tmp_path, args):
db = create_engine(
f"sqlite:///{tmp_path / 'shop.db'}", connect_args=args
)
Base.metadata.create_all(db)
with db.connect() as conn:
outer = conn.begin()
with Session(
conn, join_transaction_mode="create_savepoint"
) as s:
s.add(CustomerRow(id="c-1"))
s.commit()
outer.rollback()
with Session(db) as s:
assert s.get(CustomerRow, "c-1") is None
autocommit=False needs Python 3.12 or later and is SQLAlchemy's recommended setting there. The same page says legacy mode stops being the default in a future Python, "3.16 as of this writing". When that happens, the strict marker on the first case will tell you.
I haven't run any of the code in this post myself. If a marked test passes on your versions, strict=True fails the run and names it.
Keep a second fixture that really commits
Assertions about which rows the adapter wrote or read stay on sessions. Anything another connection sees, or the database does at commit time, gets the real engine and pays for the cleanup. Add this to conftest.py:
@pytest.fixture
def committed(engine):
yield sessionmaker(engine)
with engine.begin() as conn:
conn.execute(delete(OrderRow))
Then give the deferred constraint and the notification a test that has to pass:
# tests/test_limits.py, continued
def test_commit_rejects_unknown_customer(committed):
with pytest.raises(IntegrityError):
SqlOrders(committed).add("o-1", "nobody")
def test_listener_hears_a_committed_order(engine, committed):
assert heard(engine, committed) == ["o-1"]
The second one is the control for the NOTIFY limit. Misspell the channel in heard() and the expected failure still fails as expected, but this test goes red.

Most adapter tests belong on the covered bench. A few have to mark the real one, and clean up after.
Give each parallel test worker its own database. The engine fixture drops tables when it starts, committed rows are visible to everyone, and uncommitted ones hold locks.
now() will also surprise you in the savepoint tests: it returns the start time of the current transaction, so every row in one test gets the same timestamp and "newest first" assertions become a coin toss. Sequence values are not reclaimed on rollback either, so never assert that an order got id 1.
If this was useful
These fixtures only work because the adapter accepts its session factory from outside. Where to draw that line is what Hexagonal Architecture in Python is about: one async FastAPI and SQLAlchemy 2 codebase, with the same feature built five ways (Hexagonal, Clean, Onion, layered, vertical slice), then measured. Every listing that names a repo path is quoted from the free companion repo, so you can run it there, and the book is on Amazon.

Top comments (0)