简体   繁体   中英

How to mock an unit test for a delete bucket operation using boto3

I'm using Python 2.7 and boto3 to interact with S3 buckets. So far so good!

What I'm trying to achieve now is an unit test for the delete bucket operation, but using mocked data, ie, with no real interaction with the S3 storage.

For other unit tests throughout the project, I've used patches and boto3's Stubber successfully, but for some reason, I'm unable to find a way to use the same techniques to mock interactions using the S3 resource and the Bucket sub-resource .

This is the snippet of code I want to unit test:

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

Thanks!

You can use unittest.mock . With this, any method can be patched and the return value can be set:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM