mirror of
https://salsa.debian.org/freeipa-team/freeipa.git
synced 2025-02-25 18:55:28 -06:00
209: Added Type.__call__() method; fleshed out Type.convert() method; added corresponding unit tests
This commit is contained in:
parent
a50f618548
commit
2b01bdc112
@ -53,9 +53,6 @@ class Type(ReadOnly):
|
|||||||
|
|
||||||
type = None # Override in base class
|
type = None # Override in base class
|
||||||
|
|
||||||
def convert(self, value):
|
|
||||||
return self.type(value)
|
|
||||||
|
|
||||||
def __get_name(self):
|
def __get_name(self):
|
||||||
"""
|
"""
|
||||||
Convenience property to return the class name.
|
Convenience property to return the class name.
|
||||||
@ -63,6 +60,19 @@ class Type(ReadOnly):
|
|||||||
return self.__class__.__name__
|
return self.__class__.__name__
|
||||||
name = property(__get_name)
|
name = property(__get_name)
|
||||||
|
|
||||||
|
def convert(self, value):
|
||||||
|
try:
|
||||||
|
return self.type(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def __call__(self, value):
|
||||||
|
if value is None:
|
||||||
|
raise TypeError('value cannot be None')
|
||||||
|
if type(value) is self.type:
|
||||||
|
return value
|
||||||
|
return self.convert(value)
|
||||||
|
|
||||||
|
|
||||||
class Int(Type):
|
class Int(Type):
|
||||||
type = int
|
type = int
|
||||||
|
@ -122,6 +122,36 @@ class test_Int(ClassChecker):
|
|||||||
'min_value > max_value: min_value=%d, max_value=%d' % (l, h)
|
'min_value > max_value: min_value=%d, max_value=%d' % (l, h)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_call(self):
|
||||||
|
o = self.cls()
|
||||||
|
|
||||||
|
# Test calling with None
|
||||||
|
e = raises(TypeError, o, None)
|
||||||
|
assert str(e) == 'value cannot be None'
|
||||||
|
|
||||||
|
# Test with values that can be converted:
|
||||||
|
okay = [
|
||||||
|
3,
|
||||||
|
'3',
|
||||||
|
' 3 ',
|
||||||
|
3L,
|
||||||
|
3.0,
|
||||||
|
]
|
||||||
|
for value in okay:
|
||||||
|
assert o(value) == 3
|
||||||
|
|
||||||
|
# Test with values that cannot be converted:
|
||||||
|
fail = [
|
||||||
|
object,
|
||||||
|
'3.0',
|
||||||
|
'3L',
|
||||||
|
'whatever',
|
||||||
|
]
|
||||||
|
for value in fail:
|
||||||
|
assert o(value) is None
|
||||||
|
|
||||||
|
|
||||||
def test_validate(self):
|
def test_validate(self):
|
||||||
o = self.cls(min_value=2, max_value=7)
|
o = self.cls(min_value=2, max_value=7)
|
||||||
assert o.validate(2) is None
|
assert o.validate(2) is None
|
||||||
|
Loading…
Reference in New Issue
Block a user