为什么我的Python模拟补丁以错误的顺序出现?

前端之家收集整理的这篇文章主要介绍了为什么我的Python模拟补丁以错误的顺序出现?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个模块test.py,它使用键盘导入*从另一个模块keyboard.py导入函数.

在keyboard.py里面有两个功能

def get_keys(keyList,timeStamped):
    return event.getKeys(keyList=keyList,timeStamped=timeStamped)

def wait_keys(keyList,timeStamped):
    return event.waitKeys(keyList=keyList,timeStamped=timeStamped)

现在,我在test.py中的测试函数如下所示:

@mock.patch('keyboard.wait_keys')
    @mock.patch('keyboard.get_keys')
    def test_2(self,mock_waitKeys,mock_getKeys):

        mock_waitKeys.return_value = [['wait_keys!',0.1]]
        mock_getKeys.return_value = [['get_keys!',0.1]]

        run_blocks(trials,noise,win,expInfo,incorrect,tone1,tone2,experiment_details,allPoints,32,60)

正如您所看到的,我正在尝试将两个模拟返回值放在适当的位置.

然而,他们的影响似乎是倒置的!

当我在交互式控制台中调用它们而在断点处停止时(或在正常调用时检查值),两个模拟函数返回彼此的假返回值!

从控制台:

get_keys()
Out[2]: [['wait_keys!',0.1]]
wait_keys()
Out[3]: [['get_keys!',0.1]]

我是否误解了传递给测试函数的模拟参数的顺序?

这可能与修补keyboard.get_keys而不是test.get_keys有关吗?

谢谢!
路易丝

解决方法

补丁的顺序应该颠倒,因为它们是自下而上应用的.在嵌套模拟参数的 python docs中查看此注释:

Note When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal python order that decorators are applied). This means from the bottom up,so in the example above the mock for module.ClassName1 is passed in first.

猜你在找的Python相关文章