我有使用以下代码从 S3 存储桶下载文件的代码boto3 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Bucket.download_file.
# foo.py
def dl(src_f, dest_f):
s3 = boto3.resource('s3')
s3.Bucket('mybucket').download_file(src_f, dest_f)
我现在想编写一个单元测试dl()
使用 pytest 并使用中可用的存根模拟与 AWS 的交互botocore https://botocore.amazonaws.com/v1/documentation/api/latest/reference/stubber.html.
@pytest.fixture
def s3_client():
yield boto3.client("s3")
from foo import dl
def test_dl(s3_client):
with Stubber(s3_client) as stubber:
params = {"Bucket": ANY, "Key": ANY}
response = {"Body": "lorem"}
stubber.add_response(SOME_OBJ, response, params)
dl('bucket_file.txt', 'tmp/bucket_file.txt')
assert os.path.isfile('tmp/bucket_file.txt')
我不确定对此的正确方法。我该如何添加bucket_file.txt
到存根响应?我需要什么对象add_response()
至(显示为SOME_OBJ
)?
您是否考虑过使用moto3 https://github.com/spulec/moto?
您的代码可能看起来与现在相同:
# foo.py
def dl(src_f, dest_f):
s3 = boto3.resource('s3')
s3.Bucket('mybucket').download_file(src_f, dest_f)
和测试:
import boto3
import os
from moto import mock_s3
@mock_s3
def test_dl():
s3 = boto3.client('s3', region_name='us-east-1')
# We need to create the bucket since this is all in Moto's 'virtual' AWS account
s3.create_bucket(Bucket='mybucket')
s3.put_object(Bucket='mybucket', Key= 'bucket_file.txt', Body='')
dl('bucket_file.txt', 'bucket_file.txt')
assert os.path.isfile('bucket_file.txt')
代码的意图变得更加明显,因为您只是像往常一样使用 s3,除了方法调用背后没有真正的 s3。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)