2015-07-12 30 views
1

,我有以下的TestCaseURL引用向前self.assertRedirects斜槓(響應,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 
+0

你還沒有說過'expenseList'是怎麼做重定向的。你使用'login_required'裝飾器嗎?它需要對查詢字符串參數進行urlencode編碼,以防它們包含像'#'或'&'這樣的字符,但是,正斜槓[不應該引用](https://github.com/django/django/blob/d72f8862cb1a39934952e708c3c869be1399846e/django /contrib/auth/views.py#L134)。 – Alasdair

+0

是的,expenseList用@login_required裝飾。我嘗試使用urllib.quote並在expected_url上取消引用來使其匹配,但那沒有奏效。 – MagicLAMP

回答

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

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

+0

謝謝。我應該想到這一點。我嘗試引用,不加引號等,但在整個URL上,而不僅僅是查詢參數。 – MagicLAMP