[英]How to setup return_value for a function call with specific signature?
I have some code like this 我有一些这样的代码
class MyClass:
def my_function(self):
....
return lst
I want to test some other functions calling my_function
. 我想测试其他一些调用
my_function
函数。 I can't figure out how to set the return_value
for the call of function with specific signature. 我不知道如何为具有特定签名的函数调用设置
return_value
。 Is there any way to do that? 有什么办法吗? This can be done very easily with Moq in .Net though...
不过,使用.Net中的Moq可以非常轻松地完成此操作...
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
. 您在该行中所做的实际上是为通过调用
my_mock
返回的另一个模拟对象设置return_value。 The value you've assigned there will be returned if you execute m()()
, not m(1, 2)
as you probably expected. 如果执行
m()()
而不是您可能期望的m(1, 2)
m()()
,则会返回您在其中分配的值。
return_value
doesn't depend on the call signature and should be used like this: return_value
不依赖于呼叫签名,应该这样使用:
>>> 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
: 如果希望返回值取决于调用参数,则应使用
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 . 顺便说一句,我更喜欢用patch.object修补方法。 I don't think
patch("MyClass.my_function")
will work because patch()
requires target to start with package/module name. 我不认为
patch("MyClass.my_function")
会起作用,因为patch()
要求目标以包/模块名称开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.