模拟boto3响应,用于从S3下载文件

时间:2019-10-25 19:08:41

标签: python amazon-web-services amazon-s3 boto3 botocore

我有使用boto3从S3存储桶下载文件的代码。

# foo.py
def dl(src_f, dest_f):
  s3 = boto3.resource('s3')
  s3.Bucket('mybucket').download_file(src_f, dest_f)

我现在想使用pytest编写dl()的单元测试,并使用botocore中可用的存根来模拟与AWS的交互。

@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)?

1 个答案:

答案 0 :(得分:2)

您是否考虑过使用moto3
您的代码看起来可能与现在相同:

# 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。