Skip to content

Instantly share code, notes, and snippets.

@dutc
Created November 27, 2013 17:08
Show Gist options
  • Save dutc/7679334 to your computer and use it in GitHub Desktop.
Save dutc/7679334 to your computer and use it in GitHub Desktop.
Making a mockery of open!
def test(filename, message):
with open(filename, 'w') as f:
f.write(message)
#!/usr/bin/env python
from somecode import func
if __name__ == '__main__':
from cStringIO import StringIO
from contextlib import contextmanager
buf = StringIO()
def open(*args, **kwargs):
@contextmanager
def wrapper():
try: yield buf
finally: pass
return wrapper()
# mock it
import somecode
somecode.open = open
# run it
filename = 'test'
message = 'hello!'
func(filename, message)
assert buf.getvalue() == message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment