根据输入参数模拟python函数 [英] Mocking python function based on input arguments
问题描述
一段时间以来,我们一直在为Python使用模拟.
We have been using Mock for python for a while.
现在,我们需要模拟一个函数
Now, we have a situation in which we want to mock a function
def foo(self, my_param):
#do something here, assign something to my_result
return my_result
通常,模拟此方法的方式是(假设foo是对象的一部分)
Normally, the way to mock this would be (assuming foo being part of an object)
self.foo = MagicMock(return_value="mocked!")
即使我多次调用foo()也可以使用
Even, if i call foo() a couple of times i can use
self.foo = MagicMock(side_effect=["mocked once", "mocked twice!"])
现在,我正面临一种情况,当输入参数具有特定值时,我想返回一个固定值.因此,如果说"my_param"等于"something",那么我想返回"my_cool_mock"
Now, I am facing a situation in which I want to return a fixed value when the input parameter has a particular value. So if let's say "my_param" is equal to "something" then I want to return "my_cool_mock"
似乎可以在 mockito for python
when(dummy).foo("something").thenReturn("my_cool_mock")
我一直在寻找如何通过Mock实现相同的目标而没有成功?
I have been searching on how to achieve the same with Mock with no success?
有什么想法吗?
推荐答案
如果
side_effect
是一个函数,则该函数返回的值是 模拟返回的调用方式.side_effect
函数使用 与模拟相同的论点.这使您可以改变回报 根据输入动态调用的值:
If
side_effect
is a function then whatever that function returns is what calls to the mock return. Theside_effect
function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:
>>> def side_effect(value):
... return value + 1
...
>>> m = MagicMock(side_effect=side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]
http://www.voidspace.org.uk/python/mock/mock.html #calling
这篇关于根据输入参数模拟python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!