Skip to content

Commit 0525d62

Browse files
author
Lode Rosseel
committed
Revert "Drop sync extra checks"
This reverts commit 7673814.
1 parent 1bf9be6 commit 0525d62

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

docs/database.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,15 @@ actively restricts where database connections may be opened:
132132
or by requesting ``transactional_db`` if you must keep sync fixtures.
133133
See :ref:`async-db-behavior` for more details.
134134

135+
- In sync tests: database access is only allowed from the main thread. Attempting to use the database connection
136+
from a different thread will raise::
137+
138+
RuntimeError: Database access is only allowed in the main thread, modify your
139+
test fixtures to be sync or use the transactional_db fixture.
140+
141+
Fix this by ensuring all database transactions run in the main thread (e.g., avoiding the use of async fixtures),
142+
or use ``transactional_db`` to allow mixing.
143+
135144

136145
.. _`multi-db`:
137146

pytest_django/plugin.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -858,10 +858,25 @@ def _unblocked_async_only(self, *args, **kwargs):
858858
elif self._real_ensure_connection is not None:
859859
self._real_ensure_connection(*args, **kwargs)
860860

861-
def unblock(self, async_only=False) -> AbstractContextManager[None]:
861+
def _unblocked_sync_only(self, *args, **kwargs):
862+
__tracebackhide__ = True
863+
if threading.current_thread() != threading.main_thread():
864+
raise RuntimeError(
865+
"Database access is only allowed in the main thread, "
866+
"modify your test fixtures to be sync or use the transactional_db fixture."
867+
"See https://pytest-django.readthedocs.io/en/latest/database.html#db-thread-safeguards for more information."
868+
)
869+
elif self._real_ensure_connection is not None:
870+
self._real_ensure_connection(*args, **kwargs)
871+
872+
def unblock(self, sync_only=False, async_only=False) -> AbstractContextManager[None]:
862873
"""Enable access to the Django database."""
874+
if sync_only and async_only:
875+
raise ValueError("Cannot use both sync_only and async_only. Choose at most one.")
863876
self._save_active_wrapper()
864-
if async_only:
877+
if sync_only:
878+
self._dj_db_wrapper.ensure_connection = self._unblocked_sync_only
879+
elif async_only:
865880
self._dj_db_wrapper.ensure_connection = self._unblocked_async_only
866881
else:
867882
self._dj_db_wrapper.ensure_connection = self._real_ensure_connection

0 commit comments

Comments
 (0)