如何使用Stubber来模拟download_fileobj?

dru*_*rum 0 python boto3

在boto3中,我如何使用Stubbermockdownload_fileobj这是一个资源方法?

例如:

import boto3
from botocore.stub import Stubber

s3 = boto3.resource('s3')

def foo(s3):
    with open('filename', 'wb') as data:
        s3.download_fileobj('mybucket', 'mykey', data)

def test_foo():
    s3_test = boto3.resource('s3')
    s3_stub = Stubber(s3_test.meta.client)
    
    s3_stub.add_response() # something here

    with s3_stub:
        foo(s3_test)
Run Code Online (Sandbox Code Playgroud)

Man*_*fre 5

get_fileobj 转换为“head_object”和“get_object”调用。这是一个对两个调用进行存根的基本代码片段。

bucket_name = 'mybucket'
key = 'mykey'
content = 'This is the content'

expected_params = {
    'Bucket': bucket_name,
    'Key': key,
}

# Head object
response = {
    'ContentLength': 10,
    'ContentType': 'utf-8',
    'ResponseMetadata': {
        'Bucket': bucket_name,
    }
}
s3_stub.add_response('head_object', response, expected_params)


# Get object
data = BytesIO()
data.write(content.encode("utf-8")
data.seek(0)

response = {
    'ContentLength': len(content),
    'ContentType': 'utf-8',
    'Body': data,
    'ResponseMetadata': {
        'Bucket': bucket_name,
    }
}

s3_stub.add_response('get_object', response, expected_params)
Run Code Online (Sandbox Code Playgroud)