Django: 测试页面是否已重定向到目标网址

83 投票
5 回答
57707 浏览
提问于 2025-04-17 16:20

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

接下来我可能需要做什么呢?

5 个回答

39

你可以查看 response['Location'],看看它是否和你预期的网址一致。同时也要确认状态码是302。

60

你还可以通过以下方式跟踪重定向:

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

这样做会让用户在浏览器中的体验变得一样,并且可以检查你期望在那儿找到的内容,比如:

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

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)

这个方法用来检查返回的响应是否是一个状态码重定向,是否重定向到了预期的URL(包括任何GET数据),并且最终页面的状态码是目标状态码

如果你的请求使用了follow参数,那么预期的URL目标状态码将会是重定向链的最后一个网址和状态码。

如果fetch_redirect_response设置为False,那么最终页面不会被加载。因为测试客户端无法获取外部网址,这在预期的URL不属于你的Django应用时特别有用。

在比较两个网址时,方案(比如http或https)会被正确处理。如果重定向到的地方没有指定方案,就会使用原始请求的方案。如果预期的URL中有方案,那么就会用这个方案来进行比较。

撰写回答