This commit is contained in:
Marcelo Galigniana 2025-08-10 12:58:54 +01:00 committed by GitHub
commit 4c033781d2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
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 request.user = user
response = view(request) 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 ## Forcing CSRF validation

View File

@ -17,6 +17,7 @@ from rest_framework.response import Response
from rest_framework.test import ( from rest_framework.test import (
APIClient, APIRequestFactory, URLPatternsTestCase, force_authenticate APIClient, APIRequestFactory, URLPatternsTestCase, force_authenticate
) )
from rest_framework.views import APIView
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']) @api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
@ -294,6 +295,28 @@ class TestAPIRequestFactory(TestCase):
assert response.status_code == 403 assert response.status_code == 403
assert response.data == expected 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): def test_invalid_format(self):
""" """
Attempting to use a format that is not configured will raise an Attempting to use a format that is not configured will raise an