gpt4 book ai didi

python - Django : Testing if the page has redirected to the desired url

转载 作者:IT老高 更新时间:2023-10-28 20:23:27 26 4
gpt4 key购买 nike

在我的 django 应用程序中,我有一个身份验证系统。因此,如果我没有登录并尝试访问某些个人资料的个人信息,我会被重定向到登录页面。

现在,我需要为此编写一个测试用例。我得到的浏览器的响应是:

GET /myprofile/data/some_id/ HTTP/1.1 302 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 301 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 200 6533

如何编写测试?这是我目前所拥有的:

self.client.login(user="user", password="passwd")
response = self.client.get('/myprofile/data/some_id/')
self.assertEqual(response.status,200)
self.client.logout()
response = self.client.get('/myprofile/data/some_id/')

接下来会发生什么?

最佳答案

Django 1.4:

https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TestCase.assertRedirects

Django 2.0:

https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects

SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)

Asserts that the response returned a status_code redirect status, redirected to expected_url (including any GET data), and that the final page was received with target_status_code.

If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain.

If fetch_redirect_response is False, the final page won’t be loaded. Since the test client can’t fetch external URLs, this is particularly useful if expected_url isn’t part of your Django app.

Scheme is handled correctly when making comparisons between two URLs. If there isn’t any scheme specified in the location where we are redirected to, the original request’s scheme is used. If present, the scheme in expected_url is the one used to make the comparisons to.

关于python - Django : Testing if the page has redirected to the desired url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14951356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com