How do I modify the session in the Django test framework How do I modify the session in the Django test framework python python

How do I modify the session in the Django test framework


The client object of the django testing framework makes possible to touch the session. Look at http://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.client.Client.session for details

Be careful : To modify the session and then save it, it must be stored in a variable first (because a new SessionStore is created every time this property is accessed)

I think something like this below should work

s = self.client.sessions.update({    "expire_date": '2010-12-05',    "session_key": 'my_session_key',})s.save()response = self.client.get('/myview/')


This is how I did it (inspired by a solution in http://blog.mediaonfire.com/?p=36).

from django.test import TestCasefrom django.conf import settingsfrom django.utils.importlib import import_moduleclass SessionTestCase(TestCase):    def setUp(self):        # http://code.djangoproject.com/ticket/10899        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'        engine = import_module(settings.SESSION_ENGINE)        store = engine.SessionStore()        store.save()        self.session = store        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

After that, you may create your tests as:

class BlahTestCase(SessionTestCase):    def test_blah_with_session(self):        session = self.session        session['operator'] = 'Jimmy'        session.save()

etc...


As Andrew Austin already mentioned, it doesn't work because of this bug: https://code.djangoproject.com/ticket/11475

What you can do though is this:

from django.test import TestCasefrom django.test.client import Clientfrom django.contrib.auth.models import Userclass SessionTestCase(TestCase):    def setUp(self):        self.client = Client()        User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')        self.client.login(username='john', password='johnpassword')    def test_something_with_sessions(self):        session = self.client.session        session['key'] = 'value'        session.save()

After creating and logging in a user with User.objects.create_user() and self.client.login(), as in the code above, sessions should work.