简体   繁体   中英

How to assert multiple method calls with different parameters each time in python unittest?

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 ie 'ssm', arg1, arg2

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

mock_boto3.client.assert_has_calls([
    call('sts'),
    call('ec2'),
    call('ssm', arg1, arg2)
])

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