How to login a user during a unit test in Django REST Framework?

Viewed 6511

This is my DRF view:

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def check_user(request):
    user = request.user
    # use user object here
    return JSONResponse({})

And this is my unit test for said view:

class CheckUserViewTest(TestCase):

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

But I always get a 401 UNAUTHORIZED response from my view. I have logged in the user in my test. What am I doing wrong?

1 Answers

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)
Related