python / intermediate
Snippet
Unit Testing Asynchronous Django Views with AsyncRequestFactory
Testing coroutine-based Django views requires an asynchronous request context. AsyncRequestFactory creates non-blocking mock HTTP request objects that can be directly awaited within async test cases executed by pytest-asyncio.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
import pytestfrom django.test import AsyncRequestFactoryfrom myapp.views import async_status_view@pytest.mark.asyncioasync def test_async_status_view_success():factory = AsyncRequestFactory()request = factory.get('/api/status/')response = await async_status_view(request)assert response.status_code == 200assert response.headers['content-type'] == 'application/json'
django
Breakdown
1
factory = AsyncRequestFactory()
Instantiates the specialized Django request factory for building asynchronous HTTP request mocks.
2
response = await async_status_view(request)
Directly awaits the async view execution with the generated mock request object.
3
assert response.status_code == 200
Verifies that the asynchronous view completed successfully and returned an HTTP 200 OK state.