From b4c553e201406ad23dc58928a4ba5561c802b4fb Mon Sep 17 00:00:00 2001 From: Thomas Adamcik Date: Mon, 1 Apr 2013 20:33:22 +0200 Subject: [PATCH] config: Add LogLevelConfigSchema. --- mopidy/utils/config.py | 33 +++++++++++++++++++++++++++++++++ tests/utils/config_test.py | 16 ++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/mopidy/utils/config.py b/mopidy/utils/config.py index d7eed6bf..a121b277 100644 --- a/mopidy/utils/config.py +++ b/mopidy/utils/config.py @@ -223,3 +223,36 @@ class ExtensionConfigSchema(ConfigSchema): def format(self, name, values): return super(ExtensionConfigSchema, self).format('ext.%s' % name, values) + + +class LogLevelConfigSchema(object): + """Special cased schema for handling a config section with loglevels. + + Expects the config keys to be logger names and the values to be log levels + as understood by the LogLevel config value. Does not sub-class ConfigSchema, + but implements the same interface. + """ + def __init__(self): + self._configvalue = LogLevel() + + def format(self, name, values): + lines = ['[%s]' % name] + for key, value in sorted(values.items()): + if value is not None: + lines.append('%s = %s' % (key, self._configvalue.format(value))) + return '\n'.join(lines) + + def convert(self, items): + errors = {} + values = {} + + for key, value in items: + try: + if value.strip(): + values[key] = self._configvalue.deserialize(value) + except ValueError as e: # deserialization failed + errors[key] = str(e) + + if errors: + raise exceptions.ConfigError(errors) + return values diff --git a/tests/utils/config_test.py b/tests/utils/config_test.py index ae4f4a02..fae47111 100644 --- a/tests/utils/config_test.py +++ b/tests/utils/config_test.py @@ -330,3 +330,19 @@ class ExtensionConfigSchemaTest(unittest.TestCase): def test_section_name_is_prefixed(self): schema = config.ExtensionConfigSchema() self.assertEqual('[ext.foo]', schema.format('foo', {})) + + +class LogLevelConfigSchemaTest(unittest.TestCase): + def test_conversion(self): + schema = config.LogLevelConfigSchema() + result = schema.convert([('foo.bar', 'DEBUG'), ('baz', 'INFO')]) + + self.assertEqual(logging.DEBUG, result['foo.bar']) + self.assertEqual(logging.INFO, result['baz']) + + def test_format(self): + schema = config.LogLevelConfigSchema() + expected = ['[levels]', 'baz = info', 'foo.bar = debug'] + result = schema.format('levels', {'foo.bar': logging.DEBUG, 'baz': logging.INFO}) + self.assertEqual('\n'.join(expected), result) +