Commits

David Baumgold  committed fc2132c

Updated tests, fixed minor bugs that cropped up

  • Participants
  • Parent commits a59b567

Comments (0)

Files changed (4)

File tests/fields.py

 
 class PrePostValidationTest(TestCase):
     class F(Form):
-        a = PrePostTestField(validators=[validators.Length(max=1, message="too long")])
+        a = PrePostTestField(validators=[validators.Length(max=1, \
+            messages={u'max': u"too long"})])
 
     def _init_field(self, value):
         form = self.F(a=value)

File tests/translations.py

     def test_validator_translation(self):
         form = self.F(a='hellobye')
         self.assert_(not form.validate())
-        self.assertEquals(form.a.errors[0], u'field cannot be longer than 5 characters.')
+        self.assertEquals(form.a.errors[0], u'Field cannot be longer than 5 characters.')

File tests/validators.py

 
         # Test new formatting features
         grab = lambda **k : grab_error_message(length(**k), self.form, field)
-        self.assertEqual(grab(min=2, max=5, message='%(min)d and %(max)d'), '2 and 5')
+        self.assertEqual(grab(min=2, max=5, messages={u'between': '%(min)d and %(max)d'}), '2 and 5')
         self.assert_('at least 8' in grab(min=8))
         self.assert_('longer than 5' in grab(max=5))
         self.assert_('between 2 and 5' in grab(min=2, max=5))
                 raise Exception('Translator function called during form declaration: it should be called at response time.')
             __str__ = __unicode__
 
-        message = ReallyLazyProxy()
-        self.assertRaises(Exception, str, message)
-        self.assertRaises(Exception, unicode, message)
-        self.assert_(equal_to('fieldname', message=message))
-        self.assert_(length(min=1, message=message))
-        self.assert_(NumberRange(1,5, message=message))
-        self.assert_(required(message=message))
-        self.assert_(regexp('.+', message=message))
-        self.assert_(email(message=message))
-        self.assert_(ip_address(message=message))
-        self.assert_(url(message=message))
+        messages = {u'invalid': ReallyLazyProxy()}
+        self.assertRaises(Exception, str, messages[u'invalid'])
+        self.assertRaises(Exception, unicode, messages[u'invalid'])
+        self.assert_(equal_to('fieldname', messages=messages))
+        self.assert_(length(min=1, messages=messages))
+        self.assert_(NumberRange(1,5, messages=messages))
+        self.assert_(required(messages=messages))
+        self.assert_(regexp('.+', messages=messages))
+        self.assert_(email(messages=messages))
+        self.assert_(ip_address(messages=messages))
+        self.assert_(url(messages=messages))
 
     def test_any_of(self):
         self.assertEqual(AnyOf(['a', 'b', 'c'])(self.form, DummyField('b')), None)

File wtforms/validators.py

         self.messages = {
             u'invalid': u'Field must be equal to %(other_name)s.',
             u'invalid-name': u"Invalid field name '%s'." % self.fieldname,
-        }.update(messages)
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
         try:
         will not be checked.
     :param messages:
         Dict of error message to raise in case of validation errors. Relevant keys
-        are "min-singular", "min-plural", "max-singular", "max-plural", and
-        "between". Can be interpolated using `%(min)d` and `%(max)d` if desired.
+        are "singular", "plural", "min", "max", and "between". Can be interpolated
+        using `%(min)d` and `%(max)d` if desired.
         Useful defaults are provided depending on the existence of min and max.
     """
     def __init__(self, min=None, max=None, messages={}):
         self.min = min
         self.max = max
         self.messages = {
-            u'min-singular': u"Field must be at least %(min)d character long.",
-            u'min-plural':   u"Field must be at least %(min)d characters long.",
-            u'max-singular': u"Field cannot be longer than %(max)d character.",
-            u'max-plural':   u"Field cannot be longer than %(max)d characters.",
-            u'between':      u"Field must be between %(min)d and %(max)d characters long.",
-        }.update(messages)
+            u'singular':u"character",
+            u'plural':  u"characters",
+            u'min':     u"Field must be at least %(min)d %(noun)s long.",
+            u'max':     u"Field cannot be longer than %(max)d %(noun)s.",
+            u'between': u"Field must be between %(min)d and %(max)d %(noun)s long.",
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
-        interpolate = {u'min': self.min, u'max': self.max}
+        interpolate = {u'min': self.min, u'max': self.max,
+                u'noun': self.messages['plural']}
         l = field.data and len(field.data) or 0
         if self.min is not None and self.max is not None:
             if not (self.min <= l <= self.max):
                 raise ValidationError(self.messages[u'between'] % interpolate)
         elif self.min is not None:
             if self.min == 1:
-                msg = self.messages[u'min-singular'] % interpolate
-            else:
-                msg = self.messages[u'min-plural'] % interpolate
+                interpolate[u'noun'] = self.messages[u'singular']
             if not (self.min <= l):
-                raise ValidationError(msg)
+                raise ValidationError(self.messages[u'min'] % interpolate)
         elif self.max is not None:
             if self.max == 1:
-                msg = self.messages[u'max-singular'] % interpolate
-            else:
-                msg = self.messages[u'max-plural'] % interpolate
+                interpolate[u'noun'] = self.messages[u'singular']
             if not (l <= self.max):
-                raise ValidationError(msg)
+                raise ValidationError(self.messages[u'max'] % interpolate)
 
 class NumberRange(object):
     """
             u'min': u"Number must be greater than %(min)s.",
             u'max': u"Number must be less than %(max)s.",
             u'between': u"Number must be between %(min)s and %(max)s.",
-        }.update(messages)
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
         data = field.data
     def __init__(self, messages={}):
         self.messages = {
             u'invalid': u"This field is required.",
-        }.update(message)
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
         if not field.data or isinstance(field.data, basestring) and not field.data.strip():
         self.regex = regex
         self.messages = {
             u'invalid': u"Invalid input.",
-        }.update(messages)
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
         if not self.regex.match(field.data or u''):
     expression and should only be used in instances where you later verify by
     other means, such as email activation or lookups.
 
-    :param message:
-        Error message to raise in case of a validation error.
+    :param messages:
+        Dict of error messages to raise in case of validation errors. Relevant
+        key is "invalid".
     """
-    def __init__(self, message=None):
-        super(Email, self).__init__(r'^.+@[^.].*\.[a-z]{2,10}$', re.IGNORECASE, message)
-
-    def __call__(self, form, field):
-        if self.message is None:
-            self.message = field.gettext(u'Invalid email address.')
-
-        super(Email, self).__call__(form, field)
+    def __init__(self, messages={}):
+        default_messages = {
+            u'invalid': u'Invalid email address.',
+        }
+        default_messages.update(messages)
+        super(Email, self).__init__(r'^.+@[^.].*\.[a-z]{2,10}$', re.IGNORECASE, default_messages)
 
 
 class IPAddress(object):
             u"invalid": u"Invalid IP address.",
             u"four-octets": u"IP address must contain exactly four integers, separated by dots.",
             u"int-range": u"IP address must contain four integers between 0 and 255.",
-        }.update(messages)
+        }
+        self.messages.update(messages)
 
     def __call__(self, form, field):
         try:
             octets = [int(o) for o in octets]
         except ValueError:
             raise ValidationError(self.messages['four-octets'])
-        for o in octects:
+        for o in octets:
             if o < 0 or o > 255:
                 raise ValidationError(self.messages['int-range'])
 
     def __init__(self, require_tld=True, messages={}):
         tld_part = (require_tld and ur'\.[a-z]{2,10}' or u'')
         regex = ur'^[a-z]+://([^/:]+%s|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]+)?(\/.*)?$' % tld_part
-        messages = {
+        default_messages = {
             u'invalid': u"Invalid URL.",
-        }.update(messages)
-        super(URL, self).__init__(regex, re.IGNORECASE, messages)
+        }
+        default_messages.update(messages)
+        super(URL, self).__init__(regex, re.IGNORECASE, default_messages)
 
 
 class AnyOf(object):
         self.values = values
         self.messages = {
             u'invalid': u'Invalid value, must be one of: %(values)s.',
-        }.update(messages)
+        }
+        self.messages.update(messages)
         if values_formatter is None:
             values_formatter = lambda v: u', '.join(v)
         self.values_formatter = values_formatter
         self.values = values
         self.messages = {
             u'invalid': u"Invalid value, can't be any of: %(values)s.",
-        }.update(messages)
+        }
+        self.messages.update(messages)
         if values_formatter is None:
             values_formatter = lambda v: u', '.join(v)
         self.values_formatter = values_formatter