vendredi 5 août 2016

Django form unittest with ChoiceField and MultipleChoiceField failing is_valid()

I'm running into a small problem with writing a unit test for a Django form. I really just want to check the is_valid() method and have seen examples but my code isn't working and after a day or so of reading up on Google I've yet to find the answer I'm looking for. Below is the code for the forms.py and test_forms.py

forms.py

class DataSelectForm(forms.Form):
    #these are done in the init funct.
    result_type = forms.ChoiceField(widget=forms.Select(attrs={'class': 'field-long'}))
    band_selection = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}))
    title = forms.CharField(widget=forms.HiddenInput())
    description = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, result_list=None, band_list=None, *args, **kwargs):
        super(DataSelectForm, self).__init__(*args, **kwargs)
        if result_list is not None and band_list is not None:
            self.fields["result_type"] = forms.ChoiceField(choices=result_list, widget=forms.Select(attrs={'class': 'field-long'}))
            self.fields["band_selection"] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}), choices=band_list

test_forms.py

 def test_data_select_form(self):
        results = ResultType.objects.all()
        results_value = []
        for result in results:
            results_value.append(result.result_type)
        bands = SatelliteBand.objects.all()
        bands_value = []
        for band in bands:
            bands_value.append(band.band_name)
        form_data = {'result_type': results_value, 'band_selection': bands_value, 'title': 'a title', 'description': 'some description'}
        form = DataSelectForm(data = form_data)

        print(form['title'].value())
        print(form['description'].value())
        print(form['result_type'].value())
        print(form['band_selection'].value())

        self.assertTrue(form.is_valid())

The only thing I get when I run the test case is "AssertionError: False is not true" I understand the error, just not why I'm getting it. I'm passing in all the data and I can see it when I run the print statements. I've tried taking the result_type and band_selection and passing it into the constructor instead of it being a part of the form_data but that didn't work either. What am I missing?

Aucun commentaire:

Enregistrer un commentaire