Ril*_*ley 29 python django django-testing django-sessions
我的网站允许个人在没有登录的情况下通过基于当前session_key创建用户来贡献内容
我想为我的视图设置一个测试,但似乎无法修改request.session:
我想这样做:
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/')
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)
关于如何在获取请求之前修改客户端会话的想法?我已经看到了这个,它似乎并没有工作
luc*_*luc 51
django测试框架的客户端对象使触摸会话成为可能.请查看http://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.client.Client.session了解详情
小心 : 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)
我认为下面这样的事情应该有效
s = self.client.session
s.update({
"expire_date": '2010-12-05',
"session_key": 'my_session_key',
})
s.save()
response = self.client.get('/myview/')
Run Code Online (Sandbox Code Playgroud)
Car*_*bés 32
这就是我做到的方式(灵感来自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
Run Code Online (Sandbox Code Playgroud)
之后,您可以创建测试:
class BlahTestCase(SessionTestCase):
def test_blah_with_session(self):
session = self.session
session['operator'] = 'Jimmy'
session.save()
Run Code Online (Sandbox Code Playgroud)
等等...
tym*_*ymm 11
正如安德鲁·奥斯汀已经提到的那样,由于这个错误它不起作用:https://code.djangoproject.com/ticket/11475
你可以做的是:
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
class 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()
Run Code Online (Sandbox Code Playgroud)
使用User.objects.create_user()和self.client.login()创建并登录用户后,如上面的代码所示,会话应该有效.
| 归档时间: |
|
| 查看次数: |
12976 次 |
| 最近记录: |