diff --git a/ipalib/errors.py b/ipalib/errors.py index 6b1a898a3..f11628272 100644 --- a/ipalib/errors.py +++ b/ipalib/errors.py @@ -54,6 +54,7 @@ class ValidationError(IPAError): self.error = error super(ValidationError, self).__init__(name, value, error) + class NormalizationError(ValidationError): def __init__(self, name, value, type): self.type = type @@ -62,9 +63,10 @@ class NormalizationError(ValidationError): ) - -class ValidationRuleError(ValidationError): - msg = '%r is invalid %r: %s' +class RuleError(ValidationError): + def __init__(self, name, value, rule, error): + self.rule = rule + super(RuleError, self).__init__(name, value, error) diff --git a/ipalib/public.py b/ipalib/public.py index 9467feaff..358bd0762 100644 --- a/ipalib/public.py +++ b/ipalib/public.py @@ -76,9 +76,19 @@ class opt(plugable.ReadOnly): if is_rule(attr): yield attr - 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, + ) + + diff --git a/ipalib/tests/test_public.py b/ipalib/tests/test_public.py index 87d6d1042..57cb2a77f 100644 --- a/ipalib/tests/test_public.py +++ b/ipalib/tests/test_public.py @@ -72,29 +72,40 @@ class test_opt(): class int_opt(self.cls()): type = int @rule - def rule_a(self, value): - if value == 'a': - return 'cannot be a' + def rule_0(self, value): + if value == 0: + return 'cannot be 0' @rule - def rule_b(self, value): - if value == 'b': - return 'cannot be b' + def rule_1(self, value): + if value == 1: + return 'cannot be 1' @rule - def rule_c(self, value): - if value == 'c': - return 'cannot be c' + def rule_2(self, value): + if value == 2: + return 'cannot be 2' return int_opt def test_rules(self): """ Test the rules property. """ - i = self.sub()() - def i_attr(l): - return getattr(i, 'rule_%s' % l) - letters = ('a', 'b', 'c') - rules = tuple(i_attr(l) for l in letters) - assert i.rules == rules + o = self.sub()() + def get_rule(i): + return getattr(o, 'rule_%d' % i) + rules = tuple(get_rule(i) for i in xrange(3)) + assert o.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 + +