kev*_*vin 68 python unit-testing scope
在unittest的setUp()方法中,我设置了一些自变量,稍后在实际测试中引用.我还创建了一个装饰器来做一些日志记录.有没有办法可以从装饰器访问这些自变量?
为简单起见,我发布此代码:
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
Run Code Online (Sandbox Code Playgroud)
什么是访问的最好办法一个从装饰(()在设置中设定)?
Dav*_*ave 104
由于您正在装饰方法,并且self是方法参数,因此装饰器可以self在运行时访问.显然不是在解析时,因为还没有对象,只是一个类.
所以你将装饰师改为:
def decorator(func):
def _decorator(self, *args, **kwargs):
# access a from TestSample
print 'self is %s' % self
func(self, *args, **kwargs)
return _decorator
Run Code Online (Sandbox Code Playgroud)