Search code examples
pythonpython-3.xamazon-web-servicespytestmonkeypatching

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

Solution

  • 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