'How to write pytest for boto3 lambda invoke when it is defined inside a function

I am trying to write pytest to test the following method by mocking the boto3 client. I tried with sample test case. I am not sure if that is right way to do it. Please correct me if I am wrong.

//temp.py

import boto3
import json


def temp_lambda(event):
    client_lam = boto3.client('lambda', region_name="eu-west-1")  #defined inside the function.

    obj = client_lam.invoke(
        FunctionName='XYZ',
        InvocationType='ABC',
        Payload=json.dumps({'payload': event}))

    return obj

//test_temp.py

import mock
from unittest.mock import MagicMock, patch
from .temp import temp_lambda

@mock.patch("boto3.client")
def test_temp_lambda(mock_lambda_client):
    mocked_response = MagicMock(return_value = 'yes')
    mock_lambda_client.invoke.return_value = mocked_response.return_value
    event = {}
    x = temp_lambda(event)
    assert x == 'yes'

I am getting assertion error in output

AssertionError: assert <MagicMock name='client().invoke()' id='2557742644480'> == 'yes'


Solution 1:[1]

The golden rule of the mock framework is that you mock where the object is used not where it's defined.

So it would be @mock.patch('temp.boto3.client')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 P4L