为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Stubber来模拟download_fileobj?

如何使用Stubber来模拟download_fileobj?

眼眸繁星 2023-10-18 15:23:10
在boto3中,我如何使用Stubbermockdownload_fileobj这是一个资源方法?例如:import boto3from botocore.stub import Stubbers3 = 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)
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

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)


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 61 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信