Django, Testing, and Sessions

Published 2011-01-07

Working on my new site, I wanted to test a view. I’m new to python and the django, so I’m incrementally increasing my tool usage. Currently I’m sticking to unittest. I needed to set a session var, but the docs are a little light — so here’s what I did:

import unittest

from django.conf import settings
from django.test.client import Client

class Test(unittest.TestCase):
    def setUp(self):
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = importlib.import_module('django.contrib.sessions.backends.file')
        store = engine.SessionStore()
        store.save()

        self.client = Client()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

    def tearDown(self):
        store = self.session
        os.unlink(store._key_to_file())

    def test_exception_no_next_stage(self):
        session = self.session
        session['foo'] = 'bar'
        session.save()

        response = self.client.get('/')

        self.assertEquals(...)

Your view for ‘/’ should see the session variable foo set to ‘bar’.

If you want to read a value from session in your unit test after you’ve got the response, then you need to load the data from the session:

session_data = session.load()
self.assertEqual(session_data['foo'], 'baz')

Clearly this is a mess and needs more research.