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 63063da082
commit fab9b80738
2 changed files with 34 additions and 0 deletions

View File

@ -102,6 +102,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)
In case you want to test the request having a REST famework's `Request` you have to transform it by-hand before:
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

@ -263,6 +263,26 @@ 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):
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): 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