2

我目前有以下要测试的基本 Python 类:

class Example:

    def run_steps(self):
        self.steps = 0

        while self.steps < 4:
            self.step()
    
    def step(self):
        # some expensive API call
        print("wasting time...")
        time.sleep(1000)

        self.steps += 1

正如你所看到的, step() 方法包含一个昂贵的 API 调用,所以我想用另一个函数来模拟它,避免昂贵的 API 调用但仍然增加self.steps。我发现这样做是可能的(从这里可以看出):

def mock_step(self):
    print("skip the wasting time")
    self.steps += 1

# This code works!
def test(mocker):
    example = Example()
    mocker.patch.object(Example, 'step', mock_step)

    example.run_steps()

我只是创建了一个mock_step(self)避免 API 调用的函数,并step()用新mock_step(self)函数修补了原来的慢速方法。

然而,这导致了一个新的问题。由于该mock_step(self)函数不是 Mock 对象,因此我无法在其上调用任何 Mock 方法(例如 assert_call() 和 call_count()):

def test(mocker):
    example = Example()
    mocker.patch.object(Example, 'step', mock_step)

    example.run_steps()

    # this line doesn't work
    assert mock_step.call_count == 4

为了解决这个问题,我尝试mock_step使用参数包装一个 Mock 对象wraps

def test(mocker):
    example = Example()

    # this doesn't work
    step = mocker.Mock(wraps=mock_step)
    mocker.patch.object(Example, 'step', step)

    example.run_steps()

    assert step.call_count == 4

但后来我得到一个不同的错误说mock_step() missing 1 required positional argument: 'self'

因此,从这个阶段开始,我不确定如何断言step()run_steps().

4

2 回答 2

0
import unittest.mock as mock
from functools import partial


def fake_step(self):
    print("faked")
    self.steps += 1


def test_api():
    api = Example()
    with mock.patch.object(api, attribute="step", new=partial(fake_step, self=api)):
        # we need to use `partial` to emulate that a real method has its `self` parameter bound at instantiation
        api.run_steps()
    assert api.steps == 4

正确输出"faked"4 次。

于 2021-06-02T06:48:22.727 回答
0

有几种解决方案,最简单的可能是使用具有副作用的标准模拟:

def mock_step(self):
    print("skip the wasting time")
    self.steps += 1


def test_step(mocker):
    example = Example()
    mocked = mocker.patch.object(Example, 'step')
    mocked.side_effect = lambda: mock_step(example)
    example.run_steps()
    assert mocked.call_count == 4

side_effect可以采用可调用对象,因此您可以同时使用标准模拟和修补方法。

于 2021-06-02T06:37:21.357 回答