python - unittest跳过用例
前言:我们在做自动化测试的时候,可能会遇到一些用例中间不用回归,想要进行跳过。直接注释的话,代码量修改过大,显然这个方法不妥,哪还有什么方法?unittest这个自动化框架可以帮助我们完成这个操作
自动跳过用例
unittest中提供了一些跳过用例的装饰器方法。我们可以通过这些装饰器来帮我们完成这些操作
@unittest.skip()
表示:无条件跳过用例
def skip(reason): """ 无条件地跳过用例 """ def decorator(test_item): if not isinstance(test_item, type): @functools.wraps(test_item) def skip_wrapper(*args, **kwargs): raise SkipTest(reason) test_item = skip_wrapper test_item.__unittest_skip__ = True test_item.__unittest_skip_why__ = reason return test_item return decorator
@unittest.skipIf()
表示:如果条件为真,则跳过测试。
def skipIf(condition, reason): """ 如果条件为真,则跳过测试。 """ if condition: return skip(reason) return _id
@unittest.skipUnless()
表示:除非条件为真,否则跳过测试。
def skipUnless(condition, reason): """ 除非条件为真,否则跳过测试。 """ if not condition: return skip(reason) return _id
小试牛刀
#-*- encoding: utf-8 -*- import unittest import time import sys defaultencoding = 'GBK' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) class TestCase(unittest.TestCase): def setUp(self): print('这是初始化').decode('utf-8') def tearDown(self): print('这是tearDown').decode('utf-8') @unittest.skip('强制性跳过') def test01(self): print('这是test01,需要强制跳过').decode('utf-8') @unittest.skipIf(True, '条件为真的时候跳过') def test02(self): print('这是test02,条件为真的时候跳过').decode('utf-8') @unittest.skipUnless(False, '条件为假的时候跳过') def test03(self): print('这是test03,条件为假的时候跳过').decode('utf-8') def test04(self): time.sleep(3) print('这是test04').decode('utf-8') if __name__ == '__main__': unittest.main()
运行结果如下:
从执行结果中看到我们一共跳过了3条用例
那么把装饰器放Class上,那会是怎么样?
那么就是全部跳过这个类