将 2+ mock.patch 组为一组
group 2+ mock.patch into one
假设我有:
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):
...
可以使用一个函数,将要修补的目标对象作为参数,returns一个装饰器函数,遍历目标对象,使用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
假设我有:
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):
...
可以使用一个函数,将要修补的目标对象作为参数,returns一个装饰器函数,遍历目标对象,使用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