unittest模块学习(六)

25.3.6 跳过测试和预期的失败


unittest支持跳过单独的测试方法甚至整个测试类。此外,它还支持将测试标记为‘预期失败’,这是一项测试失败并将失败,但不应该被视为TestResult失败。

可以很简单的使用skip()装饰器或者使用其条件变体来跳过一个测试。
基本上跳过测试的行为类似这样:
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

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

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

----------------------------------------------------------------------
Ran 3 tests in 0.005s

OK (skipped=3)

类可以像方法一样跳过:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass
TestCase.setUp()也可以跳过测试。当需要建立的资源不可用时,这非常有用。
预期失败使用expectedFailure()装饰器。
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)

无条件地跳过装饰测试。理由应该描述为什么测试被跳过。

-unittest.skipIf(condition, reason)

跳过测试,如果条件为True

-unittest.skipUnless(condition, reason)

跳过测试,除非条件为True

-unittest.expectedFailure()

将测试标记为预期的失败。如果运行时测试失败,测试不算做失败。

-exception unittest.SkipTest(reason)

这个exception升起则跳过该测试

通常你可以使用TestCase.skipTest()或者其中一个跳过的装饰器,而不是直接引用它。
被跳过的测试没有setUp()和testDown()方法运行。跳过类也没有setUpClass()和tearDownClass()方法运行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值