【问题标题】:Commands after unittest don't executeunittest 后的命令不执行
【发布时间】:2018-05-11 12:42:28
【问题描述】:

我在 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"),不会执行。 为什么单元测试后我什么都做不了?测试后如何继续代码?

【问题讨论】:

    标签: python unit-testing execution


    【解决方案1】:

    unittest docs 解释一下:

    默认情况下,main 调用 sys.exit() 并带有指示测试运行成功或失败的退出代码。

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

    你可以通过传递exit=False来避免这种行为:

    unittest.main(exit=False)
    

    【讨论】:

    • 我又慢了:p。是的
    • 添加exit=False 后,现在当测试用例失败时,其余代码行仍在执行。有没有一种快速的方法来解决这个问题?谢谢
    【解决方案2】:

    只是对先前答案的快速补充。是的,exit=False 运行良好,但我遇到了测试用例失败的情况,即使那时程序的其余部分仍在运行(根据当前逻辑,这是预期的)。理想情况下,程序应该在任何测试用例失败的情况下停止。在那种情况下,我只是这样做了。

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

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多