Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework APIRequestFactory request object has no attribute 'query_params'

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'>
like image 674
James Lin Avatar asked Feb 09 '15 23:02

James Lin


1 Answers

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')
like image 92
ZZY Avatar answered Sep 25 '22 06:09

ZZY