django - django_webtest 中的用户身份验证

标签 django django-testing

我的模板中有以下代码:

<div class="account">
{% if request.user.is_authenticated %}
    <a href="{% url settings %}"
       class="iconed username">{{ request.user.username }}</a>
    &nbsp;|&nbsp;
    <a href="{% url logout %}?next={{ request.path }}"
       class="iconed logout">{% trans "Logout" %}</a>
{% else %}
    <a href="{% url login %}?next={{ request.path }}" class="iconed login">{% trans "Login" %}</a>
    &nbsp;|&nbsp;
    <a href="{% url sign_up %}?next={{ request.path }}"
       class="iconed sign-up">{% trans "Sign up" %}</a>
{% endif %}
</div>

如您所见,它显示不同的链接取决于用户是否登录。如果我手动测试它可以正常工作,但是当我尝试使用以下代码对其进行测试时:
def test_home_logged_in(self):
    if self.client.login(username='Test', password='secret'):
        home = self.app.get('/')
        self.assertOK(home)
        self.assertContains(home, '/settings/')
        self.assertContains(home, '/logout/')
    else:
        self.fail("Couldn't log in.")

login() 返回 True,但测试失败。我为 home 对象调用了 showbrowser() 并看到返回的页面看起来像匿名用户的页面 - 除了设置和注销的链接之外,它还包含注册和登录的链接。

在模板中使用 *request.user.is_authenticated* 来检查用户是否通过身份验证是否正确?为什么模板看不到用户是从 注册的测试 ?

谢谢!

最佳答案

根据您的其他问题,我猜您正在使用 django_webtest .如果是这样,您可以向请求指定您希望以哪个用户身份登录。因此,要以用户“Test”身份访问主页,您需要执行以下操作:

home = self.app.get('/', user='Test')

关于django - django_webtest 中的用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9242003/

相关文章:

python - 使用 Django 为抽象基类设置外键

python - “模块”对象没有属性 'main' -- Django

jquery - 使用jquery列出django相关的下拉值

python - 使用线程模块时,Django 在完成测试后不退出

django-testing - HttpResponseRedirect' 对象没有属性 'client'

python - Django test.Client 已登录但在 View 中作为 AnonymousUser 传递

django - 测试 URL 是否与正确的 View 匹配

python - 将 json 文件导入 Django 模型

python - 在 virtualenv 中运行测试时 Django MySQL 错误

Django get_or_create 与捕获 IntegrityError