Search code examples
pythondjangodjango-testingdjango-sessions

How do I modify the session in the Django test framework


My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session_key

I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:

I'd like to do this:

from django.contrib.sessions.models import Session
s = Session()
s.expire_date = '2010-12-05'
s.session_key = 'my_session_key'
s.save()
self.client.session = s
response = self.client.get('/myview/')

But I get the error:

AttributeError: can't set attribute

Thoughts on how to modify the client session before making get requests? I have seen this and it doesn't seem to work


Solution

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

    from django.test import TestCase
    from django.conf import settings
    from django.utils.importlib import import_module
    
    class 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...