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

2024-05-19 13:32:58 发布

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

我使用unittest来测试烧瓶应用程序,使用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中是否有一些内置的方法允许这样做?


Tags: testself应用程序flask测试环境烧瓶defpass
3条回答

为了让一个测试首先执行,并且只在该测试出错时停止其他测试的执行,您需要在^{}中调用该测试(因为python不保证测试顺序),然后失败或跳过其余的失败测试。

我喜欢^{},因为它实际上并不运行其他测试,而引发异常似乎仍然试图运行测试。

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!")

通过在setUp()中调用skipTest(),可以跳过整个测试用例。这是Python2.7中的一个新特性。而不是失败的测试,它只是跳过所有的。

对于您的用例,有^{}函数:

If an exception is raised in a setUpModule then none of the tests in the module will be run and the tearDownModule will not be run. If the exception is a SkipTest exception then the module will be reported as having been skipped instead of as an error.

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

相关问题 更多 >