URL 在 self.assertRedirects 中引用正斜杠(响应,expected_url,status_code=302,target_status_code=200)

URL quoted forward slash in self.assertRedirects(response, expected_url, status_code=302, target_status_code=200)

我有以下测试用例

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

我遇到了失败

==================================================================== FAIL: testNoAccessWithoutLogin (procurement.tests.expenseTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/jason/public_html/activity/project/procurement/tests.py", line 66, in testNoAccessWithoutLogin target_status_code=200) File "/Users/jason/.virtualenvs/activity/lib/python2.7/site-packages/django/test/testcases.py", line 304, in assertRedirects (url, expected_url)) AssertionError: Response redirected to 'http://testserver/login/?next=%2Fprocurement%2FexpenseList%2F', expected 'http://testserver/login/?next=/procurement/expenseList/'

我假设这是因为“%2F”不等于“/”,但为什么要引用响应中的 url?

正在测试的函数装饰有

@login_required

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])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'.

来源docs on python.org.