Lets say I have this APIView
class Dummy(APIView):
def get(self, request):
return Response(data=request.query_params.get('uuid'))
To test it, I need to create a request object to pass into the get
function
def test_dummy(self):
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
request = factory.get('/?uuid=abcd')
DummyView().get(request)
It complains about AttributeError: 'WSGIRequest' object has no attribute 'query_params'
Having a closer look, the factory creates a WSGIRequest
instance instead of a DRF version <class 'rest_framework.request.Request'>
.
>>> from rest_framework.test import APIRequestFactory
>>> factory = APIRequestFactory()
>>> request = factory.get('/')
>>> request.__class__
<class 'django.core.handlers.wsgi.WSGIRequest'>
Refer to Tom's solution, DummyView()(request)
will raise error:
TypeError: 'DummyView' object is not callable
Instead, should use as_view
just like what you do in urls.py
:
DummyView.as_view()(request)
DRF's as_view
uses method initialize_request
to convert Django Request object to DRF version. You can try with:
from rest_framework.views import APIView
APIView().initialize_request(request)
>>> <rest_framework.request.Request object at 0xad9850c>
You can also use APIClient to run test. It also tests URL dispatching.
from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With