找不到generate_presigned_post的BotoCore / Boto3 Stubber操作

时间:2019-06-21 13:23:45

标签: python django mocking boto3 botocore

我正在尝试使用botocore.stub.Stubber模拟我的boto3.client,并且在尝试添加模拟的botocore.model.OperationNotFoundError响应时得到generate_presigned_post

class S3FileTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.s3 = botocore.session.get_session().create_client('s3')
        cls.region_name = 'eu-west-2'

    @staticmethod
    def _mock__get_s3(region_name):
        client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name=region_name)
        stubber = Stubber(client)

        stubber.add_response('generate_presigned_post', {'test':1}, {'bucket_name': 'test_bucket', 'region_name': region_name, 'object_name': 'test.csv'})
        return stubber

    @patch('uploader.models.s3_file.S3File._get_s3', new=_mock__get_s3)
    def test_create_presigned_post(self):
        response = S3File.create_presigned_post('stuart-special-testing-bucket', self.region_name, 'test.csv')
        print(response)

运行test_create_presigned_post时,我在OperationNotFoundError中得到了add_reponse。有谁知道为什么会这样吗?

注意:S3File.create_presigned_post直接来自docs,唯一的变化是将客户端移入了一个函数中,以便可以对其进行模拟(并添加region参数)。

1 个答案:

答案 0 :(得分:0)

generate_presigned_post()generate_presigned_url() 不会对 S3 进行 API 调用,因此不需要 Stubber。

https://github.com/boto/botocore/blob/b3b5559a641c1caecaec2739564f043b61947d51/botocore/signers.py#L607

示例:

import boto3

s3 = boto3.client("s3")


def get_upload_url() -> dict:
    return s3.generate_presigned_post(
        Bucket="test-bucket",
        Key="test-file.txt",
    )


def test_get_upload_url():
    response: dict = get_upload_url()
    assert "url" in response
    assert "fields" in response