如何解决S3 单元测试 boto 客户端
在为 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}"
)
解决方法
不接受这是一个答案,但对最终到这里的任何人都有用,我找到了一种解决方法,如果我在尝试测试的函数中创建 s3 客户端,那么这种方法将起作用,而不是全局创建它。不过,我更愿意找到一个实际的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。