Mercurial > hg > configuration
changeset 115:56db0b2b90af
fix casting
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Wed, 04 Jul 2012 09:54:37 -0700 |
parents | d1911d9b5b19 |
children | 9d19ed8fd883 |
files | configuration/configuration.py setup.py tests/unit.py |
diffstat | 3 files changed, 32 insertions(+), 5 deletions(-) [+] |
line wrap: on
line diff
--- a/configuration/configuration.py Thu Jun 28 14:54:29 2012 -0700 +++ b/configuration/configuration.py Wed Jul 04 09:54:37 2012 -0700 @@ -313,11 +313,19 @@ _type = self.option_dict[key].get('type') if _type is None and 'default' in self.option_dict[key]: _type = type(self.option_dict[key]['default']) - if _type is not None and not isinstance(value, _type): + if _type is not None: + tocast = True try: - config[key] = _type(value) - except BaseException, e: - raise TypeCastException("Could not coerce %s, %s, to type %s: %s" % (key, value, _type.__name__, e)) + if isinstance(value, _type): + tocast = False + except TypeError: + # type is a type-casting function, not a proper type + pass + if tocast: + try: + config[key] = _type(value) + except BaseException, e: + raise TypeCastException("Could not coerce %s, %s, to type %s: %s" % (key, value, _type.__name__, e)) return config
--- a/setup.py Thu Jun 28 14:54:29 2012 -0700 +++ b/setup.py Wed Jul 04 09:54:37 2012 -0700 @@ -4,7 +4,7 @@ import os -version = "0.2.2" +version = "0.3" dependencies = ['PyYAML'] try:
--- a/tests/unit.py Thu Jun 28 14:54:29 2012 -0700 +++ b/tests/unit.py Wed Jul 04 09:54:37 2012 -0700 @@ -5,6 +5,7 @@ """ import configuration +import datetime import os import sys import tempfile @@ -184,5 +185,23 @@ self.assertEqual(example.config['preferences'], default_prefs) os.remove(tf) + def test_typecast(self): + """casting example""" + + def todate(string): + return datetime.datetime.strptime(string, "%Y%m%d") + + # make an example class + class TypecastExample(configuration.Configuration): + options = {'datestring': {'type': todate}} + example = TypecastExample() + + # parse a date string + example({'datestring': "20120704"}) + + # ensure it works correctly + expected = datetime.datetime(2012, 7, 4, 0, 0) + self.assertEqual(example.config['datestring'], expected) + if __name__ == '__main__': unittest.main()