Skip to content

Instantly share code, notes, and snippets.

@la10736
Created March 9, 2016 20:17
Show Gist options
  • Save la10736/bc268e714723ffb2144a to your computer and use it in GitHub Desktop.
Save la10736/bc268e714723ffb2144a to your computer and use it in GitHub Desktop.
wrap_write
from mock import patch
def no_write_option_decorator(f):
builtin_open = open
def fake_write(*args):
pass
def patch_open(path, options):
ret = builtin_open(path, options)
ret.write = fake_write
return ret
def wrapped(src, dst, can_write=True):
with patch("builtins.open", open if can_write else patch_open):
return f(src, dst)
return wrapped
@no_write_option_decorator
def copy(src, dst):
with open(src, 'r') as foo:
with open(dst, 'w') as bar:
bar.write(foo.read())
if __name__ == '__main__':
copy('foo.txt', 'bar.txt')
copy('foo.txt', 'bar2.txt', False)
copy('foo.txt', 'bar3.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment