diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 261df80f27..d8fe08082b 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -102,6 +102,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 196319a29e..f56d189065 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -263,6 +263,26 @@ 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): + from rest_framework.views import APIView + + factory = APIRequestFactory() + + class DummyView(APIView): + ... + + request = factory.get('/', {'demo': 'test'}) + DRF_request = DummyView().initialize_request(request) + assert DRF_request.query_params == {'demo': ['test']} + assert not hasattr(DRF_request, 'accepted_media_type') + + 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
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: