pytest 中的 monkeypatching boto3 s3 调用
monkeypatching boto3 s3 call in pytest
我想使用 pytest 测试 save_doc 函数并模拟下面的调用
boto3.resource('s3').Object(bucket_name, key).put(Body=json.dumps(body))
我想弄清楚如何使用 "patch" 装饰器来模拟此调用。有没有我可以看的例子/指针?
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))
以下测试用例适用于问题中发布的场景
@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
我想使用 pytest 测试 save_doc 函数并模拟下面的调用
boto3.resource('s3').Object(bucket_name, key).put(Body=json.dumps(body))
我想弄清楚如何使用 "patch" 装饰器来模拟此调用。有没有我可以看的例子/指针?
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))
以下测试用例适用于问题中发布的场景
@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