如何在 python 单元测试中每次使用不同参数断言多个方法调用?

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

我正在使用 python unittest 来测试我的代码。作为我代码的一部分,我正在使用这些

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

所以我在编写测试用例之前模拟了 boto3,并将其作为参数。 现在我可以断言 boto3.client 是否被调用了。

但我想检查 boto3.client 是否使用 sts 调用,boto3.client 是否使用 ec2 和 ssm,arg1,arg2 调用。

当我只能使用 boto3.client.assert_called_with('my parameters') 进行一次调用时。但面临每次使用不同参数检查多个调用的问题。

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

我想达到这样的效果

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)

但这只在第一个断言中给出错误,说 boto3.client 调用了 3 次,它显示的是最后一次调用的参数,即 'ssm'、arg1、arg2

如果要验证对同一个 mock 的多次调用,可以使用 assert_has_calls with call。在你的情况下:

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