URL引用self.assertRedirects中的正斜杠(response,expected_url,status_code = 302,target_status_code = 200)

时间:2015-07-12 07:56:29

标签: django url testcase quote

我有以下TestCase

def testNoAccessWithoutLogin(self):
    """
    Tests that redirected to the login page if you are not logged in
    """
    response = self.client.get(reverse('expenseList'), follow=True)
    expected_url = reverse('login') + "?next=" + reverse('expenseList')
    self.assertRedirects(response, expected_url, status_code=302, 
        target_status_code=200)
    expected_url = reverse('login') + "?next=" + reverse('purchaseList')
    response = self.client.get(reverse('purchaseList'), follow=True)
    self.assertRedirects(response, expected_url, status_code=302, 
        target_status_code=200)
# end testNoAccessWithoutLogin

我的失败

  

=============================================== =====================失败:testNoAccessWithoutLogin(procurement.tests.expenseTests)   -------------------------------------------------- -------------------- Traceback(最近一次调用最后一次):文件   “/Users/jason/public_html/activity/project/procurement/tests.py”,一行   66,在testNoAccessWithoutLogin中       target_status_code = 200)文件“/Users/jason/.virtualenvs/activity/lib/python2.7/site-packages/django/test/testcases.py”,   第304行,在assertRedirects中       (url,expected_url))AssertionError:响应重定向到“http://testserver/login/?next=%2Fprocurement%2FexpenseList%2F”,   预期'http://testserver/login/?next=/procurement/expenseList/'

我认为这是因为“%2F”不等于“/”,但为什么引用的网址被引用?

正在测试的功能用

修饰
@login_required

1 个答案:

答案 0 :(得分:1)

next查询参数值是URL编码的;所以你必须这样做才能验证重定向。

response = self.client.get(reverse('expenseList'), follow=True)
expected_url = reverse('login') + "?next=" + urllib.quote(reverse('expenseList'), "")
self.assertRedirects(response, expected_url, status_code=302, 
    target_status_code=200)

注意urllib.quote的第二个参数是"",为

urllib.quote(string[, safe])
  

使用%xx转义替换字符串中的特殊字符。从不引用字母,数字和字符“_.-”。默认情况下,此函数用于引用URL的路径部分。可选的安全参数指定不应引用的其他字符 - 其默认值为“/”

来源docs on python.org