Search code examples
pythondjangopatchpytestpython-mock

How to mock in python and still allow the actual code of mocked function to execute


I have recently started using the mock framework in python. It seems that if I patch a function, the actual code is not called - which means that the database changes etc that this actual function does is not implemented. I have been trying to go around it by calling the function before hand and storing the return value and passing it as arg in patch(), but is there a better way to do it? Ideally, I would want a code that works as a silent observer and i can simply ask it if a certain observed function was called or not, how many times, and with what arguments

My current code

return_val = funct()

# C: Now call me again and assert that these intensive computation functions are not called but taken from cache
with patch('funct', return_value=return_val) as mock_task:

    me_response = self.client.get(me_url, format='json')    #should fetch from cache
    assert not mock_task.called

Solution

  • You could set the Mock#side_effect attribute to your original function.

    orig = funct
    funct = Mock(side_effect=orig)
    

    I do find loganasherjones' answer more elegant.

    Just adding another possibility for those who may need it.