Search code examples
pythonamazon-web-servicesboto3python-unittest

Unit testing lambdas which call dynamodb in python


I am having lambdas which use boto3.client() to connect to a dynamoDB.

I tried to test it like this

    @mock.patch("boto3.client")
    def test(self, mock_client, test):

        handler(event, context)

        print(mock_client.call_count) # 1
        print(mock_client.put_item.call_count) # 0

However, the mock_client.call_count is 1, but not the put_item_call_count.

My handler looks like this:

def handler(event, context):
      dynamodb = boto3.client('dynamodb')

         response = dynamodb.put_item(// same attributed) 

Any suggestion, how to test if the correct item gots putted in the database without using moto?


Solution

  • I believe you're very close, there's just one tiny problem.

    When your mocked boto3.client is called, it returns another mock and you want to evaluate that mocks call_count. By accessing the return_value of the original mock, you get access to the created magic mock.

        @mock.patch("boto3.client")
        def test(self, mock_client, test):
    
            handler(event, context)
    
            print(mock_client.call_count)
    
            # .return_value refers to the magic mock that's
            # created when boto3.client is called
            print(mock_client.return_value.put_item.call_count) 
    

    What you're currently evaluating is the call count of boto3.client.put_item and not boto3.client("dynamodb").put_item().