Python模拟具有不同结果的多次调用 [英] Python Mock Multiple Calls with Different Results
问题描述
我希望能够对特定属性函数进行多次调用,每次后续调用都返回不同的结果.
I want to be able to have multiple calls to a particular attribute function return a different result for each successive call.
在下面的示例中,我希望增量在其第一次调用时返回5,然后在其第二次调用时返回10.
In the below example, I would like increment to return 5 on its first call and then 10 on its second call.
例如:
import mock
class A:
def __init__(self):
self.size = 0
def increment(self, amount):
self.size += amount
return amount
@mock.patch("A.increment")
def test_method(self, mock_increment):
def diff_inc(*args):
def next_inc(*args):
#I don't know what belongs in __some_obj__
some_obj.side_effect = next_inc
return 10
return 5
mock_increment.side_effect = diff_inc
下面的页面几乎包含了我需要的所有内容,但它假定调用者将是一个名为"mock"的对象,但这不能假定.
The below page has almost everything that I need except that it assumes that the caller would be an object named "mock", but this can't be assumed.
http://mock.readthedocs. org/en/latest/examples.html#multiple-calls-with-different-effects
推荐答案
您可以传递一个可迭代的副作用,并在每次调用的值列表中进行迭代.
You can just pass an iterable to side effect and have it iterate through the list of values for each call you make.
@mock.patch("A.increment")
def test_method(self, mock_increment):
mock_increment.side_effect = [5,10]
self.assertEqual(mock_increment(), 5)
self.assertEqual(mock_increment(), 10)
这篇关于Python模拟具有不同结果的多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!