76: Fleshed out opt.validate(); added corresponding unit tests

This commit is contained in:
Jason Gerard DeRose 2008-08-07 06:23:02 +00:00
parent 8cbd8343be
commit 14a0658464
3 changed files with 43 additions and 20 deletions

View File

@ -54,6 +54,7 @@ class ValidationError(IPAError):
self.error = error self.error = error
super(ValidationError, self).__init__(name, value, error) super(ValidationError, self).__init__(name, value, error)
class NormalizationError(ValidationError): class NormalizationError(ValidationError):
def __init__(self, name, value, type): def __init__(self, name, value, type):
self.type = type self.type = type
@ -62,9 +63,10 @@ class NormalizationError(ValidationError):
) )
class RuleError(ValidationError):
class ValidationRuleError(ValidationError): def __init__(self, name, value, rule, error):
msg = '%r is invalid %r: %s' self.rule = rule
super(RuleError, self).__init__(name, value, error)

View File

@ -76,9 +76,19 @@ class opt(plugable.ReadOnly):
if is_rule(attr): if is_rule(attr):
yield attr yield attr
def validate(self, value): def validate(self, value):
pass for rule in self.rules:
msg = rule(value)
if msg is None:
continue
raise errors.RuleError(
self.__class__.__name__,
value,
rule,
msg,
)

View File

@ -72,29 +72,40 @@ class test_opt():
class int_opt(self.cls()): class int_opt(self.cls()):
type = int type = int
@rule @rule
def rule_a(self, value): def rule_0(self, value):
if value == 'a': if value == 0:
return 'cannot be a' return 'cannot be 0'
@rule @rule
def rule_b(self, value): def rule_1(self, value):
if value == 'b': if value == 1:
return 'cannot be b' return 'cannot be 1'
@rule @rule
def rule_c(self, value): def rule_2(self, value):
if value == 'c': if value == 2:
return 'cannot be c' return 'cannot be 2'
return int_opt return int_opt
def test_rules(self): def test_rules(self):
""" """
Test the rules property. Test the rules property.
""" """
i = self.sub()() o = self.sub()()
def i_attr(l): def get_rule(i):
return getattr(i, 'rule_%s' % l) return getattr(o, 'rule_%d' % i)
letters = ('a', 'b', 'c') rules = tuple(get_rule(i) for i in xrange(3))
rules = tuple(i_attr(l) for l in letters) assert o.rules == rules
assert i.rules == rules
def test_validation(self):
"""
Test the validation method.
"""
o = self.sub()()
o.validate(9)
for i in xrange(3):
e = raises(errors.RuleError, o.validate, i)
assert e.error == 'cannot be %d' % i