samedi 4 juillet 2015

Test form with dynamic choice fields

I created a form with a TypedChoiceField:

class EditProjectForm(ModelForm):
    def __init__(self, action, *args, **kwargs):
        super(EditProjectForm, self).__init__(*args, **kwargs)

        now = datetime.datetime.now()
        if action == 'edit':
            project_year = kwargs['project_year']
            self.fields['year'].choices = [(project_year, project_year)]
        else:
            self.fields['year'].choices = [(now.year, now.year), (now.year + 1, now.year + 1)]

    year = forms.TypedChoiceField(coerce=int)
    ...

This works perfectly fine when using it inside a view. Now I want to write tests for this form:

form_params = {
    'project_year': datetime.datetime.now().year,
}
form = EditProjectForm('new', form_params)
self.assertTrue(form.is_valid())

The test fails, because is_valid() returns False. This is because when calling super.__init__() in the EditProjectForm, the field year doesn't have its choices yet. So the validation for this field fails and an error is added to the error list inside the form.

Moving the super call after self.fields['year'].choices doesn't work either, because self.fields is only available after the super.__init__() call.

How can I add the choices dynamically and still be able to test this?

Aucun commentaire:

Enregistrer un commentaire