Testing django-rest-framework-API with TokenAuthentication

Wednesday, June 05, 2013

I’ve been struggeling a bit using the Django-unittests to test my RESTful interface. In this post I assume, that django-rest-framework is already integrated in your Django-project and the token authentication is activated here’s how).

To give you some context: In my project exits a model called Bookmark and a simple ModelSerializer called BookmarkSerializer. What I want is to test the GET-functionalty on that BookmarkSerializer while token authentication is active. To achieve that, you have to create a user in the TestCase-class and get his token:

tests.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from rest_framework.reverse import reverse
from rest_framework.authtoken.models import Token
import json

class ApiTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('foo', 'foo@bar.de', 'bar')
        self.token = Token.objects.get(user=self.user).key
        self.c = Client()

Now I want to connect to my REST-API, so I added a test-method to the ApiTest-class. The tricky part was setting the right header. The HTTP-Request is implemented using Django’s client.get()-function.

1
2
3
4
    def test_authorization(self):
        header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)} 
        response = self.client.get(reverse('bookmark-list'), {}, **header)
        self.assertEqual(response.status_code, 200, "REST token-auth failed")

Versions: Django 1.5 and django-rest-framework 2.3.6