Being new to testing i'm looking to test my API in Django (Django-rest-framework).
I'm setting up tests for my views, that is my API endpoints. Now looking over the documentation i can use an APIRequestFactory or a APIClient. Both seem to do the same thing.
What is the difference between those two, and why/when should i use one or the other??
JSON Web Token Authentication Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app.
A RequestFactory allows you to test you views in a very isolated manner. You can build a request and test your view without the need to setup your urls or care about things happening in middlewares etc. So this is closer to a typical unit test. That said, both types of tests are useful.
As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login() .
If you look at the tools and helpers for testing "standard" views in Django you will find something very analogue, the TestClient
and a RequestFactory
.
The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view. This means you can test a view function the same way as you would test any other function – as a black box, with exactly known inputs, testing for specific outputs.
The TestClient
lets you interact with your site from the perspective of a user browsing your site (... though testing Javascript is yet another story). Many things come into play when testing your site like this (Sessions, Middlewares, URL-Routing, etc.). So these are typically more integrational tests that mimic real world interaction with your site or API.
A RequestFactory
allows you to test you views in a very isolated manner. You can build a request and test your view without the need to setup your urls or care about things happening in middlewares etc. So this is closer to a typical unit test.
That said, both types of tests are useful. To get a general feeling if your API works as expected I would probably start using the APIClient and use RequestFactories when it comes to more complex views. But the right mix depends a lot on your concrete application.
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