小编Sha*_*efe的帖子

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

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

假设在模块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
查看次数

标签 统计

function ×1

mocking ×1

python ×1

python-mock ×1