diff options
-rw-r--r-- | ipalib/ipa_types.py | 16 | ||||
-rw-r--r-- | ipalib/tests/test_ipa_types.py | 17 |
2 files changed, 32 insertions, 1 deletions
diff --git a/ipalib/ipa_types.py b/ipalib/ipa_types.py index f0baf1ba6..3cae7af57 100644 --- a/ipalib/ipa_types.py +++ b/ipalib/ipa_types.py @@ -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 diff --git a/ipalib/tests/test_ipa_types.py b/ipalib/tests/test_ipa_types.py index d78160db0..71d8d6f31 100644 --- a/ipalib/tests/test_ipa_types.py +++ b/ipalib/tests/test_ipa_types.py @@ -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 |