問題描述
我們一直在使用 Mock for python.
We have been using Mock for python for a while.
現(xiàn)在,我們要模擬一個函數(shù)
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
通常,模擬它的方法是(假設(shè) foo 是對象的一部分)
Normally, the way to mock this would be (assuming foo being part of an object)
self.foo = MagicMock(return_value="mocked!")
即使我調(diào)用 foo() 幾次我也可以使用
Even, if i call foo() a couple of times i can use
self.foo = MagicMock(side_effect=["mocked once", "mocked twice!"])
現(xiàn)在,我面臨一種情況,當(dāng)輸入?yún)?shù)具有特定值時,我想返回一個固定值.因此,如果假設(shè)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 實現(xiàn)同樣的目標,但沒有成功?
I have been searching on how to achieve the same with Mock with no success?
有什么想法嗎?
推薦答案
如果
side_effect_func
是一個函數(shù),那么該函數(shù)返回的是什么叫模擬返回.side_effect_func
函數(shù)被調(diào)用與模擬相同的論點.這允許您改變回報根據(jù)輸入動態(tài)調(diào)用的值:
If
side_effect_func
is a function then whatever that function returns is what calls to the mock return. Theside_effect_func
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_func(value):
... return value + 1
...
>>> m = MagicMock(side_effect=side_effect_func)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]
http://www.voidspace.org.uk/python/模擬/mock.html#calling
這篇關(guān)于基于輸入?yún)?shù)模擬python函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!