For a specific test-scenario I wanted:
- avoid accessing the file system through pythons builtin
open
-function - don't want to use 3rd party libraries like Michael Foord's Mock library
I would like to hear your opinion, if this seems like a valuable solution, or if there are
- similar solutions with less lines of code
- grave errors or caveats in the provided solution
from io import StringIO
class MockFile(StringIO):
"""Wraps StringIO, because of python 2.6: clumsy name-property reset"""
name = None #overwrite TextIOWrapper-property - part 1/2
_vfs = {} #virtual File-System enables to "re-read" already written MockFiles
def __init__(self, name, mode = 'r', buffer_ = None):
self.name = name #overwrite TextIOWrapper-property - part 2/2
if self._vfs.has_key(name):
buffer_ = self._vfs[name]
super(MockFile, self).__init__(unicode(buffer_))
__enter__ = lambda self: self
__exit__ = lambda self, exc_type, exc_value, traceback: None
read = lambda self, size = None: super(Mockfile, self).read(size)
def write(self, data):
super(MockFile, self).write(data)
self._vfs[self.name] = self.getvalue()
def replace_builtin(builtinname, replacementobj):
import __builtin__
builtin_func = getattr(__builtin__, builtinname)
setattr(__builtin__, builtinname, replacementobj)
def decorator_factory(func):
def decorator(*args, **kwarg):
return func(*args, **kwarg)
#attach the original name and function to the decorator:
decorator.replaced_builtin = (builtinname, builtin_func)
return decorator
return decorator_factory