A common task in programs I\'ve been working on lately is modifying a text file in some way. (Hey, I\'m on Linux. Everything\'s a file. And I do large-scale system admin.)>
For later readers who just want a way to test that code writing to files is working correctly, here is a "fake_open" that patches the open builtin of a module to use StringIO. fake_open returns a dict of opened files which can be examined in a unit test or doctest, all without needing a real file-system.
def fake_open(module):
"""Patch module's `open` builtin so that it returns StringIOs instead of
creating real files, which is useful for testing. Returns a dict that maps
opened file names to StringIO objects."""
from contextlib import closing
from StringIO import StringIO
streams = {}
def fakeopen(filename,mode):
stream = StringIO()
stream.close = lambda: None
streams[filename] = stream
return closing(stream)
module.open = fakeopen
return streams