首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么django.test.client.Client不让我保持登录状态

为什么django.test.client.Client不让我保持登录状态
EN

Stack Overflow用户
提问于 2010-05-21 07:27:47
回答 3查看 1.3K关注 0票数 4

我使用django.test.client.Client来测试当用户登录时是否显示一些文本。但是,客户端对象似乎并没有让我保持登录状态。

如果使用Firefox手动完成此测试,但在使用Client对象时不会通过此测试。

代码语言:javascript
运行
复制
class Test(TestCase):
    def test_view(self):
        user.set_password(password)
        user.save()

        client = self.client
        # I thought a more manual way would work, but no luck
        # client.post('/login', {'username':user.username, 'password':password})
        login_successful = client.login(username=user.username, password=password)
        # this assert passes  
        self.assertTrue(login_successful)

        response = client.get("/path", follow=True)
        #whether follow=True or not doesn't seem to work

        self.assertContains(response, "needle" )

当我打印响应时,它返回被以下内容隐藏的登录表单:

代码语言:javascript
运行
复制
{% if not request.user.is_authenticated %}
    ... form ...
{% endif %}

这在我运行ipython manage.py shell时得到了确认。

问题似乎是客户端对象没有保持会话的身份验证。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-05-21 21:05:55

FWIW,Django 1.2的更新(我之前运行的是1.1.1 )修复了这个问题。我不知道那里出了什么问题,考虑到我上一次运行测试套件是在大约两周前,它工作得很好。

票数 0
EN

Stack Overflow用户

发布于 2010-07-27 03:17:14

在重新测试一个已经工作了几个月却被遗忘的应用程序时,我碰巧遇到了这个问题。

解决方案(除了更新到Django1.2)是Patch #11821。简而言之,Python 2.6.5在Cookie模块中有一些错误修复,从而触发了测试客户端中的边缘案例错误。

票数 1
EN

Stack Overflow用户

发布于 2010-05-21 13:56:20

我使用RequestContext让登录的用户进入模板上下文。

代码语言:javascript
运行
复制
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

@login_required
def index(request):
   return render_to_response('page.html',
                             {},
                             context_instance=RequestContext(request))

在模板中

代码语言:javascript
运行
复制
{% if user.is_authenticated %} ... {{ user.username }} .. {% endif %}

当通过测试客户端时,这就像预期的那样工作(我不登录就不能进入这个页面,当我到达那里时,用户名就出现在response.content中)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2878602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档