2010-05-20 39 views
4

我正在使用django.test.client.Client来测试当用户登录时是否显示一些文本。但是,我的客户端对象不会' t似乎让我登录。为什么django.test.client.Client不让我登录

该测试通过,如果手动完成与Firefox,但不完成与客户端对象。

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") 

当我打印响应它返回被隐藏的登录表单:

{% if not request.user.is_authenticated %} 
    ... form ... 
{% endif %} 

当我运行ipython manage.py shell这证实。

问题似乎是客户端对象没有保持会话认证。

+0

看着这个我不确定问题在哪里。你能明确表明客户端正在注销吗?如果客户端已经登录,那么'client.session!= {}'您可以使用它来显示客户端在何处登出。 – tdedecko 2010-05-21 04:13:42

+0

这肯定没有帮助你,对不起,但我从今天起就有同样的问题。我不知道改变了什么。 – Fred 2010-05-21 12:47:13

回答

0

FWIW,Django 1.2的更新(我以前运行1.1.1)修复它。我不知道那里发生了什么,考虑到我大约两个星期前上次运行该测试套件时,它运行得很好。

+0

所以你遇到了同样的问题? – Mystic 2010-05-21 14:03:46

+0

我也升级到了Django 1.2,问题就消失了。谢谢! – Mystic 2010-05-21 16:46:08

0

我使用RequestContext将登录用户置入模板上下文中。

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)) 

,并在模板

{% if user.is_authenticated %} ... {{ user.username }} .. {% endif %} 

可正常工作(我不明白这个页面无需登录,当我到达那里时,用户名中response.content存在)驱动时通过测试客户端。

+0

我不认为这是问题。如果我没有正确导入上下文,那么它不适用于Firefox以及客户端。问题是它在Firefox中工作,但与客户端无关,所以我无法测试功能。 – Mystic 2010-05-21 12:41:24

+0

您使用request.user.is_authenticated(而不是user.is_authenticated)表示您没有使用上下文。如果它不能通过浏览器为你工作,我会怀疑你没有将'{'request':request}'传递给你的模板。 – 2010-05-21 14:21:58

1

刚发生在我重新测试一直在工作并被遗忘了几个月的应用程序时。

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

+0

很好找!这正是我的问题。 – user27478 2010-11-12 20:57:15

相关问题