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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With