在设置一个档案索引视图 https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-date-based/#django.views.generic.dates.ArchiveIndexView在 Django 中,我可以通过自己导航到页面来成功显示模型中的项目列表。
当要在 pytest 中编写测试以验证导航到页面“checklist_GTD/archive/”是否成功时,测试失败并显示消息:
> assert response.status_code == 200
E assert 301 == 200
E + where 301 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/checklist_GTD/archive/">.status_code
test_archive.py:4: AssertionError
我知道有一种方法可以按照请求获取最终的 status_code。有人可以帮助我如何在 pytest-django 中完成此操作,类似于这个问题 https://stackoverflow.com/questions/14951356/django-testing-if-the-page-has-redirected-to-the-desired-url? The pytest-django 的文档 https://pytest-django.readthedocs.io/en/latest/没有任何关于重定向的内容。谢谢。
pytest-django https://pytest-django.readthedocs.io/en/latest/提供未经身份验证的client
和一个已登录的admin_client
作为固定装置。确实简化了这类事情。假设您目前正在使用admin_client
因为您只想尽可能轻松地测试重定向,而无需手动登录:
def test_something(admin_client):
response = admin_client.get(url, follow=True)
assert response.status_code == 200
如果您想以标准用户登录:
def test_something(client):
# Create user here, then:
client.login(username="foo", password="bar")
response = client.get(url, follow=True)
assert response.status_code == 200
通过使用follow=True
在其中任何一个中,response.status_code
将等于重定向后页面的返回码,而不是对原始 URL 的访问。因此,它应该解析为 200,而不是 301。
我认为它没有记录在 pytest-django 中,因为该选项是从 Django 测试客户端继承的(它是子类)发出请求 https://docs.djangoproject.com/en/2.0/topics/testing/tools/#making-requests).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)