Skip to content

Commit 98ca6a3

Browse files
committed
Add documentation about how to transform factory request to DRF request
1 parent 853969c commit 98ca6a3

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
@@ -105,6 +105,20 @@ This means that setting attributes directly on the request object may not always
105105
request.user = user
106106
response = view(request)
107107

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

110124
## Forcing CSRF validation

tests/test_testing.py

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

297+
def test_transform_factory_django_request_to_drf_request(self):
298+
from rest_framework.views import APIView
299+
300+
factory = APIRequestFactory()
301+
302+
class DummyView(APIView):
303+
...
304+
305+
request = factory.get('/', {'demo': 'test'})
306+
DRF_request = DummyView().initialize_request(request)
307+
assert DRF_request.query_params == {'demo': ['test']}
308+
assert not hasattr(DRF_request, 'accepted_media_type')
309+
310+
DummyView().initial(DRF_request)
311+
assert DRF_request.accepted_media_type == 'application/json'
312+
313+
request = factory.post('/', {'example': 'test'})
314+
DRF_request = DummyView().initialize_request(request)
315+
assert DRF_request.data.get('example') == 'test'
316+
297317
def test_invalid_format(self):
298318
"""
299319
Attempting to use a format that is not configured will raise an

0 commit comments

Comments
 (0)