Python django auth test

Question:

I want to write tests for my python django application. For tests, I need to get an API token, I tried it through APIClient with this code:

   client = APIClient()
   responce = json.loads(client.post('/api-token-auth/',data={"username":"root", "password":"root"}).content)

But in return I get

{'non_field_errors': ['Unable to login with provided credentials.']}

Through the "requests" library and Postman everything works with the same data

Asked By: koolaa12

||

Answers:

You probably haven’t populated your test database yet. Django defaults to creating a new database for model tests. (E.g: Authorization tests needs a user record to properly authorize it)

Here is a relevant line from the documentation why it does that:

Tests that require a database (namely, model tests) will not use your “real” (production) database. Separate, blank databases are created for the tests.

Running the setup function should help you kickstart what you want to do on your testcase:

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework.test import APITestCase

class AuthTestCase(APITestCase):
   def setUp(self):
      get_user_model().objects.create(username="root", "password": make_password("root"))
      return super().setUp()

   def test_login_not_authorized_succeeds(self):
       ....
    

Refer to this documentation for additional information: https://docs.djangoproject.com/en/4.1/topics/testing/overview/#writing-tests

Answered By: mutedeuphonies