我已经搜索过了,但是我看到的结果却恰恰相反:对一个函数应用多个decorator。
我想简化这个模式。有没有一种方法可以将这个单一的decorator应用到多个函数如果没有,我如何重写上面的内容以减少重复?
from mock import patch
@patch('somelongmodulename.somelongmodulefunction')
def test_a(patched):
pass # test one behavior using the above function
@patch('somelongmodulename.somelongmodulefunction')
def test_b(patched):
pass # test another behavior
@patch('somelongmodulename.somelongmodulefunction')
def test_c(patched):
pass # test a third behavior
from mock import patch
patched_name = 'somelongmodulename.somelongmodulefunction'
@patch(patched_name)
def test_a(patched):
pass # test one behavior using the above function
@patch(patched_name)
def test_b(patched):
pass # test another behavior
@patch(patched_name)
def test_c(patched):
pass # test a third behavior
最佳答案
如果您只想让“long”函数调用一次,并用结果装饰所有三个函数,只需这样做。
my_patch = patch('somelongmodulename.somelongmodulefunction')
@my_patch
def test_a(patched):
pass
@my_patch
def test_b(patched):
pass