unittest 跳过测试和预期故障

2022-08-02 14:59 更新

3.1 版中的新功能。

Unittest支持跳过单个测试方法甚至整个测试类。此外,它还支持将测试标记为“预期失败”,即已中断并将失败的测试,但不应计为 TestResult 上的失败。

跳过测试只需使用 skip() 装饰器或其条件变体之一,在 setUp() 或测试方法中调用 TestCase.skipTest(), 或直接引发 SkipTest

基本跳过如下所示:

class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("external resource not available")
        # test code that depends on the external resource
        pass

这是在详细模式下运行上述示例的输出:

test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)

可以像方法一样跳过类:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass

TestCase.setUp() 也可以跳过测试。当需要设置的资源不可用时,这很有用。

预期的故障使用预期的Failure()装饰器。

class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

通过制作一个在测试中调用 skip() 的装饰器,当它希望它被跳过时,很容易滚动你自己的跳过装饰器。除非传递的对象具有特定属性,否则此装饰器会跳过测试:

def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

以下修饰器和异常实现测试跳过和预期故障:

@unittest.skip(reason)

无条件跳过装饰测试。reason应描述跳过测试的原因。

@unittest.skipIf(conditionreason)

如果条件为真,则跳过修饰测试。

@unittest.skipUnless(condition, reason)

跳过装饰测试,除非条件为真。

@unittest.expectedFailure

将测试标记为预期的失败或错误。如果测试失败或测试函数本身(而不是其中一个测试夹具方法)中的错误,则将被视为成功。如果测试通过,则将被视为失败。

      exception unittest.SkipTest(reason)

引发此异常是为了跳过测试。

通常,您可以使用 TestCase.skipTest() 或其中一个跳过的装饰器,而不是直接引发它。

跳过的测试不会有 setUp() 或 tearDown() 围绕它们运行。跳过的类将不会运行 setUpClass() 或 tearDownClass()。跳过的模块将不会有​setUpModule()​或​tearDownModule()​运行。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号