Support database transactions in async tests - #1305
Conversation
|
@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. |
|
This one seems to access very internal/private parts of
But more to the code itself, I'm not sure I fully follow it, but IIUC even though the main & executor threads are different, they will still share a connection? That seems dangerous, since the |
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
AsyncClientrequests inside the transaction managed by pytest-django'sdbfixture.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-createdThreadSensitiveContextexecutors and production ASGI execution are outside this PR's scope.