unittest框架系列三(跳过测试和预期失败)

跳过测试和预期失败

欢迎加入测试交流群:夜行者自动化测试(816489363)进行交流学习QAQ

–成都-阿木木

 

以下装饰器和异常实现了测试方法及测试类的跳过和测试方法预期的失败:

  • @unittest.skip原因

    无条件跳过装饰测试。 原因应说明为何跳过测试。

  • @unittest.skipIf条件原因

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

  • @unittest.skipUnless条件原因

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

  • @unittest.expectedFailure

    将测试标记为预期的失败。如果测试失败,则视为成功。如果测试通过,将被视为失败。

  • 异常unittest.SkipTest原因

    引发此异常以跳过测试。通常,您可以使用TestCase.skipTest()或跳过装饰器之一,而不是直接提高它。

#!/user/bin/env python
# -*- coding: utf-8 -*-

"""
------------------------------------
@Project : mysite
@Time    : 2020/8/28 11:32
@Auth    : chineseluo
@Email   : 848257135@qq.com
@File    : unittest_demo.py
@IDE     : PyCharm
------------------------------------
"""
import unittest
import sys
import pytest


class MyTestCase(unittest.TestCase):
    Conut = 0

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

    @unittest.skipIf(pytest.__version__ in ("5.4.3", "5.4.4"),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        print(pytest.__version__)
        print(type(pytest.__version__))
        pass

    @unittest.skipUnless(sys.platform.startswith("linux"), "requires Windows")
    def test_windows_support(self):
        print(sys.platform)
        # windows specific testing code 在windows平台下进行测试
        pass

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


if __name__ == '__main__':
    unittest.main()

测试类也可以像测试方法一样跳过:

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

预期的失败使用expectedFailure()装饰器:

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

注意:

  • 跳过的测试方法,setUptearDown将不会运行,setUpClasstearDownClass仍会运行
  • 跳过的测试类,setUpClasstearDownClass将不会运行,setUptearDown将不会运行
posted @ 2020-09-22 10:19  成都-阿木木  阅读(190)  评论(0编辑  收藏  举报