Why are my Python mock patches appearing in the wr

2019-06-16 22:47发布

I have a module test.py which is importing functions from another module, keyboard.py, using from keyboard import *.

Inside keyboard.py there are two functions:

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

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

Now, my test function, in test.py, looks like this:

    @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)

As you can see, I'm trying to put two mock return values in place.

However, their effects seem to be inversed!

When I call them in the interactive console while stopped at a breakpoint (or inspect the values when called normally), the two mocked functions return each other's fake return values!

From the console:

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

Am I misunderstanding something about the order of mock arguments being passed to the test function?

Could it be something to do with patching keyboard.get_keys rather than test.get_keys?

Thanks! Louise

1条回答
放我归山
2楼-- · 2019-06-16 23:31

The order of your patches should be reversed, as they are applied bottom up. See this comment in the python docs on nested mock arguments:

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.

查看更多
登录 后发表回答