diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index ed585faf24..b74d236280 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -105,6 +105,20 @@ This means that setting attributes directly on the request object may not always request.user = user response = view(request) +If you want to test a request involving the REST framework’s 'Request' object, you’ll need to manually transform it first: + + class DummyView(APIView): + ... + + factory = APIRequestFactory() + request = factory.get('/', {'demo': 'test'}) + drf_request = DummyView().initialize_request(request) + assert drf_request.query_params == {'demo': ['test']} + + request = factory.post('/', {'example': 'test'}) + drf_request = DummyView().initialize_request(request) + assert drf_request.data.get('example') == 'test' + --- ## Forcing CSRF validation diff --git a/tests/test_testing.py b/tests/test_testing.py index 26a6e8ffb9..fed42342a3 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -17,6 +17,7 @@ from rest_framework.test import ( APIClient, APIRequestFactory, URLPatternsTestCase, force_authenticate ) +from rest_framework.views import APIView @api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']) @@ -294,6 +295,28 @@ def test_explicitly_enforce_csrf_checks(self): assert response.status_code == 403 assert response.data == expected + def test_transform_factory_django_request_to_drf_request(self): + """ + ref: GH-3608, GH-4440 & GH-6488. + """ + + factory = APIRequestFactory() + + class DummyView(APIView): # Your custom view. + ... + + request = factory.get('/', {'demo': 'test'}) + drf_request = DummyView().initialize_request(request) + assert drf_request.query_params == {'demo': ['test']} + + assert hasattr(drf_request, 'accepted_media_type') is False + DummyView().initial(drf_request) + assert drf_request.accepted_media_type == 'application/json' + + request = factory.post('/', {'example': 'test'}) + drf_request = DummyView().initialize_request(request) + assert drf_request.data.get('example') == 'test' + def test_invalid_format(self): """ Attempting to use a format that is not configured will raise an