I am trying to decide whether I should use Django's Client or RequestFactory to test my views.
I am creating my server using DjangoRESTFramework and it's really simple, so far:
class SimpleModelList(generics.ListCreateAPIView):
"""
Retrieve list of all route_areas or create a new one.
"""
queryset = SimpleModel.objects.all()
serializer_class = SimpleModelSerializer
filter_backends = (IsOwnerFilterBackend,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
What are the differences between testing with Django's Client and RequestFactory and which approach is more suited for testing a REST server (if there is any difference besides liking one better)?
Should I create tests with both so as to provide a better coverage for my system?
RequestFactoryandClienthave some very different use-cases. To put it in a single sentence:RequestFactoryreturns arequest, whileClientreturns aresponse.The
RequestFactorydoes what it says - it's a factory to createrequestobjects. Nothing more, nothing less.The
Clientis used to fake a complete request-response cycle. It will create arequestobject, which it then passes through a WSGI handler. This handler resolves the url, calls the appropriate middleware, and runs the view. It then returns the response object. It has the added benefit that it gathers a lot of extra data on theresponseobject that is extremely useful for testing.The
RequestFactorydoesn't actually touch any of your code, but therequestobject can be used to test parts of your code that require a validrequest. TheClientruns your views, so in order to test your views, you need to use theClientand inspect the response. Be sure to check out the documentation on theClient.