Django Unit Test Authentication

ARAVIND ALLU
2 min readAug 20, 2019

--

In Django, when the developer is writing unit tests, he has to make API calls for every request. So for every request object, it consists of method-type, context, Authorization-header, etc.

In Django when we run the unit tests, we have to pass the Authorization header Token in order to execute the API calls. So the developer needs to send the token in the Authorization Header every time.

If the software project is integrated with the auth0 configuration for Authentication. Then they must keep in mind that to pass Token in the Authorization Header every time for unit tests for passing the unit tests without any failure messages.

Instead of passing Token every time, In Django rest-framework, the built-in package called User in Django models. Importing the User class and create one sample user of fields Username and Password.

Import the client class from the Django test package and make a login call with the Username and Password in the following way.

Login with Dummy Username and Password

So after the login call, return the object. And assign the object to some variable and make API calls. Here the login method makes the login request and makes the user logged in. It is the default login method in Django which consists of a username and password fields as arguments in order to log in. So the user never needs to pass the Token for authentication for API calls. It will make authentication internally and execute the unit tests successfully. Below is an example for API calls for Django Unit tests.

Calling the login function

API call for the post request is as follows:

Making POST API call with the client object

Here it makes the valid response and it doesn’t need any token for the authentication in auth0 integrated projects.

Reference Links: https://docs.djangoproject.com/en/2.2/topics/testing/tools/

--

--

No responses yet