Skip to content

Commit fab9b80

Browse files
committed
Add documentation about how to transform factory request to DRF request
1 parent 63063da commit fab9b80

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

docs/api-guide/testing.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,20 @@ This means that setting attributes directly on the request object may not always
102102
request.user = user
103103
response = view(request)
104104

105+
In case you want to test the request having a REST famework's `Request` you have to transform it by-hand before:
106+
107+
class DummyView(APIView):
108+
...
109+
110+
factory = APIRequestFactory()
111+
request = factory.get('/', {'demo': 'test'})
112+
DRF_request = DummyView().initialize_request(request)
113+
assert DRF_request.query_params == {'demo': ['test']}
114+
115+
request = factory.post('/', {'example': 'test'})
116+
DRF_request = DummyView().initialize_request(request)
117+
assert DRF_request.data.get('example') == 'test'
118+
105119
---
106120

107121
## Forcing CSRF validation

tests/test_testing.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,26 @@ def test_explicitly_enforce_csrf_checks(self):
263263
assert response.status_code == 403
264264
assert response.data == expected
265265

266+
def test_transform_factory_django_request_to_drf_request(self):
267+
from rest_framework.views import APIView
268+
269+
factory = APIRequestFactory()
270+
271+
class DummyView(APIView):
272+
...
273+
274+
request = factory.get('/', {'demo': 'test'})
275+
DRF_request = DummyView().initialize_request(request)
276+
assert DRF_request.query_params == {'demo': ['test']}
277+
assert not hasattr(DRF_request, 'accepted_media_type')
278+
279+
DummyView().initial(DRF_request)
280+
assert DRF_request.accepted_media_type == 'application/json'
281+
282+
request = factory.post('/', {'example': 'test'})
283+
DRF_request = DummyView().initialize_request(request)
284+
assert DRF_request.data.get('example') == 'test'
285+
266286
def test_invalid_format(self):
267287
"""
268288
Attempting to use a format that is not configured will raise an

0 commit comments

Comments
 (0)