简体   繁体   中英

How to unit test a boto3 lambda client invoke function

Completely unsure and can't find much information on how to unit test a response from a boto 3 lambda client, especially seen as i need to decode the response that comes back as it is stored in an object. Here is an example of something like the function i would like to unit test

def get_attachment(my_id):
    payload = {"myId": my_id}
    response = lambda_client.invoke(
        FunctionName=os.environ["MY_LAMBDA"],
        Payload=json.dumps(payload),
    )
    response_content = json.loads(response["Payload"].read().decode())
    return response_content["claim"][0]

There are various boto3 mocking efforts:

The response payload is encoded in an object. Specifically, it is a StreamingBody object. Your mock response must also return a StreamingBody object so that it can call .read() and decode it.

import io
import json
import os

import mock
from botocore.response import StreamingBody

@mock.patch.dict(os.environ, {"MY_LAMBDA": "some_lambda"})
@mock.patch("path.to.get_attachment.lambda_client")
def test_get_attachment(mock_lambda_client):
    mocked_response_payload = json.dumps({'claim': ['foobar']}).encode("utf-8")
    mock_lambda_client.invoke.return_value = {'Payload': StreamingBody(io.BytesIO(mocked_response_payload), len(mocked_response_payload))}
    response = get_attachment('some_id')
    assert response == 'foobar'

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