python / expert
Snippet
Asynchronous Database Isolation Hooks for Channels Consumer Testing
Testing asynchronous Django Channels consumers with database isolation requires explicit transactional boundaries wrapped inside database_sync_to_async adaptors.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import pytestfrom channels.testing import WebsocketCommunicatorfrom channels.db import database_sync_to_asyncfrom django.db import transaction@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_async_consumer_transaction_isolation(application_factory):communicator = WebsocketCommunicator(application_factory(), "/ws/updates/")connected, _ = await communicator.connect()assert connected@database_sync_to_asyncdef get_atomic_state():with transaction.atomic():return Trueassert await get_atomic_state()await communicator.disconnect()
django
Breakdown
1
@pytest.mark.django_db(transaction=True)
Enables database access with real transactional rollbacks inside pytest-django async tests.
2
@database_sync_to_async
Wraps synchronous Django ORM database queries into threadpool coroutines suitable for async event loops.
3
with transaction.atomic():
Guarantees isolated database transaction boundaries within synchronous context adapted for async execution.