在unittest的setUp()方法中我设置了一些self变量,稍后在实际测试中引用。我还创建了一个装饰器来进行一些日志记录。有什么方法可以访问这些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
最好的访问方式是什么a(在 setUp() 中设置)来自装饰器?
既然你正在装饰一个方法,并且self
是一个方法参数,你的装饰器可以访问self
在运行时。显然不是在解析时,因为还没有对象,只是一个类。
所以你将你的装饰器更改为:
def decorator(func):
def _decorator(self, *args, **kwargs):
# access a from TestSample
print 'self is %s' % self
return func(self, *args, **kwargs)
return _decorator
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)