PageRenderTime 97ms CodeModel.GetById 29ms RepoModel.GetById 2ms app.codeStats 0ms

/tests/regressiontests/forms/tests/error_messages.py

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