Package pyrobase :: Module testing
[hide private]
[frames] | no frames]

Source Code for Module pyrobase.testing

 1  # -*- coding: utf-8 -*- 
 2  """ Unittest Helpers. 
 3   
 4      Copyright (c) 2009, 2011 The PyroScope Project <pyroscope.project@gmail.com> 
 5  """ 
 6  # This program is free software; you can redistribute it and/or modify 
 7  # it under the terms of the GNU General Public License as published by 
 8  # the Free Software Foundation; either version 2 of the License, or 
 9  # (at your option) any later version. 
10  # 
11  # This program is distributed in the hope that it will be useful, 
12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
14  # GNU General Public License for more details. 
15  # 
16  # You should have received a copy of the GNU General Public License along 
17  # with this program; if not, write to the Free Software Foundation, Inc., 
18  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 
19  import errno 
20  import StringIO 
21  from contextlib import contextmanager 
22 23 24 -class DictItemIO(StringIO.StringIO):
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
36 - def close(self):
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__ # pylint: disable=W0404 48 fakefiles = fakefiles or {} 49 50 def mock_open(name, mode=None, buffering=None): # pylint: disable=W0613 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