Python模拟具有不同结果的多个调用

Fea*_*ure 26 python mocking

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

在下面的例子中,我想在第一次调用时增加返回5,然后在第二次调用时返回10.

例如:

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
Run Code Online (Sandbox Code Playgroud)

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

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

Sil*_*eed 45

您可以将迭代传递给副作用,并让它遍历您进行的每个调用的值列表.

@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)
Run Code Online (Sandbox Code Playgroud)

  • 另外,这似乎有效:`@mock.patch("A.increment", side_effect=[5, 10])` (9认同)

Nat*_*and 6

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

另外,我之前在使用模拟库时遇到了困难,并且发现该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)
Run Code Online (Sandbox Code Playgroud)


Bin*_* Ho 6

我测试过,这应该可以工作

import mock

...
...

@mock.patch.object(ClassB, 'method_2')
@mock.patch.object(ClassA, 'method_1')
def test_same_method_multi_return_value(self, method_1, method_2):
    # type: () -> None

    method_1.return_value = 'Static value'
    method_1.side_effect = [
        'Value called by first time'
        'Value called by second time'
        '...'
    ]

Run Code Online (Sandbox Code Playgroud)

版本

https://mock.readthedocs.io/en/latest/
mock>=2.0.0,<3.0
Run Code Online (Sandbox Code Playgroud)