2011-09-28 77 views
47

在unittest的setUp()方法中,我已经设置了一些自我变量,这些变量稍后会在实际测试中引用。我还创建了一个装饰器来做一些日志记录。有没有办法让我可以访问这些self从装饰变量?访问装饰商自我

为了简单起见,我张贴此代码:

def decorator(func): 
    def _decorator(*args, **kwargs): 
     # access a from TestSample 
     func(*args, **kwargs) 
    return _decorator 

class TestSample(unittest.TestCase):  
    def setUp(self): 
     self.a = 10 

    def tearDown(self): 
     # tear down code 

    @decorator 
    def test_a(self): 
     # testing code goes here 

什么是访问一个的最佳方式(在设置中设定())的设计师吗?

回答

79

由于您正在装饰一个方法,并且self是一个方法参数,所以您的装饰器可以在运行时访问self。显然不是在parsetime,因为没有任何对象,只是一个类。

所以你改变你的装饰到:

def decorator(func): 
    def _decorator(self, *args, **kwargs): 
     # access a from TestSample 
     print 'self is %s' % self 
     func(self, *args, **kwargs) 
    return _decorator