How do I modify the session in the Django test framework

Riley picture Riley · Dec 15, 2010 · Viewed 15.1k times · Source

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

Answer

luc picture luc · Dec 15, 2010

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.session
s.update({
    "expire_date": '2010-12-05',
    "session_key": 'my_session_key',
})
s.save()
response = self.client.get('/myview/')