我使用django.test.client.Client来测试当用户登录时是否显示一些文本。但是,客户端对象似乎并没有让我保持登录状态。
如果使用Firefox手动完成此测试,但在使用Client对象时不会通过此测试。
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时得到了确认。
问题似乎是客户端对象没有保持会话的身份验证。
发布于 2010-05-21 21:05:55
FWIW,Django 1.2的更新(我之前运行的是1.1.1 )修复了这个问题。我不知道那里出了什么问题,考虑到我上一次运行测试套件是在大约两周前,它工作得很好。
发布于 2010-07-27 03:17:14
在重新测试一个已经工作了几个月却被遗忘的应用程序时,我碰巧遇到了这个问题。
解决方案(除了更新到Django1.2)是Patch #11821。简而言之,Python 2.6.5在Cookie模块中有一些错误修复,从而触发了测试客户端中的边缘案例错误。
发布于 2010-05-21 13:56:20
我使用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中)。
https://stackoverflow.com/questions/2878602
复制相似问题