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