简体   繁体   中英

monkeypatching boto3 s3 call in pytest

I want to test the save_doc function using pytest and mock the below call

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

I am trying to figure out how i can use the "patch" decorator to mock this call. Are there any examples / pointers that I can look at?

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))

The below test case works for the scenario posted in the questions

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM