Skip to content

Instantly share code, notes, and snippets.

@slor
Created January 16, 2013 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slor/4544538 to your computer and use it in GitHub Desktop.
Save slor/4544538 to your computer and use it in GitHub Desktop.
Mock the open() builtin as a context manager.
# http://www.voidspace.org.uk/python/mock/
from mock import MagicMock
open_name = '%s.open' % __name__
with patch(open_name, create=True) as mock_open:
mock_file = MagicMock(spec=file)
mock_file.read.return_value = 'hello'
mock_open.return_value.__enter__.return_value = mock_file
with open('/some/path', 'rU') as f:
print f.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment