【问题标题】:S3 unit tests boto clientS3 单元测试 boto 客户端
【发布时间】:2021-02-18 13:02:27
【问题描述】:

在为 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}"
    )

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 另一种方法是在测试函数中导入您正在测试的模块。在这两种情况下,boto3-client 都是在 mock 建立后创建的,这是 moto 工作的要求。见github.com/spulec/moto/blob/master/…
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多