From 3b6e995f6362ae782a145eb2c7e02ee58d11fd98 Mon Sep 17 00:00:00 2001 From: Marcelo Galigniana Date: Thu, 11 Apr 2024 23:11:40 -0300 Subject: [PATCH] Add documentation about how to transform factory request to DRF request --- docs/api-guide/testing.md | 14 ++++++++++++++ tests/test_testing.py | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+) 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 pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy