File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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 ])
You can’t perform that action at this time.
0 commit comments