Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mock library: Is there any way to get corresponding return values from magic mock calls?

When writing Python tests with the mock library, I often get "what arguments a method is called with" like this,

from __future__ import print_function
import mock

m = mock.MagicMock(side_effect=lambda x: x * x)
m(4)
print("m called with: ", m.call_args_list)

(this will print m called with: [call(4)]). Question: Is there any way to get the return value (in this case, 16)?

Details: In my particular scenario, I want to use side_effect to return a sub-mock object: introspecting that object to see what is called on it is important. For example, the "real code" (non-test code) might write,

myobj = m(4)
myobj.foo()

Using side_effect seems like a convenient way to return new sub-mock objects, but also keep around call_args_list. However, it doesn't seem like MagicMock stores return values from the side_effect function ... am I wrong?

like image 759
gatoatigrado Avatar asked Nov 12 '22 00:11

gatoatigrado


1 Answers

What about the wraps parameter?

class MyClass:
    def foo(self, x):
        return(x * x)

then you can assert a call like this:

my_obj = MyClass()
with patch.object(MyClass, 'foo', wraps=MyClass().foo) as mocked_foo:
    my_result = my_obj.foo(4)
    mocked_foo.assert_called_with(4)    

and my_result will contain the actual result of invoking foo()

like image 127
Federico Giraldi Avatar answered Nov 14 '22 23:11

Federico Giraldi