Skip to content

Commit 3c986bf

Browse files
author
Lode Rosseel
committed
Add test case for db access outside main thread in sync context
1 parent 593d02f commit 3c986bf

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

tests/test_db_thread_safeguards.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from __future__ import annotations
2+
3+
import threading
4+
5+
import pytest
6+
7+
from pytest_django_test.app.models import Item
8+
9+
10+
@pytest.mark.django_db
11+
def test_sync_db_access_in_non_main_thread_is_blocked() -> None:
12+
"""
13+
Ensure that when using the sync django_db helper (non-transactional),
14+
database access from a different thread raises the expected RuntimeError
15+
stating that DB access is only allowed in the main thread.
16+
17+
Mirrors the intent of the async equivalent test that checks thread
18+
safeguards for async contexts.
19+
"""
20+
captured: list[BaseException | None] = [None]
21+
22+
def worker() -> None:
23+
try:
24+
# Any ORM operation that touches the DB will attempt to ensure a connection.
25+
# This should raise from the "sync_only" db blocker in non-main threads.
26+
Item.objects.count()
27+
except BaseException as exc: # noqa: BLE001 - we want to capture exactly what is raised
28+
captured[0] = exc
29+
30+
t = threading.Thread(target=worker)
31+
t.start()
32+
t.join()
33+
34+
assert captured[0] is not None, "Expected DB access in worker thread to raise an exception"
35+
assert isinstance(captured[0], RuntimeError)
36+
assert "only allowed in the main thread" in str(captured[0])

0 commit comments

Comments
 (0)