Add documentation about how to transform factory request to DRF request

This commit is contained in:
Marcelo Galigniana 2024-04-11 23:11:40 -03:00
parent 853969c69c
commit 3b6e995f63
2 changed files with 37 additions and 0 deletions

View File

@ -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 frameworks 'Request' object, youll 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

View File

@ -17,6 +17,7 @@ from rest_framework.response import Response
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 @@ class TestAPIRequestFactory(TestCase):
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