Search code examples
djangodjango-rest-frameworkdjango-testingdjango-rest-auth

auth_token for unittest in Django


I've been trying to test my login system using the following code

from django.test import TestCase, Client
from rest_framework.test import force_authenticate
  
class DeckTestCase(TestCase):
 @classmethod
 def setUp(cls):
    test_user1 = User.objects.create(first_name='tester',username='test1', password='123', email='[email protected]')

 def test_if_logged(self):
    factory = Client()
    user = User.objects.get(username='teste1')
    request = factory.post('/login', {'username': 'test1', 'password': '123'}, format='json')
    force_authenticate(request,user=user)
    print(request)

But i keep getting this response, which is 401 (Unauthorized)

<Response status_code=401, "application/json">

Can someone help me? I don't know how do I send an auth_token with test_if_logged


Solution

  • You should use .create_user(…) [Django-doc] to create a user, this will set a hashed password for that user:

    @classmethod
    def setUp(cls):
        test_user1 = User.objects.create_user(
            first_name='tester',
            username='test1',
            password='123',
            email='[email protected]'
        )