source: trunk/packages/invirt-base/python/invirt/common.py @ 1391

Last change on this file since 1391 was 1330, checked in by price, 16 years ago

sipb-xen-base -> invirt-base

File size: 1.6 KB
RevLine 
[1197]1from __future__ import with_statement
2
[778]3import unittest
[795]4from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
[1197]5import contextlib as clib
[778]6
7class struct(object):
8    'A simple namespace object.'
[781]9    def __init__(self, d = {}, **kwargs):
[778]10        'd is the dictionary to update my __dict__ with.'
11        self.__dict__.update(d)
[781]12        self.__dict__.update(kwargs)
[778]13
14def dicts2struct(x):
15    """
16    Given a tree of lists/dicts, perform a deep traversal to transform all the
17    dicts to structs.
18    """
19    if type(x) == dict:
20        return struct((k, dicts2struct(v)) for k,v in x.iteritems())
21    elif type(x) == list:
22        return [dicts2struct(v) for v in x]
23    else:
24        return x
25
[1197]26@clib.contextmanager
27def lock_file(path, exclusive = True):
28    with clib.closing(file(path, 'w')) as f:
29        if exclusive:
30            locktype = LOCK_EX
31        else:
32            locktype = LOCK_SH
33        flock(f, locktype)
34        try:
35            yield
36        finally:
37            flock(f, LOCK_UN)
[778]38
[781]39#
40# Tests.
41#
42
[778]43class common_tests(unittest.TestCase):
44    def test_dicts2structs(self):
45        dicts = {
46                'atom': 0,
47                'dict': { 'atom': 'atom', 'list': [1,2,3] },
48                'list': [ 'atom', {'key': 'value'} ]
49                }
50        structs = dicts2struct(dicts)
51        self.assertEqual(structs.atom,        dicts['atom'])
52        self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
53        self.assertEqual(structs.dict.list,   dicts['dict']['list'])
54        self.assertEqual(structs.list[0],     dicts['list'][0])
55        self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
56
57if __name__ == '__main__':
58    unittest.main()
Note: See TracBrowser for help on using the repository browser.