Django: 测试页面是否已重定向到所需的 URL

在我的 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/')

接下来会发生什么?

53527 次浏览

您可以检查 response['Location']并查看它是否与预期的 URL 匹配。还可以检查状态代码是否为302。

姜戈1.4:

Https://docs.djangoproject.com/en/1.4/topics/testing/#django.test

姜戈2.0:

Https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test

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

断言响应返回一个 状态代码重定向状态,重定向到 预期 _ url(包括任何 走开数据) ,并且最终页面是用 Target _ status _ code接收的。

如果请求使用了 跟上参数,则 预期 _ urlTarget _ status _ code将是重定向链最后一点的 URL 和状态代码。

如果 获取 _ redirect _ response假的,则不会加载最后一页。由于测试客户端不能获取外部 URL,所以如果 预期 _ url不是 Django 应用程序的一部分,那么这一点特别有用。

在两个 URL 之间进行比较时,Scheme 得到了正确的处理。如果在重定向到的位置没有指定任何方案,则使用原始请求的方案。如果存在,预期 _ url中的方案就是用来进行比较的方案。

您还可以按照下面的重定向操作:

response = self.client.get('/myprofile/data/some_id/', follow=True)

它将反映浏览器中的用户体验,并对您希望在其中找到的内容作出断言,例如:

self.assertContains(response, "You must be logged in", status_code=401)

response['Location']在1.9中不存在,改用以下代码:

response = self.client.get('/myprofile/data/some_id/', follow=True)
last_url, status_code = response.redirect_chain[-1]
print(last_url)

可以使用 assertRedirects,例如:

response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')

Https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test

如果你需要获得网址重定向

如果 followTrue

你会得到网址

response.redirect_chain[-1]

如果 followFalse

response.url