samedi 20 janvier 2018

Django testing: assertionError 'form' not used to render response

I am getting this error message when I try to test a form validation in Django.

AssertionError: The form 'form' was not used to render the response

I am trying to test a couple things around a FileUpload form.

What is strange is that only one test is failing, out of bunch that use the form. For example, the first and second test below are almost identical, yet the first one is successful and the second returns this AssertionError.

The only difference between first and second is file path and the field attribute. And I can't narrow down the problem to these two items.

def test_invalid_file_extension_error(self):
        date = dt(2018,1,14)
        with open(bad_path) as fp:
            data = {
                'account': self.account.pk,
                'date': self.date.strftime("%d-%m-%Y"),
                'file': fp
            }
            response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True)
        field = 'file'

        self.assertEqual(response.status_code, 200)
        self.assertFormError(response, 'form', field, u'Unsupported file extension.')

def test_invalid_due_to_future_date(self):
        date = dt(2020,1,1)
        with open(good_path) as fp:
            data = {
                'account': self.account.pk,
                'date': self.date.strftime("%d-%m-%Y"),
                'file': fp
            }
            response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True)
        field = 'date'
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response, 'form', field, u'The date cannot be a future date!')

Here's my view:

class UploadView(CreateView):
    model = SaveReports
    form_class = SaveReportsForm

    def form_valid(self, form):
        report = form.save()
        account = ReportsToTraxns(
                                    account = report.account.name,
                                    filename = report.file.name
        )
        account.commit_statement(report.account_id)
        return super().form_valid(form)

Here's my form:

class SaveReportsForm(ModelForm):
    date = DateField(widget=DateInput(format = '%d-%m-%Y'),
                     input_formats=['%d-%m-%Y',]
                    )

    class Meta:
        model = SaveReports
        exclude = ['datetime_upload']

    def __init__(self, *args, **kwargs):
        super(SaveReportsForm, self).__init__(*args, **kwargs)
        self.fields['account'].empty_label = None

    def clean_date(self):
        date = self.cleaned_data['date']
        if date > dt_date.today():
            raise ValidationError("The date cannot be a future date! ... unless you own a time machine")
        return date

I appreciate anyone that can help!

Aucun commentaire:

Enregistrer un commentaire