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?
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.
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.
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.
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