【发布时间】:2015-04-22 00:15:36
【问题描述】:
这是一个示例脚本,用于检查第一个测试用例中的前提条件,我的意图是如果不满足前提条件则中止脚本。
#!/usr/bin/python
import unittest
import sys
class TestMyScript(unittest.TestCase):
def test_000_prerequisite(self):
a = 0
if not a:
sys.exit()
return
def test_001_test1(self):
print "Inside test 1"
return
def test_002_test2(self):
print "Inside test 2"
return
if __name__ == "__main__":
unittest.main()
但是,sys.exit() 仅从套件的单个测试用例中退出。它不会退出整个脚本。
我知道 unittest 会单独处理每个测试用例,这就是为什么由任何测试用例引起的任何异常都由测试运行器处理并继续进行下一个测试用例的原因。
但我希望脚本自行结束。我该怎么做?
这是我的脚本的输出:
./temp.py
EInside test 1
.Inside test 2
.
======================================================================
ERROR: test_000_prerequisite (__main__.TestMyScript)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./temp.py", line 9, in test_000_prerequisite
sys.exit()
SystemExit
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)
我的猜测是,如果测试用例返回一些信号,我必须弄乱 TestRunner 并终止脚本。但我不确定如何真正实现它。
【问题讨论】:
-
你正在赶上
SystemExit。 -
重复,见上面的链接。
-
谢谢大家的回复。上面的线程导致另一个解决了我的问题。最简单的方法是添加故障快速标志。我用解决方案更新了我的帖子。
-
如果您找到了问题的解决方案,我建议您将其作为答案提交,然后接受答案。这样一来,其他人就不会在您已经解决问题时继续提出您的问题希望提供帮助。
标签: python unit-testing python-unittest