如何在Django测试框架中修改会话 [英] How do I modify the session in the Django test framework
问题描述
我的网站允许个人在没有登录的情况下通过创建基于当前session_key的用户来贡献内容
我想为我设置一个测试查看,但似乎无法修改request.session:
我想这样做:
$ b导入会话
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 /')
但是我收到错误:
code> AttributeError:无法设置属性
关于如何修改客户端会话的想法获得请求?
我已经看到这个,它似乎不是工作
这是我做的(灵感来自于 http://blog.mediaonfire.com/?p=36 )。
<$ p从django.test导入TestCase
从django.conf导入设置
从django.utils.importlib导入import_module
类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
之后,您可以创建以下测试:
类BlahTestCase(SessionTestCase):
pre>
def test_blah_with_session(self):
session = self.session
session ['operator'] ='Jimmy'
session.save()
等...
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
解决方案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...
这篇关于如何在Django测试框架中修改会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!