Django:测试页面是否已重定向到所需的URL [英] Django : Testing if the page has redirected to the desired url

查看:208
本文介绍了Django:测试页面是否已重定向到所需的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用中,我有一个认证系统。所以,如果我不登录并尝试访问某个个人资料的个人信息,我将被重定向到一个登录页面。

In my django app, I have an authentication system. So, If I do not log in and try to access some profile's personal info, I get redirected to a login page.

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

Now, I need to write a test case for this. The responses from the browsers I get is :

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

我如何写我的测试?这是我到目前为止:

How do I write my test ? This what I have so far:

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:

Django 1.4:

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

Django 1.7:

Django 1.7:

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


SimpleTestCase.assertRedirects(response,expe cted_url,status_code = 302,target_status_code = 200,host = None,msg_prefix ='',fetch_redirect_response = True)

status_code 重定向状态,重定向到 expected_url (包括任何 GET 数据),最后一页被 target_status_code

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.

如果您的请求使用跟随参数,则 expected_url target_status_code 将是重定向链的最终点的URL和状态代码。

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.

主机参数设置默认主机,如果 expected_url 不包括一个(例如的 /酒吧/ )。如果 expected_url 是包含主机的绝对URL(例如 http:// testhost / bar / ) ,主机参数将被忽略。请注意,测试客户端不支持提取外部URL,但如果您使用自定义HTTP主机进行测试,则该参数可能很有用(例如,使用客户端(HTTP_HOST =testhost)初始化测试客户端

The host argument sets a default host if expected_url doesn’t include one (e.g. "/bar/"). If expected_url is an absolute URL that includes a host (e.g. "http://testhost/bar/"), the host parameter will be ignored. Note that the test client doesn’t support fetching external URLs, but the parameter may be useful if you are testing with a custom HTTP host (for example, initializing the test client with Client(HTTP_HOST="testhost").

这篇关于Django:测试页面是否已重定向到所需的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆