Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing rest-framework: APIRequestFactory vs APIClient

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

like image 907
Robin van Leeuwen Avatar asked Aug 21 '15 09:08

Robin van Leeuwen


People also ask

Which authentication is best in Django REST framework?

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.

What is Apirequestfactory?

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.

Which statement is applicable for CSRF validation in REST framework?

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() .


1 Answers

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.

like image 88
arie Avatar answered Oct 13 '22 03:10

arie