基于输入参数模拟python函数

2022-01-08 00:00:00 python mocking unit-testing mockito

问题描述

我们一直在使用 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. The side_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

相关文章