Skip to main content
 首页 » 编程设计

python之检查提供给另一个可调用参数的参数

2024年11月01日10artech

我有一个函数可以调用。在我的测试中,我想检查这个函数的调用和参数。

由于函数是在参数中给出的而不是导入的,所以我无法模拟它(或者我没有找到正确的方法)。

然而,我模拟了一个输入函数,因为它不会在运行时使用,所以我知道它不会破坏任何东西。

它运行良好,但我觉得它不是真正的 Pythonic。

是否有另一种方法可以让我可以检查调用号和参数(如模拟)?

这里是工作代码,文件 package/my_file.py 具有函数

from typing import Callable, List 
 
def generate_calls(function_to_call: Callable, arguments_to_give: List[int]): 
    for an_argument in arguments_to_give: 
        function_to_call(arg_1=an_argument) 

测试文件:

from package.my_file import generate_calls 
 
 
def test_call_with_arguments(mocker): 
   a_list = [1, 2, 3] 
   called_function = mocker.patch('package.my_file.Callable') 
   generate_calls(called_function, a_list) 
   # get the argument of the mock function when called 
   argument_dict = [one_call[1] for one_call in called_function.call_args_list] 
   assert argument_dict == [{'arg_1': 1}, {'arg_1': 2}, {'arg_1': 3}] 

请您参考如下方法:

您可以直接将 MagicMock 对象传递到测试中的 generate_calls 中。使用类似下面的模式

from unittest.mock import MagicMock 
 
def call_with_1(fun): 
    fun(1) 
 
def test_called(): 
    mock_fun = MagicMock() 
    call_with_1(mock_fun) 
    mock_fun.assert_called_with(1) 
    assert mock_fun.call_count == 1