模拟测试用例以将文件上传到S3 [英] Mock test case to upload file to S3

查看:168
本文介绍了模拟测试用例以将文件上传到S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何模拟文件上传到S3.我尝试过这样的事情.

How can we mock file upload to S3. I tried something like this.

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的情况下实现呢?

But this is in inturn actually uploading to S3. I'm new to this. How can this be implemented without uploading files to S3?

推荐答案

因此,您的常规方法是正确的,但是您需要覆盖boto的行为.因此,您需要为其创建多个补丁.这样的事情可能会起作用:

So your general approach is correct but you need to override the behavior of boto. So you need to create multiple patches for it. Something like this would probably work:

"""
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)

然后,您可以在函数中添加各种内容,以达到预期的效果.希望这会有所帮助.

You can then add various things in your function as what would be the expected behavior. Hope this helps.

这篇关于模拟测试用例以将文件上传到S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆