相关疑难解决方法(0)

检查多个模拟中的呼叫顺序

我有三个函数,我正在尝试测试它的调用顺序.

假设在模块module.py中我有以下内容

# module.py    

def a(*args):
    # do the first thing

def b(*args):
    # do a second thing

def c(*args):
    # do a third thing


def main_routine():
    a_args = ('a')
    b_args = ('b')
    c_args = ('c')

    a(*a_args)
    b(*b_args)
    c(*c_args)
Run Code Online (Sandbox Code Playgroud)

我想检查b在a之后和c之前被调用.因此,对a,b和c中的每一个进行模拟很容易:

# tests.py

@mock.patch('module.a')
@mock.patch('module.b')
@mock.patch('module.c')
def test_main_routine(c_mock, b_mock, a_mock):
    # test all the things here
Run Code Online (Sandbox Code Playgroud)

检查每个单独的模拟被调用也很容易.如何检查呼叫相对于彼此的顺序?

call_args_list 不会工作,因为它是为每个模拟单独维护.

我尝试使用副作用来记录每个调用:

calls = []
def register_call(*args):
    calls.append(mock.call(*args))
    return mock.DEFAULT

a_mock.side_effect = register_call
b_mock.side_effect = register_call
c_mock.side_effect = register_call
Run Code Online (Sandbox Code Playgroud)

但是这只能给我一些嘲笑的诅咒,而不是实际的嘲笑.我可以添加更多逻辑:

# tests.py
from …
Run Code Online (Sandbox Code Playgroud)

python function mocking python-mock

29
推荐指数
2
解决办法
4122
查看次数

如何使用Python Mock断言方法调用顺序?

假设我有一个python函数

def func(self):
    self.method_1()
    self.method_2()
Run Code Online (Sandbox Code Playgroud)

如何在method_2之前编写可以断言method_1的单元测试?

@mock.patch(method_1)
@mock.patch(method_2)
def test_call_order(method_2_mock, method_1_mock):
     # Test the order
Run Code Online (Sandbox Code Playgroud)

python mocking

5
推荐指数
1
解决办法
4312
查看次数

标签 统计

mocking ×2

python ×2

function ×1

python-mock ×1