Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django test user password

Tags:

django

I have written a REST API for updating a user's password. Since it is impossible to unhash the password stored by django, how am I suppose to test my API besides asserting the response status_code?

like image 526
Cheng Avatar asked Mar 15 '23 07:03

Cheng


1 Answers

You can check a user's password with User.check_password(password_to_check). This will return True if the password is correct. (see documentation here)

Note that if you have created a user in your unit test and then change a password for the user, you need to update the user reference before you can see the new password, like this:

// create self.user 
// change the password to "newpassword"
self.user = User.objects.get(username="username")  # get user again so that you can see updated password
self.assertEquals(self.user.check_password("newpassword"), True)
like image 95
Peconia Avatar answered Mar 28 '23 14:03

Peconia