Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
Riley Avatar asked Dec 15 '10 19:12

Riley


People also ask

How are sessions maintained in Django?

Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).

How would you describe session in context of Django framework?

A session is a mechanism to store information on the server side during the interaction with the web application. In Django, by default session stores in the database and also allows file-based and cache based sessions. It is implemented via a piece of middleware and can be enabled by using the following code.


1 Answers

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/') 
like image 190
luc Avatar answered Sep 28 '22 04:09

luc