207: Added Unicode.validate() method and corresponding unit tests

This commit is contained in:
Jason Gerard DeRose 2008-08-27 23:40:34 +00:00
parent 8fbc01ca86
commit 5da1d4bb86
2 changed files with 32 additions and 1 deletions

View File

@ -83,6 +83,8 @@ class Int(Type):
class Unicode(Type):
type = unicode
def __init__(self, min_length=None, max_length=None, pattern=None):
check_min_max(min_length, max_length, 'min_length', 'max_length')
if min_length is not None and min_length < 0:
@ -100,3 +102,17 @@ class Unicode(Type):
self.regex = None
else:
self.regex = re.compile(pattern)
lock(self)
def validate(self, value):
if type(value) is not self.type:
return 'Must be a string'
if self.regex and self.regex.match(value) is None:
return 'Must match %r' % self.pattern
if self.min_length is not None and len(value) < self.min_length:
return 'Must be at least %d characters long' % self.min_length
if self.max_length is not None and len(value) > self.max_length:
return 'Can be at most %d characters long' % self.max_length

View File

@ -136,9 +136,13 @@ class test_Int(ClassChecker):
class test_Unicode(ClassChecker):
_cls = ipa_types.Unicode
def test_class(self):
assert self.cls.__bases__ == (ipa_types.Type,)
assert self.cls.type is unicode
def test_init(self):
o = self.cls()
assert o.name == 'Unicode'
assert read_only(o, 'name') == 'Unicode'
assert o.min_length is None
assert o.max_length is None
assert o.pattern is None
@ -219,3 +223,14 @@ class test_Unicode(ClassChecker):
assert m.group(1) == value
for value in ('hello beautiful', 'world!'):
assert o.regex.match(value) is None
def test_validate(self):
pat = '^a_*b$'
o = self.cls(min_length=3, max_length=4, pattern=pat)
assert o.validate(u'a_b') is None
assert o.validate(u'a__b') is None
assert o.validate('a_b') == 'Must be a string'
assert o.validate(u'ab') == 'Must be at least 3 characters long'
assert o.validate(u'a___b') == 'Can be at most 4 characters long'
assert o.validate(u'a-b') == 'Must match %r' % pat
assert o.validate(u'a--b') == 'Must match %r' % pat