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

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

我有这个简单的表单(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

我有基于 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)

错误,在 运行 这个测试之后:

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

这个测试有什么问题?谢谢。

我发现 self.assertFieldOutput(DateField, valid, invalid) 用于测试从 Django class 派生的字段 class。所以它不适用于你的情况。

测试应该如下,假设 '/form/ 是您表单的 url 并且 'form' 是您视图中的上下文键。

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)