Skip to main content
 首页 » 编程设计

python之如何在 Django 测试用例中设置 cookie

2025年05月04日24zhujiabin

我正在努力解决这个问题,当我正常运行我的应用程序时, session 可以正常工作,但我无法弄清楚如何在我的测试用例中设置 session 中的数据。

文档说在测试用例中,您必须在发出请求之前保存 session 以应用更改。 https://docs.djangoproject.com/en/1.2/topics/testing/#persistent-state

例如

from django.test import TestCase 
 
class TestLogin(TestCase): 
 
    def test_processuser(self): 
        redirect = '/processuser/' 
        session = self.client.session 
        session["id"] = '1234' 
        session.save() 
        response = self.client.get(redirect) 

然而,从 self.client.session 返回的 session 对象只是一个普通的 python 字典?

深入研究 Client.session 调用的代码是这样的:

def _session(self): 
    """ 
    Obtains the current session variables. 
    """ 
    if 'django.contrib.sessions' in settings.INSTALLED_APPS: 
        engine = import_module(settings.SESSION_ENGINE) 
        cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) 
        if cookie: 
            return engine.SessionStore(cookie.value) 
    return {} 
session = property(_session) 

cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) 返回 None 所以它只返回一个字典而不是 session 存储。

看起来我必须在保存 session 之前在测试客户端中做一些更多的准备工作?在这方面没有太多经验,我们将不胜感激。

Django 1.2.5 Python 2.6.5

干杯,

阿西姆。

请您参考如下方法:

编辑:这个答案现在已经过时了;至少从 Django 1.7 开始,您可以直接在测试客户端上设置 cookie。

参见例如this answer to this question或 the comments on this answer to another, similar, question .

旧的过时答案如下...


为真正确实需要设置 cookie 的人添加此功能,例如因为他们需要做一些 Django 授权机制没有涵盖的事情...

您不能直接在 TestClient 对象上设置 cookie,但是如果您使用 RequestFactory类你可以做到。所以而不是(说):

response = Client().post('/foo') 

你这样做:

request = RequestFactory().post('/foo') 
request.COOKIES['blah'] = 'hello' 
response = foo_view(request) 

其中 foo_view 是对应于“/foo”路径的 View ,即您要测试的 View 。

HTH 某人。