1
2 """ Unittest Helpers.
3
4 Copyright (c) 2009, 2011 The PyroScope Project <pyroscope.project@gmail.com>
5 """
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import errno
20 import StringIO
21 from contextlib import contextmanager
25 """ StringIO that replaces itself in a dict on close.
26 """
27
28 - def __init__(self, namespace, key, buf=''):
29 self.namespace = namespace
30 self.key = key
31
32 self.namespace[self.key] = self
33 StringIO.StringIO.__init__(self, buf)
34
35
37 self.namespace[self.key] = self.getvalue()
38 StringIO.StringIO.close(self)
39
40
41 @contextmanager
42 -def mockedopen(fakefiles=None):
43 """ Mock the open call to use a dict as the file system.
44
45 @param fakefiles: Prepopulated filesystem, this is passed on as the context's target.
46 """
47 import __builtin__
48 fakefiles = fakefiles or {}
49
50 def mock_open(name, mode=None, buffering=None):
51 "Helper"
52 mode = mode or "r"
53 if mode.startswith('r'):
54 if name not in fakefiles:
55 raise OSError((errno.ENOENT, "File not found", name))
56 try:
57 fakefiles[name].close()
58 except AttributeError:
59 pass
60 return StringIO.StringIO(fakefiles[name])
61 else:
62 return DictItemIO(fakefiles, name)
63
64 builtin_open = __builtin__.open
65 try:
66 __builtin__.open = mock_open
67 yield fakefiles
68 finally:
69 __builtin__.open = builtin_open
70