在这基础上,稍作改动,给加上了setup和teardown。
废话不多说,直接上代码
import unittest def log(s, t, n): def decorator(xingfangfa): print xingfangfa def wrapper(*a,**w): for i in range(n): try: print '-------------------\nNum:', i re = xingfangfa(*a,**w) print 'success \n-------------------' return re except Exception: print 'have a error ' t(*a) s(*a) print '\n-------------------' raise Exception return wrapper return decorator class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls.abc = 0 def setUp(self): print 'I am setup','abc:',self.abc def tearDown(self): print 'I am tearDown','abc:',self.abc @log(setUp,tearDown,5) def test1(self,q=2): self.abc += 1 print 'do case: ', assert self.abc == 3 if __name__ == '__main__': unittest.main()
其中 n 表示最大重跑5次
把setUp tearDown当作参数给 重跑装饰器
重跑装饰器相对于传统装饰器增加最外层控制器