From 2b01bdc1121bf7dee1296bc3b8bdf8443d54d202 Mon Sep 17 00:00:00 2001 From: Jason Gerard DeRose Date: Thu, 28 Aug 2008 01:38:29 +0000 Subject: [PATCH] 209: Added Type.__call__() method; fleshed out Type.convert() method; added corresponding unit tests --- ipalib/ipa_types.py | 16 +++++++++++++--- ipalib/tests/test_ipa_types.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/ipalib/ipa_types.py b/ipalib/ipa_types.py index 3cae7af57..5bcea5344 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 71d8d6f31..657a99bd7 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