@contextmanager
def patch_open():
 mock_open = MagicMock(spec=open)
 mock_file = MagicMock(spec=file)
 @contextmanager
 def stub_open(*args, **kwargs):
  mock_open(*args, **kwargs)
  (yield mock_file)
 with patch('__builtin__.open', stub_open):
  (yield (mock_open, mock_file))

@ contextmanager def patch_open ( ) : mock_open = MagicMock ( spec = open ) mock_file = MagicMock ( spec = file ) @ contextmanager def stub_open ( * args , ** kwargs ) : mock_open ( * args , ** kwargs ) ( yield mock_file ) with patch ( '__builtin__.open' , stub_open ) : ( yield ( mock_open , mock_file ) )
patch open() to allow mocking both open() itself and the file that is yielded .