Skip to content

Instantly share code, notes, and snippets.

@medwards
Last active August 29, 2015 14:05
Show Gist options
  • Save medwards/858c829a4f74282231a0 to your computer and use it in GitHub Desktop.
Save medwards/858c829a4f74282231a0 to your computer and use it in GitHub Desktop.
Helps mock the open context manager (or any contextmanager!) and does some doublechecking that the mock was used properly
from contextlib import contextmanager
from nose.tools import assert_equals
from mock import patch, Mock
from StringIO import StringIO
@contextmanager
def mock_io_open(content, *args):
stream = StringIO(content)
with mock_context_manager('io.open', stream, *args) as mock:
yield mock
@contextmanager
def mock_context_manager(mock_target, yielded_thing, *args):
if not yielded_thing:
yielded_thing = Mock()
with patch(mock_target) as context_mock:
context_mock.return_value.__enter__.return_value = yielded_thing # mock the contextmanager
yield yielded_thing
assert context_mock.called, "%s mock wasn't used!" % mock_target
if args:
assert_equals(args, context_mock.call_args[0]) # make sure the filenames match
if __name__ == "__main__":
import io
with mock_io_open("foo\nbar\n"):
with io.open('example') as thefile:
assert_equals(thefile.readlines(), ["foo\n", "bar\n"])
with mock_io_open('', "/root/myfile", 'w') as output:
with io.open('/root/myfile', 'w') as thefile:
thefile.write("foo\n")
thefile.writelines(["bar\n", "baz\n"])
assert_equals("foo\nbar\nbaz\n", output.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment