我正在尝试使用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参数)。
答案 0 :(得分:0)
generate_presigned_post()
和 generate_presigned_url()
不会对 S3 进行 API 调用,因此不需要 Stubber。
示例:
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