I have some code like this
class MyClass:
def my_function(self):
....
return lst
I want to test some other functions calling my_function
. I can't figure out how to set the return_value
for the call of function with specific signature. Is there any way to do that? This can be done very easily with Moq in .Net though...
This is what I tried but it doesn't work.
with patch("MyClass.my_function") as my_mock:
my_mock(1, 2).return_value = [
{
"id" : "A"
}
]
#call the function...
#assert...
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.