如何使用 boto3 模拟删除存储桶操作的单元测试

问题描述 投票:0回答:2

我使用 Python 2.7 和 boto3 与 S3 存储桶交互。到目前为止一切顺利!

我现在想要实现的是删除存储桶操作的单元测试,但使用模拟数据,即与 S3 存储没有真正的交互。

对于整个项目的其他单元测试,我成功地使用了补丁和 boto3 的 Stubber,但由于某种原因,我无法找到一种方法来使用相同的技术来使用 S3 资源Bucket 来模拟交互子资源.

这是我想要进行单元测试的代码片段:

def delete_bucket(self, bucket_name):
    resource = boto3.resource('s3')
    bucket = resource.Bucket(bucket_name)
    bucket.objects.all().delete()
    return bucket.delete()

谢谢!

python python-2.7 unit-testing mocking boto3
2个回答
1
投票

您可以使用unittest.mock。这样,任何方法都可以被修补并可以设置返回值:

from unittest.mock import patch
with patch('boto3.bucket.delete') as boto_delete_patch:
    boto_delete_patch.return_value = 'Return value'
    # Perform any action

0
投票

我也有类似的问题。我想模拟删除存储桶中的对象,并且我必须模拟客户端:

from unittest import mock
def your_test():
    with mock.patch("boto3.client"):
        # Your code to test
© www.soinside.com 2019 - 2024. All rights reserved.