python - 为什么 django.test.client.Client 不让我登录

标签 python django unit-testing testing automated-tests

我正在使用 django.test.client.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 时得到确认。

问题似乎是客户端对象没有对 session 进行身份验证。

最佳答案

我在重新测试一个已经运行了几个月却被遗忘的应用程序时遇到了这种情况。

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

关于python - 为什么 django.test.client.Client 不让我登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878602/

相关文章:

java - 使用 hamcrest 匹配器进行 jUnit 测试 - 如何测试集合的大小。

python - 在 Python 中列出目录内容

python - 使用 GAE + ndb 进行配对

django - RequestFactory & reverse with pk(必须用对象 pk 或 slug 调用)

Django:表单验证:接受一个字段的多个值

unit-testing - 如何对包含 dynamoDB 查询的 lambda 函数进行单元测试

php - 您可以在回调中使用 $this 来获取 phpunit 中模拟类的 protected 属性吗?

javascript - Python Mechanize : Web Forms with Javascript

python - 如何在 Matplotlib 中使用带有形状内文本的自定义标记?

django - 让 django url 标签静默失败