如果使用不同的属性多次调用方法,如何模拟方法?

She*_*har 2 python unit-testing mocking fabric

我正在为基于 Python 和 Fabric 的代码编写单元测试。我有以下方法,该方法依次使用sudo不同的参数多次调用 Fabric API 的方法。我想知道如何在模拟sudo对象上调用断言。

**main_file.py**

from fabric.api import sudo

def do_something(path_to_file_to_be_copied, destination_path):
    # remove file if already exists
    sudo('rm ' + path_to_file_to_be_copied, warn_only=True)
    sudo('cp ' + path_to_file_to_be_copied + ' ' + destination_path)
Run Code Online (Sandbox Code Playgroud)

我编写了如下测试文件:

**test_main_file.py**

import main_file

class MainFileTest(unittest.TestCase):

    @mock.patch('main_file.sudo')
    def test_do_something(self, mock_sudo):
        file_path = '/dummy/file/path.txt'
        dest_dir = '/path/to/dest/dir'
        main_file.do_something(file_path, dest_dir)
        mock_sudo.assert_called_with('rm ' + file_path)
Run Code Online (Sandbox Code Playgroud)

上面的测试失败,因为模拟对象只记住最后一次调用。也就是说,如果我写mock_sudo.assert_called_with(cp + file_path + ' ' + dest_dir) ,那么测试就会失败。

我如何断言这两个调用sudo

Mac*_*Gol 5

尝试assert_any_call断言是否有任何呼叫,而不仅仅是最近的呼叫。

或者,您可以使用它call_args_list来获取调用模拟时使用的参数列表。