Search code examples
djangodjango-unittest

Django Unittest for form with password


I want to create a unit test in django testing a form while passing some initial data to it and see if it's valid or invalid. The problem is the framework doesn't allow you to set initial value to a password field, is there any other way around this other than subclassing (which I want to avoid...just for a password field)? My code is below.

def test_new_user_joining(self):
    form_data = {
        'full_name': #invalid value,
        'email': 'test_email@gmail.com',
        'password': 'password'
    }
    form = SignupForm(initial=form_data)
    if form.is_valid():
        self.fail('Form should not be valid')

    form_data['full_name'] = # valid value
    form = SignupForm(initial=form_data)
    if not form.is_valid():
        self.fail('Form should be valid')

Solution

  • In this case you just have to use a data arg instead of initial:

    def test_new_user_joining(self):
        form_data = {
            'full_name': #invalid value,
            'email': 'test_email@gmail.com',
            'password': 'password'
        }
        form = SignupForm(data=form_data)
        if form.is_valid():
            self.fail('Form should not be valid')
    
        form_data['full_name'] = # valid value
        form = SignupForm(data=form_data)
        if not form.is_valid():
            self.fail('Form should be valid')