Python 除了当前添加的测试之外,unittest.TestSuite还运行以前加载的测试
我的代码使用Python 除了当前添加的测试之外,unittest.TestSuite还运行以前加载的测试,python,python-2.6,test-suite,python-unittest,Python,Python 2.6,Test Suite,Python Unittest,我的代码使用unittest框架运行测试。这是我的一个方法的基本概念: def _RunTestsList(self, lTestsPaths): """ Runs all tests in lTestsPaths with the unittest module """ for sTestPath in lTestsPaths: testLoader = unittest.TestLoader()
unittest
框架运行测试。这是我的一个方法的基本概念:
def _RunTestsList(self, lTestsPaths):
""" Runs all tests in lTestsPaths with the unittest module
"""
for sTestPath in lTestsPaths:
testLoader = unittest.TestLoader()
temp_module = imp.load_source('temp_module', sTestPath)
tstSuite = testLoader.loadTestsFromModule(temp_module)
unittest.TextTestRunner (verbosity=1).run(tstSuite)
显然,我试图实现的是运行lTestsPaths
列表中的测试。出于某种原因,所发生的情况不是单独运行lTestsPaths
中的每个测试,而是在以前运行的所有测试之外运行每个测试。当从代码中的不同位置调用此方法时,也会发生这种情况。也就是说,以前运行的所有测试(在以前的调用中)都将再次运行
在调试时,我看到当tstSuite
初始化时,它将使用以前运行的所有测试进行初始化
为什么会这样?如何使此代码按预期运行?在调试了许多小时后,我找到了问题的根源:问题似乎是
temp_模块的名称,也就是说,因为我给所有temp模块的名称都相同。这与内置的dir
方法有关,如dir
方法,由testLoader调用。loadTestsFromModule(temp\u模块)
返回以前运行过的测试对象名称。我不知道为什么,但这就是代码行为的原因
为了解决这个问题,我在使用模块后从sys.modules
中删除了模块名:“temp_module”。也许有一个更干净的方法,但这是可行的
以下是对我有效的改进代码:
def _RunTestsList(self, lTestsPaths):
""" Runs all tests in lTestsPaths with the unittest module
"""
for sTestPath in lTestsPaths:
testLoader = unittest.TestLoader()
temp_module = imp.load_source('temp_module', sTestPath)
tstSuite = testLoader.loadTestsFromModule(temp_module)
unittest.TextTestRunner (verbosity=1).run(tstSuite)
del sys.modules['temp_module']