PageRenderTime 58ms CodeModel.GetById 31ms app.highlight 25ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/forms_tests/tests/test_error_messages.py

https://gitlab.com/asmjahid/django
Python | 274 lines | 268 code | 5 blank | 1 comment | 0 complexity | fafa1f1ac61608ae74eb7005b18b5f62 MD5 | raw file
  1# -*- coding: utf-8 -*-
  2from __future__ import unicode_literals
  3
  4from django.core.files.uploadedfile import SimpleUploadedFile
  5from django.forms import (
  6    BooleanField, CharField, ChoiceField, DateField, DateTimeField,
  7    DecimalField, EmailField, FileField, FloatField, Form,
  8    GenericIPAddressField, IntegerField, ModelChoiceField,
  9    ModelMultipleChoiceField, MultipleChoiceField, RegexField,
 10    SplitDateTimeField, TimeField, URLField, ValidationError, utils,
 11)
 12from django.test import SimpleTestCase, TestCase
 13from django.utils.encoding import python_2_unicode_compatible
 14from django.utils.safestring import mark_safe
 15
 16
 17class AssertFormErrorsMixin(object):
 18    def assertFormErrors(self, expected, the_callable, *args, **kwargs):
 19        try:
 20            the_callable(*args, **kwargs)
 21            self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.")
 22        except ValidationError as e:
 23            self.assertEqual(e.messages, expected)
 24
 25
 26class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
 27    def test_charfield(self):
 28        e = {
 29            'required': 'REQUIRED',
 30            'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
 31            'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
 32        }
 33        f = CharField(min_length=5, max_length=10, error_messages=e)
 34        self.assertFormErrors(['REQUIRED'], f.clean, '')
 35        self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
 36        self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901')
 37
 38    def test_integerfield(self):
 39        e = {
 40            'required': 'REQUIRED',
 41            'invalid': 'INVALID',
 42            'min_value': 'MIN VALUE IS %(limit_value)s',
 43            'max_value': 'MAX VALUE IS %(limit_value)s',
 44        }
 45        f = IntegerField(min_value=5, max_value=10, error_messages=e)
 46        self.assertFormErrors(['REQUIRED'], f.clean, '')
 47        self.assertFormErrors(['INVALID'], f.clean, 'abc')
 48        self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
 49        self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
 50
 51    def test_floatfield(self):
 52        e = {
 53            'required': 'REQUIRED',
 54            'invalid': 'INVALID',
 55            'min_value': 'MIN VALUE IS %(limit_value)s',
 56            'max_value': 'MAX VALUE IS %(limit_value)s',
 57        }
 58        f = FloatField(min_value=5, max_value=10, error_messages=e)
 59        self.assertFormErrors(['REQUIRED'], f.clean, '')
 60        self.assertFormErrors(['INVALID'], f.clean, 'abc')
 61        self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
 62        self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
 63
 64    def test_decimalfield(self):
 65        e = {
 66            'required': 'REQUIRED',
 67            'invalid': 'INVALID',
 68            'min_value': 'MIN VALUE IS %(limit_value)s',
 69            'max_value': 'MAX VALUE IS %(limit_value)s',
 70            'max_digits': 'MAX DIGITS IS %(max)s',
 71            'max_decimal_places': 'MAX DP IS %(max)s',
 72            'max_whole_digits': 'MAX DIGITS BEFORE DP IS %(max)s',
 73        }
 74        f = DecimalField(min_value=5, max_value=10, error_messages=e)
 75        self.assertFormErrors(['REQUIRED'], f.clean, '')
 76        self.assertFormErrors(['INVALID'], f.clean, 'abc')
 77        self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
 78        self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
 79
 80        f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e)
 81        self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45')
 82        self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234')
 83        self.assertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4')
 84
 85    def test_datefield(self):
 86        e = {
 87            'required': 'REQUIRED',
 88            'invalid': 'INVALID',
 89        }
 90        f = DateField(error_messages=e)
 91        self.assertFormErrors(['REQUIRED'], f.clean, '')
 92        self.assertFormErrors(['INVALID'], f.clean, 'abc')
 93
 94    def test_timefield(self):
 95        e = {
 96            'required': 'REQUIRED',
 97            'invalid': 'INVALID',
 98        }
 99        f = TimeField(error_messages=e)
100        self.assertFormErrors(['REQUIRED'], f.clean, '')
101        self.assertFormErrors(['INVALID'], f.clean, 'abc')
102
103    def test_datetimefield(self):
104        e = {
105            'required': 'REQUIRED',
106            'invalid': 'INVALID',
107        }
108        f = DateTimeField(error_messages=e)
109        self.assertFormErrors(['REQUIRED'], f.clean, '')
110        self.assertFormErrors(['INVALID'], f.clean, 'abc')
111
112    def test_regexfield(self):
113        e = {
114            'required': 'REQUIRED',
115            'invalid': 'INVALID',
116            'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
117            'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
118        }
119        f = RegexField(r'^[0-9]+$', min_length=5, max_length=10, error_messages=e)
120        self.assertFormErrors(['REQUIRED'], f.clean, '')
121        self.assertFormErrors(['INVALID'], f.clean, 'abcde')
122        self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
123        self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901')
124
125    def test_emailfield(self):
126        e = {
127            'required': 'REQUIRED',
128            'invalid': 'INVALID',
129            'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
130            'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
131        }
132        f = EmailField(min_length=8, max_length=10, error_messages=e)
133        self.assertFormErrors(['REQUIRED'], f.clean, '')
134        self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh')
135        self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com')
136        self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, 'aye@bee.com')
137
138    def test_filefield(self):
139        e = {
140            'required': 'REQUIRED',
141            'invalid': 'INVALID',
142            'missing': 'MISSING',
143            'empty': 'EMPTY FILE',
144        }
145        f = FileField(error_messages=e)
146        self.assertFormErrors(['REQUIRED'], f.clean, '')
147        self.assertFormErrors(['INVALID'], f.clean, 'abc')
148        self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
149        self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))
150
151    def test_urlfield(self):
152        e = {
153            'required': 'REQUIRED',
154            'invalid': 'INVALID',
155            'max_length': '"%(value)s" has more than %(limit_value)d characters.',
156        }
157        f = URLField(error_messages=e, max_length=17)
158        self.assertFormErrors(['REQUIRED'], f.clean, '')
159        self.assertFormErrors(['INVALID'], f.clean, 'abc.c')
160        self.assertFormErrors(
161            ['"http://djangoproject.com" has more than 17 characters.'],
162            f.clean,
163            'djangoproject.com'
164        )
165
166    def test_booleanfield(self):
167        e = {
168            'required': 'REQUIRED',
169        }
170        f = BooleanField(error_messages=e)
171        self.assertFormErrors(['REQUIRED'], f.clean, '')
172
173    def test_choicefield(self):
174        e = {
175            'required': 'REQUIRED',
176            'invalid_choice': '%(value)s IS INVALID CHOICE',
177        }
178        f = ChoiceField(choices=[('a', 'aye')], error_messages=e)
179        self.assertFormErrors(['REQUIRED'], f.clean, '')
180        self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b')
181
182    def test_multiplechoicefield(self):
183        e = {
184            'required': 'REQUIRED',
185            'invalid_choice': '%(value)s IS INVALID CHOICE',
186            'invalid_list': 'NOT A LIST',
187        }
188        f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e)
189        self.assertFormErrors(['REQUIRED'], f.clean, '')
190        self.assertFormErrors(['NOT A LIST'], f.clean, 'b')
191        self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b'])
192
193    def test_splitdatetimefield(self):
194        e = {
195            'required': 'REQUIRED',
196            'invalid_date': 'INVALID DATE',
197            'invalid_time': 'INVALID TIME',
198        }
199        f = SplitDateTimeField(error_messages=e)
200        self.assertFormErrors(['REQUIRED'], f.clean, '')
201        self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b'])
202
203    def test_generic_ipaddressfield(self):
204        e = {
205            'required': 'REQUIRED',
206            'invalid': 'INVALID IP ADDRESS',
207        }
208        f = GenericIPAddressField(error_messages=e)
209        self.assertFormErrors(['REQUIRED'], f.clean, '')
210        self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0')
211
212    def test_subclassing_errorlist(self):
213        class TestForm(Form):
214            first_name = CharField()
215            last_name = CharField()
216            birthday = DateField()
217
218            def clean(self):
219                raise ValidationError("I like to be awkward.")
220
221        @python_2_unicode_compatible
222        class CustomErrorList(utils.ErrorList):
223            def __str__(self):
224                return self.as_divs()
225
226            def as_divs(self):
227                if not self:
228                    return ''
229                return mark_safe('<div class="error">%s</div>' % ''.join('<p>%s</p>' % e for e in self))
230
231        # This form should print errors the default way.
232        form1 = TestForm({'first_name': 'John'})
233        self.assertHTMLEqual(
234            str(form1['last_name'].errors),
235            '<ul class="errorlist"><li>This field is required.</li></ul>'
236        )
237        self.assertHTMLEqual(
238            str(form1.errors['__all__']),
239            '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>'
240        )
241
242        # This one should wrap error groups in the customized way.
243        form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList)
244        self.assertHTMLEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>')
245        self.assertHTMLEqual(str(form2.errors['__all__']), '<div class="error"><p>I like to be awkward.</p></div>')
246
247
248class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
249    def test_modelchoicefield(self):
250        # Create choices for the model choice field tests below.
251        from forms_tests.models import ChoiceModel
252        ChoiceModel.objects.create(pk=1, name='a')
253        ChoiceModel.objects.create(pk=2, name='b')
254        ChoiceModel.objects.create(pk=3, name='c')
255
256        # ModelChoiceField
257        e = {
258            'required': 'REQUIRED',
259            'invalid_choice': 'INVALID CHOICE',
260        }
261        f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e)
262        self.assertFormErrors(['REQUIRED'], f.clean, '')
263        self.assertFormErrors(['INVALID CHOICE'], f.clean, '4')
264
265        # ModelMultipleChoiceField
266        e = {
267            'required': 'REQUIRED',
268            'invalid_choice': '%(value)s IS INVALID CHOICE',
269            'list': 'NOT A LIST OF VALUES',
270        }
271        f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e)
272        self.assertFormErrors(['REQUIRED'], f.clean, '')
273        self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3')
274        self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])