Mocking python function based on input arguments(基于输入参数模拟python函数)
问题描述
我们一直在使用 Mock for 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_func
是一个函数,那么该函数返回的是什么叫模拟返回.side_effect_func
函数被调用与模拟相同的论点.这允许您改变回报根据输入动态调用的值:
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
这篇关于基于输入参数模拟python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于输入参数模拟python函数


- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01