模拟补丁以错误的顺序出现?

Mock Patches Appearing in the Wrong Order?

我有一个测试模块 (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)            

我正在尝试放置两个模拟 return 值,但它们的效果是相反的。

当我在断点处停止时在交互式控制台中调用它们时——或者在正常调用时检查值——两个模拟函数 return 彼此的假 return 值。从控制台:

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

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

补丁的顺序应该颠倒,因为它们是自下而上应用的。请参阅 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.