2015-06-15 15 views
4

試圖編寫一個unittest來檢查用戶是否輸入了正確的密碼。Django User.check_password不會通過密碼檢查

爲此,使用Django的本機認證功能user.check_password

問題是check_password由於某種原因不會接受user對象自己的密碼。例如,這將引發錯誤:

assert user.check_password(user.password), "Password doesn't match" 

user.password回報MD5 unicode字符串。

有誰知道爲什麼不通過檢查,以及如何通過檢查?

+1

我想你基本上已經回答了你自己的問題。 ['check_password'](https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.User.check_password)取原始密碼而不是已經哈希的密碼。對於單元測試,您將不得不插入testuser的非哈希密碼。 – sthzg

+0

看起來像這樣的路要走。爲我的單元測試工作。 – Oleg

回答

7

發生這種情況是因爲check_password接受一個原始字符串,並且您正在向其傳遞一個散列。

assert user.check_password(user.password) # False because passing hash 

assert user.check_password('my_password') # True because accepts a raw string 

user.password是的散列,以及有關的password元數據。

docs

check_password(raw_password)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)

所以,僅僅通過實際的原始字符串密碼user.check_password()和單元測試會通過。