基于输入参数模拟python函数

时间:2022-10-18
本文介绍了基于输入参数模拟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. 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

这篇关于基于输入参数模拟python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:我如何检查调用参数是否会随 unittest.mock 改变 下一条:修补类会产生“AttributeError:Mock object has no attribute";访问实

相关文章

最新文章