S3 单元测试 boto 客户端

时间:2021-02-18 13:02:27

标签: python unit-testing amazon-s3 boto moto

在为 S3 客户端编写单元测试时遇到问题,似乎该测试正在尝试使用真正的 s3 客户端,而不是我为测试创建的客户端,这里是我的示例

    @pytest.fixture(autouse=True)
    def moto_boto(self):
        # setup: start moto server and create the bucket
        mocks3 = mock_s3()
        mocks3.start()
        res = boto3.resource('s3')
        bucket_name: str = f"{os.environ['BUCKET_NAME']}"
        res.create_bucket(Bucket=bucket_name)
        yield
        # teardown: stop moto server
        mocks3.stop()

    def test_with_fixture(self):
        from functions.s3_upload_worker import (
            save_email_in_bucket,
        )
        client = boto3.client('s3')
        bucket_name: str = f"{os.environ['BUCKET_NAME']}"
        client.list_objects(Bucket=bucket_name)
      
        save_email_in_bucket(
                "123AZT",
                os.environ["BUCKET_FOLDER_NAME"],
                email_byte_code,
            )

这会导致以下错误

botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the PutObject operation: The provided token has expired.

我正在测试的代码看起来像这样

def save_email_in_bucket(message_id, bucket_folder_name, body):
    s3_key = "".join([bucket_folder_name, "/", str(message_id), ".json"])
    s3_client.put_object(
        Bucket=bucket,
        Key=s3_key,
        Body=json.dumps(body),
        ContentType="application-json",
    )
    LOGGER.info(
        f"Saved email with messsage ID {message_id} in bucket folder {bucket_folder_name}"
    )

1 个答案:

答案 0 :(得分:1)

不接受这是一个答案,但对最终到这里的任何人都有用,我找到了一种解决方法,如果我在尝试测试的函数中创建 s3 客户端,那么这种方法将起作用,而不是全局创建它。不过,我更愿意找到一个实际的解决方案。