【问题标题】:group 2+ mock.patch into one将 2+ mock.patch 组合成一个
【发布时间】:2019-09-19 22:01:00
【问题描述】:

说我有:

import mock
...

@mock.patch("function_1")
@mock.patch("function_2")
def my_test(self, f1, f2):
    f1.return_value="foo"
    f2.return_value="bar"
    ...

function_1 和 function_2 非常相似,并在多个测试函数中进行了模拟。我很想模块化这种模式(修补两个功能)。有没有这样的方法?理想的结果如下所示。

@grouppatch("function_1_and_2")
def my_test(self):
    ...

【问题讨论】:

  • 你可以编写自己的装饰器,它需要一个函数名称列表来修补,然后修补每个。如果您真的想使用像“function_1_and_2”这样的字符串(在 imo 中看起来很麻烦),您可以自己将其解析为两个函数名并分别修补。

标签: python unit-testing testing python-mock


【解决方案1】:

您可以使用将要修补的目标对象作为参数的函数,并返回一个装饰器函数,该函数遍历目标对象以使用mock.patch 修补装饰函数的对象:

def grouppatch(*targets):
    def decorator(func):
        for target in targets:
            func = mock.patch(target)(func)
        return func
    return decorator

这样:

@grouppatch('builtins.bool', 'builtins.int')
def my_test(mock_bool, mock_int):
    mock_bool.return_value = True
    mock_int.return_value = 100
    print(bool(False), int(10))

my_test()

输出:

True 100

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多