216: Added ipa_types.Enum.validate() method; added corresponding unit tests

This commit is contained in:
Jason Gerard DeRose 2008-08-28 07:57:07 +00:00
parent c83c478ae1
commit 283c6f8fce
2 changed files with 21 additions and 3 deletions

View File

@ -170,4 +170,11 @@ class Enum(Type):
if type(val) is not type_:
raise TypeError('%r: %r is not %r' % (val, type(val), type_))
self.values = values
self.frozenset = frozenset(values)
super(Enum, self).__init__(type_)
def validate(self, value):
if type(value) is not self.type:
return 'Incorrect type'
if value not in self.frozenset:
return 'Invalid value'

View File

@ -341,12 +341,13 @@ class test_Enum(ClassChecker):
def test_init(self):
for t in (unicode, int, float):
vals = (t(1),)
o = self.cls(*vals)
values = (t(1), t(2), t(3))
o = self.cls(*values)
assert o.__islocked__() is True
assert read_only(o, 'type') is t
assert read_only(o, 'name') is 'Enum'
assert read_only(o, 'values') == vals
assert read_only(o, 'values') == values
assert read_only(o, 'frozenset') == frozenset(values)
# Check that ValueError is raised when no values are given:
e = raises(ValueError, self.cls)
@ -362,3 +363,13 @@ class test_Enum(ClassChecker):
# type as first:
e = raises(TypeError, self.cls, u'hello', 'world')
assert str(e) == '%r: %r is not %r' % ('world', str, unicode)
def test_validate(self):
values = (u'hello', u'naughty', u'nurse')
o = self.cls(*values)
for value in values:
assert o.validate(value) is None
assert o.validate(str(value)) == 'Incorrect type'
for value in (u'one fish', u'two fish'):
assert o.validate(value) == 'Invalid value'
assert o.validate(str(value)) == 'Incorrect type'