montestypatching boto3 s3调用pytest

问题描述 投票:0回答:1

我想使用pytest测试save_doc函数并模拟下面的调用

    boto3.resource('s3').Object(bucket_name, key).put(Body=json.dumps(body))

我试图找出如何使用“补丁”装饰器来模拟这个调用。有什么例子/指针我可以看一下吗?

def save_doc(doc_id, body):

    bucket_name = os.environ['bucket_name']
    key = '{}{}.json'.format(os.environ['key'], doc_id)

    boto3.resource('s3').Object(bucket_name, key).put(Body=json.dumps(body))
python python-3.x amazon-web-services pytest monkeypatching
1个回答
1
投票

以下测试用例适用于问题中发布的场景

@mock_s3
def test_save_doc(doc_id, body):
    bucket_name = os.environ['bucket_name']
    key = os.environ['key']
    conn = boto3.resource('s3', region_name='us-east-1')
    conn.create_bucket(Bucket=bucket_name)
    save_doc(doc_id, body)
    response = conn.Object(bucket_name, key).get()['Body'].read().decode("utf-8")
    assert body == response
© www.soinside.com 2019 - 2024. All rights reserved.