如何在unittest测试用例中退出脚本

gix*_*xer 13 python unit-testing python-unittest

下面是一个示例脚本,它在第一个测试用例中检查前置条件,如果不满足前置条件,我的目的是中止脚本.

#!/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()
Run Code Online (Sandbox Code Playgroud)

但是,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)
Run Code Online (Sandbox Code Playgroud)

我的猜测是,如果测试用例返回一些信号,我必须乱用TestRunner并终止脚本.但不确定如何真正实现它.

解:

如果测试用例发现错误,我在Stop testsuite中找到了解决方案

以下是调用unittest.main()时需要进行的更改.failfast标志在第一次失败后停止脚本.

#!/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()
Run Code Online (Sandbox Code Playgroud)

gix*_*xer 6

答案是:

如果测试用例发现错误,请停止测试套件

这是我致电时需要进行的更改unittest.main()。该failfast关键字参数的第一次失败后停止脚本。

if __name__ == "__main__":
    unittest.main(failfast=True)
Run Code Online (Sandbox Code Playgroud)

ps failfast关键字参数仅适用于python 2.7+

pps,您也可以failfastunittest.TextTestRunner()