For a specific test-scenario i wanted:
- avoid accessing the filesystem 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
UPDATE: After some real helpful and insightful remarks from Winston Ewert, i corrected my code:
2nd UPDATE: Eliminated superflous code and incorporated try/finally clause.
from io import StringIO
class MockFile(StringIO):
"""Wraps StringIO"""
_vfs = {} #virtual File-System
name = None #overwrite TextIOWrapper-property - part 1/2
def __init__(self, name, mode = 'r', buffer_ = ''):
self.name = name #overwrite TextIOWrapper-property - part 2/2
if self._vfs.has_key(name):
buffer_ = self._vfs.get(name, buffer_)
super(MockFile, self).__init__(unicode(buffer_))
def close(self):
self._vfs[self.name] = self.getvalue()
super(MockFile, self).close()
def replace_builtin(builtinname, replacementobj):
import __builtin__
builtin_func = getattr(__builtin__, builtinname)
def decorator_factory(func):
def decorator(*args, **kwarg):
setattr(__builtin__, builtinname, replacementobj)
try:
result = func(*args, **kwarg)
finally:
setattr(__builtin__, builtinname, builtin_func)
return result
#attach the original name and function to the decorator:
decorator.replaced_builtin = (builtinname, builtin_func)
return decorator
return decorator_factory