您可以使用装饰器,但可以通过编程方式使用,因此无需在每种方法中都放置装饰器。
我在下一个代码中假设了几件事:
测试方法都被命名为:“ testXXX()”装饰器添加到实现测试方法的模块中。
def test1():
print ("Testing hello world")
def test2():
print ("Testing hello world 2")
#This is the decorator
class TestChecker(object):
def __init__(self, testfn, *args, **kwargs):
self.testfn = testfn
def pretest(self):
print ('precheck %s' % str(self.testfn))
def posttest(self):
print ('postcheck %s' % str(self.testfn))
def __call__(self):
self.pretest()
self.testfn()
self.posttest()
for fn in dir() :
if fn.startswith('test'):
locals()[fn] = TestChecker(locals()[fn])
现在,如果您调用测试方法...
test1()
test2()
输出应该是这样的:
precheck
Testing hello world
postcheck
precheck
Testing hello world 2
postcheck
如果将测试方法作为类方法,则该方法也是有效的。 例如:
class TestClass(object):
@classmethod
def my_test(cls):
print ("Testing from class method")
for fn in dir(TestClass) :
if not fn.startswith('__'):
setattr(TestClass, fn, TestChecker(getattr(TestClass, fn)))
拨打TestClass.my_test()的电话将打印:
precheck >
Testing from class method
postcheck >