source: trunk/packages/sipb-xen-base/files/usr/share/python-support/sipb-xen-base/invirt/common.py @ 778

Last change on this file since 778 was 778, checked in by y_z, 16 years ago
  • moved more generic code into common package
  • silently fail if cache fails
  • load the configuration on module load
  • produce a struct-based representation of the configuration
  • allowing full exception messages for OSErrors (default behavior)
  • added some dependencies specs
File size: 1.3 KB
Line 
1import unittest
2
3class struct(object):
4    'A simple namespace object.'
5    def __init__(self, d = {}):
6        'd is the dictionary to update my __dict__ with.'
7        self.__dict__.update(d)
8
9def dicts2struct(x):
10    """
11    Given a tree of lists/dicts, perform a deep traversal to transform all the
12    dicts to structs.
13    """
14    if type(x) == dict:
15        return struct((k, dicts2struct(v)) for k,v in x.iteritems())
16    elif type(x) == list:
17        return [dicts2struct(v) for v in x]
18    else:
19        return x
20
21def wrap(rsrc, func):
22    "Utility to that emulates with Python 2.5's `with closing(rsrc)`."
23    try: return func(rsrc)
24    finally: rsrc.close()
25
26class common_tests(unittest.TestCase):
27    def test_dicts2structs(self):
28        dicts = {
29                'atom': 0,
30                'dict': { 'atom': 'atom', 'list': [1,2,3] },
31                'list': [ 'atom', {'key': 'value'} ]
32                }
33        structs = dicts2struct(dicts)
34        self.assertEqual(structs.atom,        dicts['atom'])
35        self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
36        self.assertEqual(structs.dict.list,   dicts['dict']['list'])
37        self.assertEqual(structs.list[0],     dicts['list'][0])
38        self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
39
40if __name__ == '__main__':
41    unittest.main()
Note: See TracBrowser for help on using the repository browser.