How to deal with persistent sessions in Django unit tests
Unit testing Django views/classes that require certain session data is possible in Django, but it requires a few tricks to make it work well. Three key issues that often come up:
Session needs to persist across different tests (e.g. in a shopping cart environment) The request object requires certain attributes to be set (e.g. ‘META’) The session object requires additional session parameters to be set.
The following code sample provides a solution to this problem by creating a mock HttpRequest object.
from django.test import TestCase
from django.utils.importlib import import_module
from django.http import HttpRequest
from django.conf import settings
class SampleTest(TestCase):
def setUp(self):
# Create mock request object with session key
engine = import_module(settings.SESSION_ENGINE)
request = HttpRequest()
request.session = engine.SessionStore()
request.session['somekey'] = 'somevalue'
request.session.session_key = 'session_key_from_model_object?'