为什么在执行'unittest.main()'后,python不再执行其他内容?
假设我有以下内容:
import unittest
class MyTests(unittest.TestCase):
def test001(self):
print 'This is test001'
def test002(self):
print 'This is test002'
if __name__ == '__main__':
unittest.main()
print 'Done'
然后输出是:
>> This is test001
>> This is test002
>> ----------------------------------------------------------------------
>> Ran 2 tests in 0.001s
>> OK
我在想,为什么没有打印出'Done'(或者后面任何东西)呢?
1 个回答
21
在调用 unittest.main()
时,传入 exit=False
这个参数(详细信息可以查看文档):
unittest.main(exit=False)
这是我在控制台上看到的内容:
$ python test.py
This is test001
.This is test002
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Done
顺便说一下,unittest 的 TestProgram.runTests()
方法在内部会调用 sys.exit()
,如果 exit
的值是 True
(默认就是这样):
def runTests(self):
...
if self.exit:
sys.exit(not self.result.wasSuccessful())