Using SessionAuthentication With Tastypie tests for Django

Today I have been studying more deeply how to create good tests with Tastypie's
alpha version documentation
.

It was easy to start if you knew about TestCase and django test Client, but still
Tastypie documentation has a lot of blanks in this part.

I was using SessionAuthentication to authenticate my resources and it uses Django sessions
in background, so it had to be easy to test it with the ResourceTestCase. It wasn't as easy as it seemed
and we needed to check the code to understand how to do it.

In a real Django app we could use login method from django.test.client.Client, and I thought
tastypie.test.TestApiClient could be inheriting from it, but because you can have different kinds of authentication it wasn't the right choice for the Tastypie api test client architecture.

If we read TestApiClient's __init__ we can see it has a client attribute,
instantiating from django.client.Client.

class TestApiClient(object):
    def __init__(self, serializer=None):
        """
        Sets up a fresh ``TestApiClient`` instance.

        If you are employing a custom serializer, you can pass the class to the
        ``serializer=`` kwarg.
        """
        self.client = Client()
        self.serializer = serializer

        if not self.serializer:
            self.serializer = Serializer()

With this in mind and following the same idea we could just do this in our tests.

from tastypie.test import ResourceTestCase, TestApiClient


class ExampleResourceTest(ResourceTestCase):
    def setUp(self):
        self.api_client = TestApiClient()
        self.get_credentials()
        self.example = {'title': 'My Data'}

    def get_credentials(self):
        result = self.api_client.client.login(username='myuser',
                                              password='secret')
        return result

    def test_post_project(self):
        self.assertHttpCreated(self.api_client.post('/api/v1/example/',
                                                    format='json',
                                                    data=self.example))

Now we can build authenticated requests for tests using SessionAuthentication in Tastypie.

Easy after all. :-)

Javier Aguirre

Read more posts by this author.

comments powered by Disqus