PageRenderTime 82ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/validators/tests.py

https://github.com/etianen/django
Python | 363 lines | 353 code | 8 blank | 2 comment | 0 complexity | 94146f029c1c7cb920bba543054fd667 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from datetime import datetime, timedelta
  4. import re
  5. import types
  6. from unittest import TestCase
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import (
  9. BaseValidator, EmailValidator, MaxLengthValidator, MaxValueValidator,
  10. MinLengthValidator, MinValueValidator, RegexValidator, URLValidator,
  11. validate_comma_separated_integer_list, validate_email, validate_integer,
  12. validate_ipv46_address, validate_ipv4_address, validate_ipv6_address,
  13. validate_slug,
  14. )
  15. from django.test import SimpleTestCase
  16. from django.test.utils import str_prefix
  17. NOW = datetime.now()
  18. EXTENDED_SCHEMES = ['http', 'https', 'ftp', 'ftps', 'git', 'file']
  19. TEST_DATA = (
  20. # (validator, value, expected),
  21. (validate_integer, '42', None),
  22. (validate_integer, '-42', None),
  23. (validate_integer, -42, None),
  24. (validate_integer, -42.5, None),
  25. (validate_integer, None, ValidationError),
  26. (validate_integer, 'a', ValidationError),
  27. (validate_email, 'email@here.com', None),
  28. (validate_email, 'weirder-email@here.and.there.com', None),
  29. (validate_email, 'email@[127.0.0.1]', None),
  30. (validate_email, 'email@[2001:dB8::1]', None),
  31. (validate_email, 'email@[2001:dB8:0:0:0:0:0:1]', None),
  32. (validate_email, 'email@[::fffF:127.0.0.1]', None),
  33. (validate_email, 'example@valid-----hyphens.com', None),
  34. (validate_email, 'example@valid-with-hyphens.com', None),
  35. (validate_email, 'test@domain.with.idn.tld.उदाहरण.परीक्षा', None),
  36. (validate_email, 'email@localhost', None),
  37. (EmailValidator(whitelist=['localdomain']), 'email@localdomain', None),
  38. (validate_email, '"test@test"@example.com', None),
  39. (validate_email, None, ValidationError),
  40. (validate_email, '', ValidationError),
  41. (validate_email, 'abc', ValidationError),
  42. (validate_email, 'abc@', ValidationError),
  43. (validate_email, 'abc@bar', ValidationError),
  44. (validate_email, 'a @x.cz', ValidationError),
  45. (validate_email, 'abc@.com', ValidationError),
  46. (validate_email, 'something@@somewhere.com', ValidationError),
  47. (validate_email, 'email@127.0.0.1', ValidationError),
  48. (validate_email, 'email@[127.0.0.256]', ValidationError),
  49. (validate_email, 'email@[2001:db8::12345]', ValidationError),
  50. (validate_email, 'email@[2001:db8:0:0:0:0:1]', ValidationError),
  51. (validate_email, 'email@[::ffff:127.0.0.256]', ValidationError),
  52. (validate_email, 'example@invalid-.com', ValidationError),
  53. (validate_email, 'example@-invalid.com', ValidationError),
  54. (validate_email, 'example@invalid.com-', ValidationError),
  55. (validate_email, 'example@inv-.alid-.com', ValidationError),
  56. (validate_email, 'example@inv-.-alid.com', ValidationError),
  57. (validate_email, 'test@example.com\n\n<script src="x.js">', ValidationError),
  58. # Quoted-string format (CR not allowed)
  59. (validate_email, '"\\\011"@here.com', None),
  60. (validate_email, '"\\\012"@here.com', ValidationError),
  61. (validate_email, 'trailingdot@shouldfail.com.', ValidationError),
  62. # Max length of domain name in email is 249 (see validator for calculation)
  63. (validate_email, 'a@%s.us' % ('a' * 249), None),
  64. (validate_email, 'a@%s.us' % ('a' * 250), ValidationError),
  65. (validate_slug, 'slug-ok', None),
  66. (validate_slug, 'longer-slug-still-ok', None),
  67. (validate_slug, '--------', None),
  68. (validate_slug, 'nohyphensoranything', None),
  69. (validate_slug, '', ValidationError),
  70. (validate_slug, ' text ', ValidationError),
  71. (validate_slug, ' ', ValidationError),
  72. (validate_slug, 'some@mail.com', ValidationError),
  73. (validate_slug, '你好', ValidationError),
  74. (validate_slug, '\n', ValidationError),
  75. (validate_ipv4_address, '1.1.1.1', None),
  76. (validate_ipv4_address, '255.0.0.0', None),
  77. (validate_ipv4_address, '0.0.0.0', None),
  78. (validate_ipv4_address, '256.1.1.1', ValidationError),
  79. (validate_ipv4_address, '25.1.1.', ValidationError),
  80. (validate_ipv4_address, '25,1,1,1', ValidationError),
  81. (validate_ipv4_address, '25.1 .1.1', ValidationError),
  82. # validate_ipv6_address uses django.utils.ipv6, which
  83. # is tested in much greater detail in its own testcase
  84. (validate_ipv6_address, 'fe80::1', None),
  85. (validate_ipv6_address, '::1', None),
  86. (validate_ipv6_address, '1:2:3:4:5:6:7:8', None),
  87. (validate_ipv6_address, '1:2', ValidationError),
  88. (validate_ipv6_address, '::zzz', ValidationError),
  89. (validate_ipv6_address, '12345::', ValidationError),
  90. (validate_ipv46_address, '1.1.1.1', None),
  91. (validate_ipv46_address, '255.0.0.0', None),
  92. (validate_ipv46_address, '0.0.0.0', None),
  93. (validate_ipv46_address, 'fe80::1', None),
  94. (validate_ipv46_address, '::1', None),
  95. (validate_ipv46_address, '1:2:3:4:5:6:7:8', None),
  96. (validate_ipv46_address, '256.1.1.1', ValidationError),
  97. (validate_ipv46_address, '25.1.1.', ValidationError),
  98. (validate_ipv46_address, '25,1,1,1', ValidationError),
  99. (validate_ipv46_address, '25.1 .1.1', ValidationError),
  100. (validate_ipv46_address, '1:2', ValidationError),
  101. (validate_ipv46_address, '::zzz', ValidationError),
  102. (validate_ipv46_address, '12345::', ValidationError),
  103. (validate_comma_separated_integer_list, '1', None),
  104. (validate_comma_separated_integer_list, '1,2,3', None),
  105. (validate_comma_separated_integer_list, '1,2,3,', None),
  106. (validate_comma_separated_integer_list, '', ValidationError),
  107. (validate_comma_separated_integer_list, 'a,b,c', ValidationError),
  108. (validate_comma_separated_integer_list, '1, 2, 3', ValidationError),
  109. (MaxValueValidator(10), 10, None),
  110. (MaxValueValidator(10), -10, None),
  111. (MaxValueValidator(10), 0, None),
  112. (MaxValueValidator(NOW), NOW, None),
  113. (MaxValueValidator(NOW), NOW - timedelta(days=1), None),
  114. (MaxValueValidator(0), 1, ValidationError),
  115. (MaxValueValidator(NOW), NOW + timedelta(days=1), ValidationError),
  116. (MinValueValidator(-10), -10, None),
  117. (MinValueValidator(-10), 10, None),
  118. (MinValueValidator(-10), 0, None),
  119. (MinValueValidator(NOW), NOW, None),
  120. (MinValueValidator(NOW), NOW + timedelta(days=1), None),
  121. (MinValueValidator(0), -1, ValidationError),
  122. (MinValueValidator(NOW), NOW - timedelta(days=1), ValidationError),
  123. (MaxLengthValidator(10), '', None),
  124. (MaxLengthValidator(10), 10 * 'x', None),
  125. (MaxLengthValidator(10), 15 * 'x', ValidationError),
  126. (MinLengthValidator(10), 15 * 'x', None),
  127. (MinLengthValidator(10), 10 * 'x', None),
  128. (MinLengthValidator(10), '', ValidationError),
  129. (URLValidator(), 'http://www.djangoproject.com/', None),
  130. (URLValidator(), 'HTTP://WWW.DJANGOPROJECT.COM/', None),
  131. (URLValidator(), 'http://localhost/', None),
  132. (URLValidator(), 'http://example.com/', None),
  133. (URLValidator(), 'http://www.example.com/', None),
  134. (URLValidator(), 'http://www.example.com:8000/test', None),
  135. (URLValidator(), 'http://valid-with-hyphens.com/', None),
  136. (URLValidator(), 'http://subdomain.example.com/', None),
  137. (URLValidator(), 'http://200.8.9.10/', None),
  138. (URLValidator(), 'http://200.8.9.10:8000/test', None),
  139. (URLValidator(), 'http://valid-----hyphens.com/', None),
  140. (URLValidator(), 'http://example.com?something=value', None),
  141. (URLValidator(), 'http://example.com/index.php?something=value&another=value2', None),
  142. (URLValidator(), 'https://example.com/', None),
  143. (URLValidator(), 'ftp://example.com/', None),
  144. (URLValidator(), 'ftps://example.com/', None),
  145. (URLValidator(EXTENDED_SCHEMES), 'file://localhost/path', None),
  146. (URLValidator(EXTENDED_SCHEMES), 'git://example.com/', None),
  147. (URLValidator(), 'foo', ValidationError),
  148. (URLValidator(), 'http://', ValidationError),
  149. (URLValidator(), 'http://example', ValidationError),
  150. (URLValidator(), 'http://example.', ValidationError),
  151. (URLValidator(), 'http://.com', ValidationError),
  152. (URLValidator(), 'http://invalid-.com', ValidationError),
  153. (URLValidator(), 'http://-invalid.com', ValidationError),
  154. (URLValidator(), 'http://invalid.com-', ValidationError),
  155. (URLValidator(), 'http://inv-.alid-.com', ValidationError),
  156. (URLValidator(), 'http://inv-.-alid.com', ValidationError),
  157. (URLValidator(), 'file://localhost/path', ValidationError),
  158. (URLValidator(), 'git://example.com/', ValidationError),
  159. (URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
  160. (BaseValidator(True), True, None),
  161. (BaseValidator(True), False, ValidationError),
  162. (RegexValidator(), '', None),
  163. (RegexValidator(), 'x1x2', None),
  164. (RegexValidator('[0-9]+'), 'xxxxxx', ValidationError),
  165. (RegexValidator('[0-9]+'), '1234', None),
  166. (RegexValidator(re.compile('[0-9]+')), '1234', None),
  167. (RegexValidator('.*'), '', None),
  168. (RegexValidator(re.compile('.*')), '', None),
  169. (RegexValidator('.*'), 'xxxxx', None),
  170. (RegexValidator('x'), 'y', ValidationError),
  171. (RegexValidator(re.compile('x')), 'y', ValidationError),
  172. (RegexValidator('x', inverse_match=True), 'y', None),
  173. (RegexValidator(re.compile('x'), inverse_match=True), 'y', None),
  174. (RegexValidator('x', inverse_match=True), 'x', ValidationError),
  175. (RegexValidator(re.compile('x'), inverse_match=True), 'x', ValidationError),
  176. (RegexValidator('x', flags=re.IGNORECASE), 'y', ValidationError),
  177. (RegexValidator('a'), 'A', ValidationError),
  178. (RegexValidator('a', flags=re.IGNORECASE), 'A', None),
  179. )
  180. def create_simple_test_method(validator, expected, value, num):
  181. if expected is not None and issubclass(expected, Exception):
  182. test_mask = 'test_%s_raises_error_%d'
  183. def test_func(self):
  184. # assertRaises not used, so as to be able to produce an error message
  185. # containing the tested value
  186. try:
  187. validator(value)
  188. except expected:
  189. pass
  190. else:
  191. self.fail("%s not raised when validating '%s'" % (
  192. expected.__name__, value))
  193. else:
  194. test_mask = 'test_%s_%d'
  195. def test_func(self):
  196. try:
  197. self.assertEqual(expected, validator(value))
  198. except ValidationError as e:
  199. self.fail("Validation of '%s' failed. Error message was: %s" % (
  200. value, str(e)))
  201. if isinstance(validator, types.FunctionType):
  202. val_name = validator.__name__
  203. else:
  204. val_name = validator.__class__.__name__
  205. test_name = test_mask % (val_name, num)
  206. return test_name, test_func
  207. # Dynamically assemble a test class with the contents of TEST_DATA
  208. class TestSimpleValidators(SimpleTestCase):
  209. def test_single_message(self):
  210. v = ValidationError('Not Valid')
  211. self.assertEqual(str(v), str_prefix("[%(_)s'Not Valid']"))
  212. self.assertEqual(repr(v), str_prefix("ValidationError([%(_)s'Not Valid'])"))
  213. def test_message_list(self):
  214. v = ValidationError(['First Problem', 'Second Problem'])
  215. self.assertEqual(str(v), str_prefix("[%(_)s'First Problem', %(_)s'Second Problem']"))
  216. self.assertEqual(repr(v), str_prefix("ValidationError([%(_)s'First Problem', %(_)s'Second Problem'])"))
  217. def test_message_dict(self):
  218. v = ValidationError({'first': ['First Problem']})
  219. self.assertEqual(str(v), str_prefix("{%(_)s'first': [%(_)s'First Problem']}"))
  220. self.assertEqual(repr(v), str_prefix("ValidationError({%(_)s'first': [%(_)s'First Problem']})"))
  221. def test_regex_validator_flags(self):
  222. try:
  223. RegexValidator(re.compile('a'), flags=re.IGNORECASE)
  224. except TypeError:
  225. pass
  226. else:
  227. self.fail("TypeError not raised when flags and pre-compiled regex in RegexValidator")
  228. def test_max_length_validator_message(self):
  229. v = MaxLengthValidator(16, message='"%(value)s" has more than %(limit_value)d characters.')
  230. with self.assertRaisesMessage(ValidationError, '"djangoproject.com" has more than 16 characters.'):
  231. v('djangoproject.com')
  232. test_counter = 0
  233. for validator, value, expected in TEST_DATA:
  234. name, method = create_simple_test_method(validator, expected, value, test_counter)
  235. setattr(TestSimpleValidators, name, method)
  236. test_counter += 1
  237. class TestValidatorEquality(TestCase):
  238. """
  239. Tests that validators have valid equality operators (#21638)
  240. """
  241. def test_regex_equality(self):
  242. self.assertEqual(
  243. RegexValidator(r'^(?:[a-z0-9\.\-]*)://'),
  244. RegexValidator(r'^(?:[a-z0-9\.\-]*)://'),
  245. )
  246. self.assertNotEqual(
  247. RegexValidator(r'^(?:[a-z0-9\.\-]*)://'),
  248. RegexValidator(r'^(?:[0-9\.\-]*)://'),
  249. )
  250. self.assertEqual(
  251. RegexValidator(r'^(?:[a-z0-9\.\-]*)://', "oh noes", "invalid"),
  252. RegexValidator(r'^(?:[a-z0-9\.\-]*)://', "oh noes", "invalid"),
  253. )
  254. self.assertNotEqual(
  255. RegexValidator(r'^(?:[a-z0-9\.\-]*)://', "oh", "invalid"),
  256. RegexValidator(r'^(?:[a-z0-9\.\-]*)://', "oh noes", "invalid"),
  257. )
  258. self.assertNotEqual(
  259. RegexValidator(r'^(?:[a-z0-9\.\-]*)://', "oh noes", "invalid"),
  260. RegexValidator(r'^(?:[a-z0-9\.\-]*)://'),
  261. )
  262. self.assertNotEqual(
  263. RegexValidator('', flags=re.IGNORECASE),
  264. RegexValidator(''),
  265. )
  266. self.assertNotEqual(
  267. RegexValidator(''),
  268. RegexValidator('', inverse_match=True),
  269. )
  270. def test_regex_equality_nocache(self):
  271. pattern = r'^(?:[a-z0-9\.\-]*)://'
  272. left = RegexValidator(pattern)
  273. re.purge()
  274. right = RegexValidator(pattern)
  275. self.assertEqual(
  276. left,
  277. right,
  278. )
  279. def test_regex_equality_blank(self):
  280. self.assertEqual(
  281. RegexValidator(),
  282. RegexValidator(),
  283. )
  284. def test_email_equality(self):
  285. self.assertEqual(
  286. EmailValidator(),
  287. EmailValidator(),
  288. )
  289. self.assertNotEqual(
  290. EmailValidator(message="BAD EMAIL"),
  291. EmailValidator(),
  292. )
  293. self.assertEqual(
  294. EmailValidator(message="BAD EMAIL", code="bad"),
  295. EmailValidator(message="BAD EMAIL", code="bad"),
  296. )
  297. def test_basic_equality(self):
  298. self.assertEqual(
  299. MaxValueValidator(44),
  300. MaxValueValidator(44),
  301. )
  302. self.assertNotEqual(
  303. MaxValueValidator(44),
  304. MinValueValidator(44),
  305. )
  306. self.assertNotEqual(
  307. MinValueValidator(45),
  308. MinValueValidator(11),
  309. )