在这种情况下,我想获取使用python 2.7运行的当前活动/正在运行的unittest。从下面的示例代码可以看到,我不希望curTestEnv存在。我也不希望setUp()方法存在。我只是想动态获取当前的测试环境,并通过调用该类的id()方法来请求其测试名称。
这可能吗?
import unittest
curTestEnv = None # don't require this
def verify( expected, actual ):
if( expected != actual ):
# How do I dynamically get test environment??
# print 'From TC: ' + unittest.TestCase.id()
print 'From Env: ' + curTestEnv.id() # Log TestName
assert expected == actual, 'Failed: ' + str( curTestEnv.id())
# Reusable Test
def theTest( exp ):
verify( exp, 'keith2' )
def otherTest( exp ):
theTest( exp )
class SomeTests(unittest.TestCase):
def setUp( self ):
global curTestEnv # don't require this
curTestEnv = self
def test_one( self ):
theTest( 'keith' )
def test_two( self ):
otherTest( 'keith2')
if __name__ == '__main__':
unittest.main( argv=sys.argv, testRunner = unittest.TextTestRunner(verbosity=2))
这种技术在很多情况下非常有用。