Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Django rest framework requests?

I have a Django-rest-framework API, that I want to unit test. More specifically, I want to unit test some data validation methods separately. These data validation methods will get a request as their parameter, like so:

def validate(request)

In order to test it separately, I need a way to create requests. In django-rest-framework, there is APIRequestFactory, that can be used in creating requests. The main problem is, that the APIRequestFactory will not create same request that the django-rest-framework uses. Instead, it will create regular django requests as stated by the site:

Note: When using APIRequestFactory, the object that is returned is Django's standard HttpRequest, and not REST framework's Request object, which is only generated once the view is called.

But because those validation methods use the django-rest-frameworks request, I cannot unit test those by using the APIRequestFactory. Is there any way to unit test separately those, or should I just use the APIClient, and try to test the whole APIView? I wouldn't want to do that, because then it will not be a pure unit test. And with the APIClient, I can only get responses, not requests. Why is there not an APIRequestFactory for the django-rest-framework requests? I mean, if those are the ones used in django-rest, then why the request factory doesn't generate those instead?

like image 906
Ville Miekk-oja Avatar asked Mar 28 '15 16:03

Ville Miekk-oja


People also ask

Can you unit test a REST API?

REST APIs are usually rigorously tested during integration testing. However, a good developer should test REST endpoints even before integration in their Unit Tests, since they are a vital part of the code since it's the sole access point of every entity wanting to make use of the services in the server.

Does Django use Unittest?

Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.


1 Answers

Was able bypass this by not sending the request to the validation method, but instead the request.DATA. This way the validation methods got independent on request, but only rely on the data sent to them.

like image 147
Ville Miekk-oja Avatar answered Oct 12 '22 23:10

Ville Miekk-oja