单元测试后的命令不执行

Commands after unittest don't execute

我在 python 3.6 中导入了 unittest,并像这样使用它:

class TestFunc(unittest.TestCase):
        def test_half(self):
            pass
        def test_merge(self):
            pass
        def test_decrypt(self):
            pass
        def test_rank(self):
            pass

if __name__ == "__main__":
    print("printing before calling unittest")
    unittest.main()
    print("printing after calling unittest")

输出如下所示:

 printing before calling unittest
    ....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

Process finished with exit code 0

并且对 print 的第二次调用即 print("printing after calling unittest") 不会执行。 为什么单元测试后我什么都做不了?测试后如何继续代码?

unittest docs 解释一下:

By default main calls sys.exit() with an exit code indicating success or failure of the tests run.

sys.exit() 立即退出脚本,因此永远不会调用您的最后一行。

您可以通过传递 exit=False:

来避免这种行为
unittest.main(exit=False)

只是对先前答案的快速补充。是的,exit=False 工作得很好,但我遇到了测试用例失败的情况,甚至程序的其余部分都是 运行(按照当前逻辑是预期的)。理想情况下,程序应该在任何测试用例失败的情况下停止。既然如此,我就这么干了。

status = unittest.main(exit=False)
if len(status.result.failures) == 0 and len(status.result.errors) == 0:
    # normal remaining execution
else:
    # exit