2017-04-18 7 views
0

S3にファイルをアップロードする方法を教えてください。私はこのようなことを試みた。S3にファイルをアップロードするための模擬テストケース

file_mock = mock.MagicMock(spec=File, name='FileMock') 
@mock.patch('storages.backends.s3boto.S3BotoStorage', FileSystemStorage) 
def test_post_file(self): 
    response = self.client.post('/api/v1/file_upload/', { 
       "status": "NEW", 
       "amount": "250.00", 
       "bill": file_mock 
      }) 

これは実際にはS3にアップロードされています。私はこれに新しいです。 S3にファイルをアップロードせずにこれをどのように実装できますか?

答えて

0

一般的なアプローチは正しいですが、botoの動作を上書きする必要があります。そのために複数のパッチを作成する必要があります。このようなものはおそらくうまくいくでしょう:

""" 
Mock Connection class for Bucket 
""" 
class MockConnection(): 
    def __init__(self): 
     self.provider = 'AWS' 

    def delete_key(self, param): 
     pass 

""" 
Mock Connection class which is called for connecting to s3 
""" 
class MockS3Connection(): 
    def get_bucket(self, name, validate=False): 
     return Bucket(MockConnection(), 'bucket') 

""" 
Mock Key class which also gets the bucket 
""" 
class MockKey(): 
    def __init__(self, bucket): 
     self.bucket = bucket 

    def set_contents_from_string(self, data, headers): 
     pass 

    def set_acl(self, read): 
     pass  
""" 
Mock the function which connects to S3 
""" 
def mock_connect_s3(): 
    return MockS3Connection() 

class TestUploadResource(BaseResourceTestCase): 
    """ 
    Test Document upload 
    """ 
    def setUp(self): 
     super(TestUploadResource, self).setUp() 

    @mock.patch('boto.connect_s3', new = mock_connect_s3) 
    @mock.patch("boto.s3.key.Key", MockKey) 
    def test_file_is_accepted(self): 
     ''' 
     Test case to check whether file is uploaded 
     ''' 
     name = raw_input('Document1')+'.pdf' 
     file = open(name,'rw') # Trying to create a new file or open one 

     """ 
     Call the upload docs command with the file which 
     we want to save 
     """ 
     response = self.client.post('some-url') 

     """ 
     Check whether the file is going and the response of creation 
     is coming or not 
     """ 
     self.assertEqual(201, response.status_code) 

期待どおりの動作となるように、さまざまな機能を追加することができます。お役に立てれば。

0

上記の溶液が作用した。また、私はsaveメソッドを嘲笑しなければならなかった。

@mock.patch.object(<Model>, 'save') 
@mock.patch('boto.connect_s3', new=mock_connect_s3) 
@mock.patch("boto.s3.key.Key", MockKey) 
def test_post_file(self, save_mock): 
    response = self.client.post('/api/v1/file_upload/', { 
      "status": "NEW", 
      "amount": "250.00", 
      "bill": file_mock 
     }) 
    self.assertTrue(save_mock.called) 
    self.assertEqual(201, response.status_code) 
関連する問題