4

I am using python unittest to test my code. As part of my code, I am using these

boto3.client('sts')
boto3.client('ec2')
boto3.client('ssm', arg1, arg2)

So I mocked boto3 before writing my test case, and taking it as argument. Now I can assert whether boto3.client called or not.

But I want to check whehter boto3.client called with sts and boto3.client called wit ec2 and with ssm,arg1,arg2.

When there is only one call I was able to do using boto3.client.assert_called_with('my parameters'). But facing issue to check multiple calls with different parameters each time.

@patch('createCustomer.src.main.boto3')
    def test_my_code(self, mock_boto3):
        # Executing main class
        mainclass(arg1, arg2)
        # Verifing
        mock_boto3.client.assert_called()

I want to achieve like

mock_boto3.client.assert_called_once_with('sts')
mock_boto3.client.assert_called_once_with('ec2')
mock_boto3.client.assert_called_once_with('ssm',arg1,arg2)

But this is giving error in first assert only, saying boto3.client called 3 times and parameters it is showing of last call i.e. 'ssm', arg1, arg2

1 Answer 1

8

If you want to verify multiple calls to the same mock, you can use assert_has_calls with call. In your case:

from unittest.mock import call

mock_boto3.client.assert_has_calls([
    call('sts'),
    call('ec2'),
    call('ssm', arg1, arg2)
])
Sign up to request clarification or add additional context in comments.

3 Comments

is this call is part of syntax? If I am writing call('sts'), it is giving syntax error, unresolved reference to call / name call is not defined. But when I check has_calls expected parameters it contains call('st's)
@venkat do you mean a NameError? Like patch, call is part of unittest.mock; you'll have to import it from that module similarly.
ohh! got it. I did, from unittest.mock import call and it worked. Previously I am just importing patch and MagicMock

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.