Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 573
Babken Vardanyan Avatar asked Nov 08 '17 16:11

Babken Vardanyan


People also ask

How can use session in Django REST framework?

If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

How do I register a user in Django REST framework?

Open auth/urls.py and add register endpoint: we should send a POST request to API for checking register endpoint. You must add username, password, password2, email, first_name, last_name to body. If fields passed validations, new user detail will be returning.

What is Restapi in Django?

REST APIs are an industry-standard way for web services to send and receive data. They use HTTP request methods to facilitate the request-response cycle and typically transfer data using JSON, and more rarely - HTML, XML and other formats.


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)
like image 106
Babken Vardanyan Avatar answered Sep 18 '22 09:09

Babken Vardanyan