Python Unitest跳过一个测试,如果之前的测试结果失败

cnwbcb6i  于 7个月前  发布在  Python
关注(0)|答案(1)|浏览(72)

如果之前的测试结果是失败,是否可以跳过测试,在下面的代码中,如果test_1是失败,我想跳过test_2

import unittest

class MyTest(unittest.TestCase):
    def test_1(self):
        assert False


    def test_2(self):
        check_test_result_test_1 = "" # how
        if check_test_result == "Fail":
            self.skipTest("skip as one is fail")

if __name__ == '__main__':
    unittest.main()

字符串

c6ubokkw

c6ubokkw1#

如果一个测试依赖于另一个测试的成功运行,那么这个测试应该成为同一个测试的一部分。你可以使用TestCase.subTest方法来注解测试的不同阶段:

class MyTest(unittest.TestCase):
    def test_phases(self):
        with self.subTest('Phase 1'):
            self.assertTrue(False)
        with self.subTest('Phase 2'):
            self.assertTrue(True)

字符串
这会产生一个描述性更强的错误消息,如:

======================================================================

FAIL: test_phases (__main__.MyTest) [Phase 1]
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./prog.py", line 6, in test_phases
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


演示:https://ideone.com/mSXl3O

相关问题