test_emailfield.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.forms import EmailField, ValidationError
  4. from django.test import SimpleTestCase
  5. from . import FormFieldAssertionsMixin
  6. class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
  7. def test_emailfield_1(self):
  8. f = EmailField()
  9. self.assertWidgetRendersTo(f, '<input type="email" name="f" id="id_f" required />')
  10. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  11. f.clean('')
  12. with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
  13. f.clean(None)
  14. self.assertEqual('person@example.com', f.clean('person@example.com'))
  15. with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"):
  16. f.clean('foo')
  17. self.assertEqual(
  18. 'local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com',
  19. f.clean('local@domain.with.idn.xyzäöüßabc.part.com')
  20. )
  21. def test_email_regexp_for_performance(self):
  22. f = EmailField()
  23. # Check for runaway regex security problem. This will take a long time
  24. # if the security fix isn't in place.
  25. addr = 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058'
  26. self.assertEqual(addr, f.clean(addr))
  27. def test_emailfield_not_required(self):
  28. f = EmailField(required=False)
  29. self.assertEqual('', f.clean(''))
  30. self.assertEqual('', f.clean(None))
  31. self.assertEqual('person@example.com', f.clean('person@example.com'))
  32. self.assertEqual('example@example.com', f.clean(' example@example.com \t \t '))
  33. with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"):
  34. f.clean('foo')
  35. def test_emailfield_min_max_length(self):
  36. f = EmailField(min_length=10, max_length=15)
  37. self.assertWidgetRendersTo(
  38. f,
  39. '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" required />',
  40. )
  41. with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'"):
  42. f.clean('a@foo.com')
  43. self.assertEqual('alf@foo.com', f.clean('alf@foo.com'))
  44. with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'"):
  45. f.clean('alf123456788@foo.com')