Python unittest:如果特定测试失败,则取消所有测试

问题描述 投票:8回答:4

我正在使用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导致unittestnoseto保释,并阻止SomeOtherTest和任何进一步的测试运行。是否有一些内置的方法在unittest(首选)或nose允许这样做?

python unit-testing nose
4个回答
7
投票

为了让一个测试首先执行并且只在该测试出错的情况下停止执行其他测试,你需要在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!")

4
投票

对于您的用例,有setUpModule()功能:

如果在setUpModule中引发异常,那么模块中的任何测试都不会运行,并且tearDownModule将不会运行。如果异常是SkipTest异常,那么该模块将被报告为已跳过而不是错误。

在此功能中测试您的环境。


2
投票

您可以通过在skipTest()中调用setUp()来跳过整个测试用例。这是Python 2.7中的一个新功能。它不会使测试失败,而是完全跳过它们。


1
投票

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

envsuite = unittest.TestSuite()
moretests = unittest.TestSuite()
# fill suites with test cases ...
envresult = unittest.TextTestRunner().run(envsuite)
if envresult.wasSuccessful():
    unittest.TextTestRunner().run(moretests)
© www.soinside.com 2019 - 2024. All rights reserved.