pytest测试框架(六)---使用skip和skipif跳过测试用例

目录

一、简介

二、使用方法

1、@pytest.mark.skip装饰器

2、pytest.skip方法

3、@pytest.mark.skipif装饰器

4、pytestmark变量

5、conftest.py

三、执行方法


一、简介

最近在写自动化用例时遇到了一个场景,某些用例是只针对CentOS操作系统的,其它系统需要跳过它们。这种情况下,可以使用skip、skipif等实现跳过测试用例的功能。

二、使用方法

1、@pytest.mark.skip装饰器

在用例或类前面加上@pytest.mark.skip装饰器,并传入原因,可以跳过用例或类。参数如下:

pytest.mark.skip(*, reason=None)

※  reason (str) – Reason why the test function is being skipped.

@pytest.mark.skip(reason="This feature has not yet been implemented") 
def test_aaa(): 
    ……

 

2、pytest.skip方法

在测试执行过程中调用pytest.skip(reason)方法,使用给定的消息跳过正在执行的用例:

skip(msg[, allow_module_level=False])

※  allow_module_level (bool) – Allows this function to be called at module level, skipping the rest of the module. Defaults to False.

def test_function():
    if not valid_config():
        pytest.skip("unsupported configuration")

当allow_moudel_level=True时,将跳过整个模块:

if not pytest.config.getoption("--custom-flag"):
    pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)

 

3、@pytest.mark.skipif装饰器

在用例或类前面加上@pytest.mark.skipif装饰器,可以有条件的跳过用例或类:

pytest.mark.skipif(condition, *, reason=None)

※  condition (bool or str) – True/False if the condition should be skipped or a condition string.

※  reason (str) – Reason why the test function is being skipped.

@pytest.mark.skipif(sys.version_info < (3.6), reason="requires python3.6 or higher")
def test_bbb():
    ...

 

4、pytestmark变量

定义pytestmark变量,这个变量将作用于整个模块:

import pytest

pytestmark = pytest.mark.skip('作用于模块中的每一个用例,所以test_ccc、test_ddd都将跳过')

def test_ccc():
    assert True

def test_ddd():
    assert True

运行结果:

>>>pytest test.py
========================================================== test session starts =============================================================
platform win32 -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: D:\6-0-Prepare_Job\TestCase
plugins: allure-pytest-2.8.18, html-2.1.1, metadata-1.10.0
collected 2 items                                                                                                                           

test.py ss                                                                                                                            [100%]

========================================================== 2 skipped in 0.02s =============================================================

 

5、conftest.py

在conftest.py中配置collect_ignore_glob项, 可以在用例的收集阶段跳过指定的文件和目录。例如,跳过当前测试目录中文件名匹配test_*.py规则的文件和eee的子文件夹fff中的文件:

collect_ignore_glob = ['test*.py', 'eee/fff']

 

三、执行方法

pytest 默认不显示skip和xfail用例的详细信息,我们可以通过-r选项使其显示出来。通常一个字母代表一种类型,具体的规则为:

(f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed, (p)assed, (P)assed with output, (a)ll except passed(p/P), or (A)ll

所以,显示结果为SKIPPED的用例:

pytest -rs

 

猜你喜欢

转载自blog.csdn.net/wxt_hillwill/article/details/114868359