我有这个简单的表单(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类的测试:
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
此测试有什么问题?谢谢。
答案 0 :(得分:0)
我发现self.assertFieldOutput(DateField, valid, invalid)
用于测试从Django类派生的字段类。因此它不适用于您的情况。
测试应如下所示,假设'/form/
是表单的网址,而'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)