my_mock(1, 2).return_value = value
What you are doing with that line is actually setting the return_value for another mock object returned by call to my_mock
. The value you've assigned there will be returned if you execute m()()
, not m(1, 2)
as you probably expected.
return_value
doesn't depend on the call signature and should be used like this:
>>> my_mock.return_value = 'foobar'
>>> my_mock()
'foobar'
>>> my_mock(1, 2)
'foobar'
If you want the return value to depend on call arguments, you should use side_effect
:
>>> def mock_func(*args):
... if args == (1, 2):
... return 'foo'
... else:
... return 'bar'
...
>>> my_mock.side_effect = mock_func
>>> my_mock(1, 2)
'foo'
>>> my_mock()
'bar'
BTW, I prefer to patch methods with patch.object. I don't think patch("MyClass.my_function")
will work because patch()
requires target to start with package/module name.