Python Mock 多次调用,结果不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23159257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:21:45  来源:igfitidea点击:

Python Mock Multiple Calls with Different Results

pythonmocking

提问by FearlessFuture

I want to be able to have multiple calls to a particular attribute function return a different result for each successive call.

我希望能够对特定属性函数进行多次调用,每次连续调用都返回不同的结果。

In the below example, I would like increment to return 5 on its first call and then 10 on its second call.

在下面的示例中,我希望 increment 在第一次调用时返回 5,然后在第二次调用时返回 10。

Ex:

前任:

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

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.

下面的页面几乎包含了我需要的所有内容,只是它假定调用者是一个名为“mock”的对象,但这不能被假定。

http://mock.readthedocs.org/en/latest/examples.html#multiple-calls-with-different-effects

http://mock.readthedocs.org/en/latest/examples.html#multiple-calls-with-different-effects

采纳答案by Silfheed

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)

回答by Nate Brennand

I think the popping values off of a list method will be more straightforward. The below example works for the test you wanted to perform.

我认为从列表方法中弹出值会更直接。以下示例适用于您要执行的测试。

Also, I've had a difficult time with the mock library before and have found that the mock.patch.object()method was typically easier to use.

此外,我之前在使用模拟库时遇到了困难,并且发现该mock.patch.object()方法通常更易于使用。

import unittest
import mock


class A:
    def __init__(self):
        self.size = 0

    def increment(self, amount):
        self.size += amount
        return amount

incr_return_values = [5, 10]


def square_func(*args):
    return incr_return_values.pop(0)


class TestMock(unittest.TestCase):

    @mock.patch.object(A, 'increment')
    def test_mock(self, A):
        A.increment.side_effect = square_func

        self.assertEqual(A.increment(1), 5)
        self.assertEqual(A.increment(-20), 10)