您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

模拟boto3 S3客户端方法Python

模拟boto3 S3客户端方法Python

一旦我在这里发布,我就设法提出了一个解决方案。希望对您有帮助:)

import botocore
from botocore.exceptions import ClientError
from mock import patch
import boto3

orig = botocore.client.BaseClient._make_api_call

def mock_make_api_call(self, operation_name, kwarg):
    if operation_name == 'UploadPartCopy':
        parsed_response = {'Error': {'Code': '500', 'Message': 'Error Uploading'}}
        raise ClientError(parsed_response, operation_name)
    return orig(self, operation_name, kwarg)

with patch('botocore.client.BaseClient._make_api_call', new=mock_make_api_call):
    client = boto3.client('s3')
    # Should return actual result
    o = client.get_object(Bucket='my-bucket', Key='my-key')
    # Should return mocked exception
    e = client.upload_part_copy()

JordanPhilips还使用botocore.stub.Stubber类发布了一个不错的解决方案]。虽然使用更干净的解决方案,但我无法模拟特定的操作。

Botocore有一个客户存根,您可以将其用于此目的:docs。

这是在其中放置错误的示例:

import boto3
from botocore.stub import Stubber

client = boto3.client('s3')
stubber = Stubber(client)
stubber.add_client_error('upload_part_copy')
stubber.activate()

# Will raise a ClientError
client.upload_part_copy()

这是放置正常响应的示例。此外,现在可以在上下文中使用该Stubber。重要的是要注意,存根将在可能的范围内验证您提供的响应与服务将实际返回的内容匹配。这不是完美的方法,但是它将保护您避免插入总的废话响应。

import boto3
from botocore.stub import Stubber

client = boto3.client('s3')
stubber = Stubber(client)
list_buckets_response = {
    "Owner": {
        "DisplayName": "name",
        "ID": "EXAMPLE123"
    },
    "Buckets": [{
        "CreationDate": "2016-05-25T16:55:48.000Z",
        "Name": "foo"
    }]
}
expected_params = {}
stubber.add_response('list_buckets', list_buckets_response, expected_params)

with stubber:
    response = client.list_buckets()

assert response == list_buckets_response
python 2022/1/1 18:43:20 有302人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶