【问题标题】:How to force tests to stop running a test suite after a specified test failed?如何在指定测试失败后强制测试停止运行测试套件?
【发布时间】:2015-04-06 00:38:41
【问题描述】:

我有一个用 Selenium Webdriver/Python 2.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 失败时应该继续测试运行),因为它很关键。我知道我们可以使用装饰器,但我正在寻找一种更有效的方法,因为我的测试运行中有大约 20 个关键测试,并且对所有测试用例使用 20 个标志似乎并不高效。

【问题讨论】:

    标签: python unit-testing selenium selenium-webdriver python-unittest


    【解决方案1】:

    类似的东西呢:

    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()(在test4)被注释掉,则测试5个方法。但如果它没有被注释掉,测试会打印“Critical Failure!”并停止。就我而言,只运行了 4 个测试。

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

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

    严重失败! 在 0.001 秒内运行 4 次测试 失败(失败=1)

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

    测试5 在 0.001 秒内运行 5 次测试 好的

    【讨论】:

    • 感谢您的回答,它似乎应该可以正常工作,但它不适合我。不管有没有 self.fail(),所有的测试都在运行。
    • @Mahmor,你是如何运行你的测试的?如果if __name__ == '__main__': 中的代码不是开始测试的代码,那么所有测试都会运行。
    • 我通过 CLI 使用 python -m unittest a.py 运行它们。我已经复制了您在 a.py 中发布的确切代码。对吗?
    • @Mahmor 如果您将其作为脚本运行(例如python a.py),该代码将起作用——我会考虑挂钩默认的单元测试运行器,但我不确定这是否可能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多