summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJason Gerard DeRose <jderose@redhat.com>2008-08-28 01:38:29 +0000
committerJason Gerard DeRose <jderose@redhat.com>2008-08-28 01:38:29 +0000
commit2b01bdc1121bf7dee1296bc3b8bdf8443d54d202 (patch)
tree356fd187da801f5eaa793c11687a07b751e26b08
parenta50f618548ad4671152f80544496dc7aca2fdcb1 (diff)
downloadfreeipa.git-2b01bdc1121bf7dee1296bc3b8bdf8443d54d202.tar.gz
freeipa.git-2b01bdc1121bf7dee1296bc3b8bdf8443d54d202.tar.xz
freeipa.git-2b01bdc1121bf7dee1296bc3b8bdf8443d54d202.zip
209: Added Type.__call__() method; fleshed out Type.convert() method; added corresponding unit tests
-rw-r--r--ipalib/ipa_types.py16
-rw-r--r--ipalib/tests/test_ipa_types.py30
2 files changed, 43 insertions, 3 deletions
diff --git a/ipalib/ipa_types.py b/ipalib/ipa_types.py
index 3cae7af5..5bcea534 100644
--- a/ipalib/ipa_types.py
+++ b/ipalib/ipa_types.py
@@ -53,9 +53,6 @@ class Type(ReadOnly):
type = None # Override in base class
- def convert(self, value):
- return self.type(value)
-
def __get_name(self):
"""
Convenience property to return the class name.
@@ -63,6 +60,19 @@ class Type(ReadOnly):
return self.__class__.__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):
type = int
diff --git a/ipalib/tests/test_ipa_types.py b/ipalib/tests/test_ipa_types.py
index 71d8d6f3..657a99bd 100644
--- a/ipalib/tests/test_ipa_types.py
+++ b/ipalib/tests/test_ipa_types.py
@@ -122,6 +122,36 @@ class test_Int(ClassChecker):
'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):
o = self.cls(min_value=2, max_value=7)
assert o.validate(2) is None