Search code examples
djangovalidationdatefielddjango-unittest

Django 2.1 SimpleTestCase, assertFieldOutput for DateField - AssertionError: ValidationError not raised


I have this simple Form (Django 2.1, Python 3.6.5).

class RenewBookForm(forms.Form):
    renewal_date = forms.DateField(
                   help_text="Enter a date between now and 4 weeks (default 3)."
                 )

    def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']

        # Check if a date is not in the past.
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - renewal in past'))

        # Check if a date is in the allowed range (+4 weeks from today).
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(_(
                              'Invalid date - renewal more than 4 weeks ahead'))

        # Remember to always return the cleaned data.
        return data

And I have the test based on SimpleTestCase class:

import datetime
from django.forms import DateField

from django.test import SimpleTestCase
from django.utils import timezone

from catalog.forms import RenewBookForm

class RenewBookFormTest(SimpleTestCase):

    def test_renew_form_date_is_not_in_the_past(self):
        error_invalid = ['Invalid date - renewal in past']
        past_date = datetime.date.today() - datetime.timedelta(days=1)
        valid_date = datetime.date.today() + datetime.timedelta(days=21)
        valid = { valid_date: valid_date }
        invalid = { past_date: error_invalid }
        self.assertFieldOutput(DateField, valid, invalid)

Error, after running this test:

Traceback (most recent call last):
  File "locallibrary/catalog/tests/test_forms.py", line 53, in test_renew_form_date_is_not_in_the_past
    self.assertFieldOutput(DateField, valid, invalid)
  File "~/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/test/testcases.py", line 660, in assertFieldOutput
    required.clean(input)
AssertionError: ValidationError not raised

What is wrong in this test? Thank you.


Solution

  • I found that self.assertFieldOutput(DateField, valid, invalid) is used to test field class derived from Django class. So it is not applicable for your case.

    The test should be as following, assuming '/form/ is the url to your form and 'form' is the context key in your view.

    class RenewBookFormTest(SimpleTestCase):
    
        def test_renew_form_date_is_not_in_the_past(self):
            error_invalid = ['Invalid date - renewal in past']
            past_date = datetime.date.today() - datetime.timedelta(days=1)
            valid_date = datetime.date.today() + datetime.timedelta(days=21)
            response = self.client.post('/form/', data={'renewal_date': past_date})
            context_form = 'form'
            self.assertFormError(response, context_form, 'renewal_date',
                    error_invalid)