我的测试脚本如下所示:
import os
import sys
from unittest import defaultTestLoader as loader, TextTestRunner
path_to_my_project = os.path.dirname(os.path.abspath(__file__)) + '/../'
sys.path.insert(0, path_to_my_project)
suite = loader.discover('my_project')
runner = TextTestRunner()
runner.run(suite)
如果我运行此脚本,则输出为:
$ python3 runtest.py
.....F.....
======================================================================
FAIL: test_insert (fate.test.test_operators.OperatorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/chiel/Projects/tfate/libs/fate/../fate/test/test_operators.py", line 16, in test_insert
self.assertEqual(expected, self.session.text[:14])
AssertionError: 'Foo import sys$' != 'Foo import sys'
- Foo import sys$
? -
+ Foo import sys
----------------------------------------------------------------------
Ran 12 tests in 0.030s
FAILED (failures=1)
退出代码为零:
$ echo $?
0
但是,python docs表示“默认情况下主要调用sys.exit()
,并带有表示测试成功或失败的退出代码。”
我的剧本出了什么问题?
答案 0 :(得分:33)
代码未使用unittest.main
。您需要使用TestResult.wasSuccessful
检查结果并手动调用sys.exit
。
import sys
....
ret = not runner.run(suite).wasSuccessful()
sys.exit(ret)
答案 1 :(得分:15)
我在获取TextTestRunner
结果时遇到了一些麻烦。对于像我这样的人来说,这是它的工作原理:
"""Run all tests inside of *_test.py modules located in the same directory."""
import sys
import unittest
if __name__ == '__main__':
test_suite = unittest.defaultTestLoader.discover('.', '*_test.py')
test_runner = unittest.TextTestRunner(resultclass=unittest.TextTestResult)
result = test_runner.run(test_suite)
sys.exit(not result.wasSuccessful())