基于输入参数模拟python函数

Mocking python function based on input arguments(基于输入参数模拟python函数)
本文介绍了基于输入参数模拟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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)