【问题标题】:Python unittest: cancel all tests if a specific test failsPython unittest:如果特定测试失败,则取消所有测试
【发布时间】:2012-10-15 18:00:17
【问题描述】:

我使用unittest 测试我的Flask 应用程序,并使用nose 实际运行测试。

我的第一组测试是确保测试环境干净,并防止在 Flask 应用程序配置的数据库上运行测试。我确信我已经干净地设置了测试环境,但我希望在不运行所有测试的情况下对此有所保证。

import unittest

class MyTestCase(unittest.TestCase):
    def setUp(self):
        # set some stuff up
        pass

    def tearDown(self):
        # do the teardown
        pass

class TestEnvironmentTest(MyTestCase):
    def test_environment_is_clean(self):
        # A failing test
        assert 0 == 1

class SomeOtherTest(MyTestCase):
    def test_foo(self):
        # A passing test
        assert 1 == 1

如果TestEnvironmentTest 失败,我希望unittestnose 保释,并阻止SomeOtherTest 和任何进一步的测试运行。在unittest(首选)或nose 中是否有一些内置方法允许这样做?

【问题讨论】:

  • 你知道nose是否解决了测试排序问题吗?因为在 python 中你不能保证测试顺序(虽然我认为它通常会解析为字母顺序)。
  • 嗯,这也将是另一个问题......但我想这可以通过在你的设置中进行测试来解决。
  • @Colleen 嗯不完全...我想运行所有测试,即使它们有错误,但我希望我的环境测试在任何其他测试运行之前通过。您的第一个建议有效:我将环境测试放入 setUp。好像我错了......测试之间持续存在一些东西,糟糕糟糕!
  • 哦,对不起,误解了你的问题。如果您未通过 TestEnvironmentTest,您认为您想立即失败。

标签: python unit-testing nose


【解决方案1】:

为了让一个测试首先执行并且只在该测试出错的情况下停止执行其他测试,您需要在 setUp() 中调用测试(因为 python 不保证测试订单),然后失败或跳过其余的失败。

我喜欢skipTest(),因为它实际上不运行其他测试,而引发异常似乎仍在尝试运行测试。

def setUp(self):
    # set some stuff up
    self.environment_is_clean()

def environment_is_clean(self):
    try:
        # A failing test
        assert 0 == 1
    except AssertionError:
        self.skipTest("Test environment is not clean!")

【讨论】:

    【解决方案2】:

    对于您的用例,有 setUpModule() 函数:

    如果在 setUpModule 中引发了异常,那么在 该模块将运行,tearDownModule 将不会运行。如果 异常是SkipTest 异常,那么模块将是 报告为已被跳过而不是错误。

    在这个函数中测试你的环境。

    【讨论】:

    • 或者在某些情况下,setUpClass() 也可以工作 If an exception is raised during a setUpClass then the tests in the class are not run and the tearDownClass is not run. docs.python.org/2/library/…
    • 如果setUpModule() 被定义为TestCase 类之外的函数,你将如何进行断言?
    【解决方案3】:

    您可以通过在setUp() 中调用skipTest() 来跳过整个测试用例。这是 Python 2.7 中的一个新特性。它不会让测试失败,而是直接跳过所有测试。

    【讨论】:

    • 这是一个不错的功能,但最终结果还可以,当它应该抱怨错误时。
    • 这就是你有 TestEnvironmentTest 失败的原因。如果你只是想让他们失败,你已经拥有的代码有什么问题?
    【解决方案4】:

    我不太确定它是否符合您的需求,但您可以根据第一套单元测试的结果执行第二套单元测试:

    envsuite = unittest.TestSuite()
    moretests = unittest.TestSuite()
    # fill suites with test cases ...
    envresult = unittest.TextTestRunner().run(envsuite)
    if envresult.wasSuccessful():
        unittest.TextTestRunner().run(moretests)
    

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多