首页 > 解决方案 > 使用实际文件从 s3 模拟下载文件

问题描述

我想编写一个测试来模拟从 s3 下载一个函数,并用我机器上存在的实际文件在本地替换它。我从这篇文章中获得了灵感。思路如下:

from moto import mock_s3
import boto3

def dl(src_f, dest_f):
  s3 = boto3.resource('s3')
  s3.Bucket('fake_bucket').download_file(src_f, dest_f)

@mock_s3
def _create_and_mock_bucket():

    # Create fake bucket and mock it
    bucket = "fake_bucket"

    # We need to create the bucket since this is all in Moto's 'virtual' AWS account
    file_path = "some_real_file.txt"
    s3 = boto3.client("s3", region_name="us-east-1")
    s3.create_bucket(Bucket=bucket)
    s3.put_object(Bucket=bucket, Key=file_path, Body="")

    dl(file_path, 'some_other_real_file.txt')

_create_and_mock_bucket()

现在some_other_real_file.txt存在,但它不是some_real_file.txt. 关于如何做到这一点的任何想法?

标签: pythonunit-testingboto3moto

解决方案


如果您的系统上已存在“some_real_file.txt”,则应改用upload_file: https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.upload_file

对于您的示例:

file_path = "some_real_file.txt"
s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket=bucket)
s3_resource = boto3.resource('s3')
s3_resource.meta.client.upload_file(file_path, bucket, file_path)

您的代码当前在 S3 中创建了一个空文件(因为 Body=""),这正是下载到“some_other_real_file.txt”的内容。请注意,如果您更改 Body 参数以在其中包含一些文本,则该确切内容将下载到“some_other_real_file.txt”。


推荐阅读