[Fixed]-How to login a user during a unit test in Django REST Framework?

18👍

Since you are using Django REST Framework you have to also use DRF’s test client called APIClient instead of Django’s test client. This happens automagically if you inherit from DRF’s APITestCase instead of Django’s TestCase.

Complete example:

class CheckUserViewTest(APITestCase):

    def test_check_user(self):
        user = User.objects.create_user('username', 'Pas$w0rd')
        self.assertTrue(self.client.login(username='username', password='Pas$w0rd'))
        response = self.client.get(reverse('check_user'))
        self.assertEqual(response.status_code, httplib.OK)

An alternative is to use force_authenticate:

class CheckUserViewTest(APITestCase):

    def test_check_user(self):
        user = User.objects.create_user('username', 'Pas$w0rd')
        self.client.force_authenticate(user)
        response = self.client.get(reverse('check_user'))
        self.assertEqual(response.status_code, httplib.OK)

0👍

If your are using djangorestframework you must have to use APITestCase here.

An complete example is just below

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password


class TestLogin(APITestCase):
    '''
    This will handle login testcases
    '''

    def setUp(self):
        self.url = reverse('check_user')
    

    def test_login(self):
        '''
        This will test successfull login
        '''
        data = {
            "full_name" : "full name",
            'email' : "email@gmail.com",
            'password' : "password"
            }

        User.objects.create(
            full_name = data.get('full_name'),
            email = data.get('email'),
            password = make_password(data.get('password'))
            )
        
        response = self.client.get(self.url, data=data)
        self.assertEqual(response.status_code,status.HTTP_200_OK)

Leave a comment