Skip to content

Support database transactions in async tests - #1305

Open
lode-braced wants to merge 3 commits into
pytest-dev:mainfrom
lode-braced:fix/async-database-tests
Open

Support database transactions in async tests#1305
lode-braced wants to merge 3 commits into
pytest-dev:mainfrom
lode-braced:fix/async-database-tests

Conversation

@lode-braced

Copy link
Copy Markdown

Fixes #580.

Supersedes #1223.

What

Share Django database connections between pytest's main thread and asgiref's thread-sensitive executor for pytest-asyncio tests.

This keeps direct async ORM calls, synchronous fixtures, and Django AsyncClient requests inside the transaction managed by pytest-django's db fixture.

Why

pytest-django opens the test transaction on the main thread, while Django executes async ORM work on a synchronous executor thread. Because Django connections are normally thread-local, that work can use a different connection and escape the transaction rollback.

Deviations

Unlike #1223, database setup and teardown remain synchronous on the main thread. Synchronous fixtures are also left on the main thread rather than moved onto the executor. The connection itself is temporarily shared between both threads.

Support is intentionally scoped to pytest-asyncio's default thread-sensitive executor, as used by direct async ORM calls and Django's test AsyncClient. Arbitrary user-created ThreadSensitiveContext executors and production ASGI execution are outside this PR's scope.

@lode-braced
lode-braced marked this pull request as ready for review August 6, 2026 13:13
@lode-braced

lode-braced commented Aug 6, 2026

Copy link
Copy Markdown
Author

@bluetech here's the alternate, newer version of fixing interaction with pytest-asyncio, by having the main thread and the async thread pool executor share one connection.

This one allows for more "it just works" behaviour for users, allowing them to combine sync and async fixtures as they please. In my opinion the better experience, but up to you to compare it against #1223 and see what you like best. Note the previous pr is a lot larger as I am quite defensive there: given that sync/async fixture combining did not work there, I wanted to make sure we inform the users instead of having "silent weird behaviours" as it is currently for async tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Database transactions with asyncio

1 participant