如何在指定的测试失败后强制测试停止运行测试套件?

2024-09-20 22:54:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Selenium Webdriver/python2.7编写的测试套件,由几个测试用例组成。有些测试用例非常关键,如果它们失败了,整个测试就失败了,并且没有必要在那之后运行测试用例。在

class TestSuite1(unittest.TestCase)
     def setUp(self):
         pass

     def test1(self):
         return True

     def test2(self):
         return false

     def test3(self):
         return True

     # This is a critical test
     def test4(self):
         return false

     def test5(self):
         return True

     def tearDown(self):
         pass

所以,我想在test4失败时停止整个测试运行(test2失败时测试运行应该继续),因为这很关键。我知道我们可以使用decorator,但我正在寻找一种更有效的方法,因为我的测试运行中有大约20个关键测试,而对所有测试用例使用20个标志似乎并不有效。在


Tags: selffalsetruereturn套件defselenium测试用例
1条回答
网友
1楼 · 发布于 2024-09-20 22:54:33

比如说:

import unittest

class CustomResult(unittest.TestResult):
    def addFailure(self, test, err):
        critical = ['test4', 'test7']
        if test._testMethodName in critical:
            print("Critical Failure!")
            self.stop()
        unittest.TestResult.addFailure(self, test, err)


class TestSuite1(unittest.TestCase):
    def setUp(self):
        pass

    def test1(self):
        return True

    def test2(self):
        return False

    def test3(self):
        return True

    # This is a critical test
    def test4(self):
        self.fail()
        pass

    def test5(self):
        print("test5")
        return True

    def tearDown(self):
        pass


if __name__ == '__main__':
    runner = unittest.runner.TextTestRunner(resultclass=CustomResult)
    unittest.main(testRunner=runner)

您可能需要根据调用测试的方式来调整此设置。在

如果self.fail()(intest4)被注释掉,则测试5种方法。但如果没有被注释掉,测试将打印“严重失败!”然后停下来。在我的例子中,只运行了4个测试。在

给这些方法命名也可能是明智的,这样当按字典顺序排序时,它们会排在第一位,这样如果发生严重故障,测试其他方法就不会浪费时间。在

输出(带self.fail()):

^{pr2}$

输出(不带self.fail()):

test5
Ran 5 tests in 0.001s

OK

相关问题 更多 >

    热门问题