2016-10-04 88 views
0

我想在Django上做我的第一次測試,我不知道這樣做或在閱讀文檔(它解釋了一個非常簡單的測試)我仍然不知道它是如何做的。在Django中如何測試

我試圖做一個測試,「登錄」的網址,並使登錄,並在成功登錄後重定向到授權頁面。

from unittest import TestCase 

from django.test.client import Client 


class Test(TestCase): 
    def testLogin(self): 
     client = Client() 
     headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'} 
     data = {} 
     response = client.post('/login/', headers=headers, data=data, secure=False) 
     assert(response.status_code == 200) 

而且試驗的成功,但我不知道這是怎麼一回事,因爲裝載200「/登錄/」或因爲測試做的登錄名和重定向後,即可獲取200碼。

我該如何檢查登錄後重定向的URL是否正確?有一個插件或者什麼可以幫助測試?或者我可以在哪裏找到一個很好的教程來測試我的觀點和模型?

感謝和問候。

+0

爲什麼不按照[Django doct on testing](https://docs.djangoproject.com/en/1.10/topics/testing/)? –

+0

我試圖按照文檔的教程,但我得到的錯誤。 – Aker666

回答

1

要正確測試重定向,使用follow參數

If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.

那麼你的代碼是

從django.test進口測試用例

class Test(TestCase): 
    def test_login(self): 
     client = Client() 
     headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'} 
     data = {} 
     response = client.post('/login/', headers=headers, data=data, secure=False) 
     self.assertRedirects(response,'/destination/',302,200) 

請注意,這是self.assertRedirects而不是簡單assertassertRedirects

另請注意,上述測試很可能會失敗,因爲您發佈空字典作爲表單數據。 Django表單視圖在表單無效時不會重定向,並且空表單在這裏可能無效。

+0

啊,好的,謝謝。我現在在工作,我會稍後再試!我發送data = {}因爲我沒有使用Django登錄,所以我將登錄委託給IDP(OpenAM),並使用相同格式的代碼進行操作,因此在測試中它應該也能工作:/ – Aker666

+0

是的,在這種情況下,它應該工作 – e4c5

+0

工程,只有一個問題。爲什麼我得到「AssertionError:響應沒有按預期重定向:響應代碼是200(預期302)」在代碼上,我使用「return HttpResponseRedirect('/ loggedin')」。這是正確的? – Aker666

1

Django有很多測試工具。對於這個任務,你應該使用Django的測試用例類,例如django.test.TestCase。 然後你可以使用方法assertRedirects(),它會檢查你已經被重定向的地方以及哪個代碼。你可以找到你需要的任何信息here。 我試着寫代碼爲任務:

from django.test import TestCase 

class Test(TestCase): 
    def test_login(self): 
     data = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password'} 
     response = client.post('/login/', data=data, content_type='application/json', secure=false) 
     assertRedirects(response, '/expected_url/', 200) 

然後你可以使用python3 manage.py test運行所有測試。

+0

嗨,我試圖這樣做之前問這個問題,但我得到「在assertRedirects url = response.url AttributeError:'HttpResponse'對象沒有任何屬性'網址'」所有的時間。 – Aker666