Example of configurator which shows cross-referencing between different parts of the configuration + access to data in external modules.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Copyright (C) 2013 Vinay Sajip. All rights reserved. | |
# | |
import re | |
import sys | |
import unittest | |
from distlib.util import Configurator | |
class TestContainer(object): | |
def __init__(self, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
class ConfigTestCase(unittest.TestCase): | |
def test_basic(self): | |
d = { | |
'a': 1, | |
'b': 2.0, | |
'c': 'xyz', | |
'stderr': 'ext://sys.stderr', | |
'list_o_stuff': [ | |
'cfg://stderr', | |
'ext://sys.stdout', | |
'ext://logging.NOTSET', | |
], | |
'dict_o_stuff': { | |
'k1': 'cfg://list_o_stuff[1]', | |
'k2': 'abc', | |
'k3': 'cfg://list_o_stuff', | |
}, | |
'another_dict_o_stuff': { | |
'k1': 'cfg://dict_o_stuff[k2]', | |
'k2': 'ext://re.I', | |
'k3': 'cfg://dict_o_stuff[k3][0]', | |
}, | |
'custom': { | |
'()': '__main__.TestContainer', | |
'[]': [1, 'a', 2.0, ('b', 'c', 'd')], | |
'.': { | |
'p1': 'a', | |
'p2': 'b', | |
'p3': { | |
'()' : '__main__.TestContainer', | |
'[]': [1, 2], | |
'.': { | |
'p1': 'c', | |
}, | |
}, | |
}, | |
'k1': 'v1', | |
'k2': 'v2', | |
} | |
} | |
cfg = Configurator(d) | |
self.assertEqual(cfg['a'], 1) | |
self.assertEqual(cfg['b'], 2.0) | |
self.assertEqual(cfg['c'], 'xyz') | |
self.assertTrue(cfg['stderr'] is sys.stderr) | |
self.assertTrue(cfg['list_o_stuff'][0] is sys.stderr) | |
self.assertTrue(cfg['list_o_stuff'][1] is sys.stdout) | |
self.assertEqual(cfg['list_o_stuff'][-1], 0) | |
self.assertTrue(cfg['dict_o_stuff']['k1'] is sys.stdout) | |
self.assertEqual(cfg['another_dict_o_stuff']['k1'], 'abc') | |
self.assertTrue(cfg['another_dict_o_stuff']['k2'] is re.I) | |
self.assertTrue(cfg['another_dict_o_stuff']['k3'] is sys.stderr) | |
custom = cfg['custom'] | |
self.assertTrue(isinstance(custom, TestContainer)) | |
self.assertEqual(custom.args, (1, 'a', 2.0, ('b', 'c', 'd'))) | |
self.assertEqual(custom.kwargs, {'k1': 'v1', 'k2': 'v2'}) | |
self.assertEqual(custom.p1, 'a') | |
self.assertEqual(custom.p2, 'b') | |
self.assertTrue(isinstance(custom.p3, TestContainer)) | |
self.assertEqual(custom.p3.args, (1, 2)) | |
self.assertEqual(custom.p3.kwargs, {}) | |
self.assertEqual(custom.p3.p1, 'c') | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment