djangounit-testingchange-password

How to test Django PasswordChangeForm


I am trying to write a test for my changing password view, which users the PasswordChangeForm. This is the test:

def test_profile_change_password(self):
    self.client.force_login(self.user)
    self.user.set_password(self.password)
    new_password = random_password()
    payload = {
        "old_password": self.password,
        "new_password1": new_password,
        "new_password2": new_password,
    }
    form = PasswordChangeForm(user=self.user, data=payload)
    self.assertTrue(form.is_valid())
    
    response = self.client.get(
        reverse_lazy("researcher_ui:change_password"),
    )
    self.assertEqual(response.template_name, ["researcher_UI/change_password.html"])

    response = self.client.post(
        reverse_lazy("researcher_ui:change_password"), payload
    )
    print(response.context['form'].error_messages)

The self.assertTrue(form.is_valid()) test works but when I then try and process the same data through the view I am getting the following errors:

{'password_mismatch': 'The two password fields didn’t match.', 'password_incorrect': 'Your old password was entered incorrectly. Please enter it again.'}

The form.is_valid() shouldn't have return True if this were the case, so what am I doing wrong?


Solution

  • Probably you a wrong a little bit:

    form.error_messages - it is constant, to keep messages if validation falls. Like here https://docs.djangoproject.com/en/5.0/ref/forms/fields/#error-messages

    for your case you need form.errors

    print(form.errors)
    

    more here: https://docs.djangoproject.com/en/5.0/ref/forms/api/#django.forms.Form.errors