skip和skipif 跳过用例

skip、skipif跳过用例

  • pytest.mark.skip 可以标记无法在某些平台运行的测试用例,或者你希望失败的测试用例
  • 希望满足某些条件才执行某些用例,否则pyetst会跳过运行该测试用例
  • 实际常见场景:跳过非Windows平台上的仅Windows测试,或者跳过依赖于当前不可用的外部资源(例如数据库)的测试
@pytest.mark.skip

​ 跳过执行测试用例,有可选参数reason:跳过的原因,会在执行结果中打印

import pytest

@pytest.fixture(autouse=True)
def login():
    print('-登录-')

def test_case01():
    print('这是第一条测试用例')

@pytest.mark.skip(reason="不执行第二条用例")
def test_case02():
    print('这是第二条测试用例')

class Test1:
    @pytest.mark.skip(reason="第三条用例不要执行")
    def test_case03(self):
        print('这是测试用例3')

    def test_case04(self):
        print('这是测试用例4')

@pytest.mark.skip(reason='整个类不执行,跳过')
class Test2:
    def test_case05(self):
        print('这是第五条测试用例')

总结:

  • pytest.mark.skip 可以加在函数上,类上,类方法上

  • 加在类上面,整个类都不会执行

pytest.skip()函数基础使用

作用:在测试用例执行期间强制跳过不再执行剩余内容

类似:在Python的循环里面,满足某些条件则break 跳出循环

import pytest

def test_function():

    n = 1
    while True:
        print(f'this is 第{n}次执行')
        n += 1
        if n == 5:
            pytest.skip('等于5 退出啦')

pytest.skip(msg="",allow_module_level=False)

当 allow_module_level=True 时,可以设置在模块级别跳过整个模块

import sys
import pytest

if sys.platform.startswith('win'):
    pytest.skip("skipping windows-only tests", allow_module_level=True)

@pytest.fixture(autouse=True)
def test_login():
    print('登录功能')

def test_case001():
    print('这是测试用例1')

@pytest.mark.skipif(condition, reason="")

作用:希望有条件地跳过某些测试用例

注意:condition需要返回True才会跳过

@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows")
class TestSkipIf(object):
    def test_function(self):
        print("不能在window上运行")

跳过标记
  • 可以将 pytest.mark.skip 和 pytest.mark.skipif 赋值给一个标记变量
  • 在不同模块之间共享这个标记变量
  • 若有多个模块的测试用例需要用到相同的 skip 或 skipif ,可以用一个单独的文件去管理这些通用标记,然后适用于整个测试用例集
import pytest,sys
# 标记
skipmark = pytest.mark.skip(reason="不能在windows运行")
skipifmark = pytest.mark.skipif(sys.platform == "win32", reason="不能在win上运行lalala====")

@skipmark
class TestSkip_Mark(object):
    @skipifmark
    def test_case01(self):
        print('测试标记1')
    def test_case02(self):
        print('测试标记2')

@skipmark
def test_case03(self):
    print('测试标记3')

posted @ 2021-06-18 09:04  太白之魔童降世  阅读(455)  评论(0)    收藏  举报