I want to add a patch annotation to a unit test so that when my boto3 lambda client tries to invoke instead we will get a mock response, but when i try add the patch to my unit test it get the following error AttributeError: <function client at 0x106a38b80> does not have the attribute 'invoke'
Here is the attempted test
@patch("functions.my_function.my_function.boto3.client.invoke")
def test_duck_response_200(self, lambda_mock_response):
mock_response = Mock()
mock_response.status_code = 200
mock_response.content = get_response()
lambda_mock_response.return_value = mock_response
id = "111111111"
response = invoke_lambda(id)
Here is the function
lambda_client = boto3.client("lambda", region)
def invoke_lambda(id):
payload = {"id": 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]
lets say your invoke_lambda
is in my_lambda.py
file. You want to use the patch annotation to mock the lambda_client, not the response. You can then set the return_value
of the mocked_lambda_client
to mocked_response
.
# my_lambda.py
def get_attachment(my_id):
payload = {"myId": my_id}
response = lambda_client.invoke(
FunctionName=os.environ["MY_LAMBDA"],
Payload=json.dumps(payload),
)
return response.status_code
# test_my_lambda.py
@mock.patch("my_lambda.lambda_client")
def test_duck_response_200(mock_lambda_client):
mocked_response = mock.Mock()
mocked_response.status_code = 200
mock_lambda_client.invoke.return_value = mocked_response
response = get_attachment('some_id')
assert response == 200
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.