[Django]-How to write Django Unit Test for Authentication Protected REST APIs?

3👍

After following @henriquesalvaro (see comments) sage advice I have updated my code to this:

from rest_framework.test import APIClient,APITestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

class RemoteAuthenticatedTest(APITestCase):
    client_class = APIClient

    def setUp(self):
        self.username = 'mister_neutron'
        self.user = User.objects.create_user(username='mister_neutron',
                                             email='mister_neutron@example.com',
                                             password='F4kePaSs0d')
        Token.objects.create(user=self.user)
        super(RemoteAuthenticatedTest, self).setUp() 

And I updated my test case to this:

class InfoViewTestCase(RemoteAuthenticatedTest):
    def create_info_record(self):
        from random import randint
        blade = 'test-blade-host-name-%s' % (randint(0, 100))
        breachs = randint(0,100)
        dimm = 'test dimm slot %s' % (randint(0,100))
        url = reverse('info:info_creat')
        data = {
            'blade_hostname': blade,
            'breach_count': breachs,
            'dimm_slot': dimm,
        }
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.user.auth_token.key)
        response = self.client.post(url, 
                                    data, 
                                    format='json', 
                                    REMOTE_USER=self.username)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Info.objects.count(), 1)
        self.assertEqual(Info.objects.get().blade_hostname, blade)

And now my unit test passes.

Leave a comment