Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Patches Appearing in the Wrong Order?

I have a test module (test.py) which imports functions from another module (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)             

I'm trying to put two mock return values in place but their effects are 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]] 

Why are my mock patches appearing in the wrong order?

like image 641
Louise Avatar asked Oct 31 '17 18:10

Louise


People also ask

What is Side_effect in mock python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.

What is MagicMock Python?

MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.

What is Assert_called_with?

assert_called_with() is used to check if the method is called with a particular set of arguments. . assert_called_once_with() is used to check if the method is called with a particular set of arguments.

What does mock patch do?

patch() unittest. mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.


1 Answers

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.

like image 149
physicsGuy Avatar answered Sep 29 '22 09:09

physicsGuy