Pytest如何使用mark的方法

 更新时间:2022年05月15日 09:27:46   作者:Redrose2100  
本文主要介绍了Pytest如何使用mark的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、常见的内置markers

  • usefixtures - 为测试函数或者测试类知名使用那些fixture
  • filterwarnings - 为一个测试函数过滤一个指定的告警
  • skip - 跳过一个测试函数
  • skipif - 如果满足条件就跳过测试函数
  • xfail - 标记用例失败
  • parametrize - 参数化

二、查看所有markers

如下,可以查看到当前环境中的所有markers

$ pytest --markers
@pytest.mark.forked: Always fork for this test.

@pytest.mark.flaky(reruns=1, reruns_delay=0): mark test to re-run up to 'reruns' times. Add a delay of 'reruns_delay' seconds between re-runs.

@pytest.mark.hypothesis: Tests which use hypothesis.

@pytest.mark.allure_label: allure label marker

@pytest.mark.allure_link: allure link marker

@pytest.mark.allure_description: allure description

@pytest.mark.allure_description_html: allure description html

@pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/stable/warnings.html#pytest-mark-filterwarnings

@pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="no way of currently testing this") skips the test.

@pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions evaluate to True. Example: skipif(sys.platform == 'win32') skip
s the test if we are on the win32 platform. See https://docs.pytest.org/en/stable/reference.html#pytest-mark-skipif

@pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): mark the test function as an expected failure if any of the conditions eva
luate to True. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expe
cted, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See https://docs.pytest.org/en/stable/reference.html#pytes
t-mark-xfail

@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of valu
es if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls o
f the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org/en/stable/parametrize.html for more info and examples.

@pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/stable/fixture.html#usefix
tures

@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.

@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.

三、注册自定义marks

方式一:在pytest.ini中按照如下格式声明即可,冒号之前为注册的mark名称,冒号之后为此mark的说明

[pytest]
markers =
    smoke: smoke tests
    test: system tests

此时test_demo.py代码如下

import pytest

@pytest.mark.smoke
def test_func():
    assert 1==1

@pytest.mark.test
def test_func2():
    assert 1==1

def test_func3():
    assert 1==1

使用pytest -m smoke执行结果如下,发现此时即只执行了标记为smoke的一个用例,这就是和自定义mark的使用方法

$ pytest -m smoke
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items / 2 deselected / 1 selected                                                                                                                           

test_demo.py .                                                                                                                                                    [100%]

=================================================================== 1 passed, 2 deselected in 0.04s ====================================================================

方式二:在conftest.py文件中重写pytest_configure函数即可,比如如下,注册两个mark:smoke和test

def pytest_configure(config):
    config.addinivalue_line(
        "markers", "smoke: smoke test"
    )
    config.addinivalue_line(
        "markers", "test: system test"
    )

test_demo.py代码如下:

import pytest

@pytest.mark.smoke
def test_func():
    assert 1==1

@pytest.mark.test
def test_func2():
    assert 1==1

def test_func3():
    assert 1==1

通过pytest -m test 执行结果如下:

$ pytest -m test
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: D:\src\blog\tests
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items / 2 deselected / 1 selected                                                                                                                           

test_demo.py .                                                                                                                                                    [100%]

=================================================================== 1 passed, 2 deselected in 0.02s ====================================================================

四、对未注册mark的限制

默认情况下,对未注册mark直接使用是会产生一条告警信息,比如这里把pytest.ini和conftest.py都删除掉,只剩test_demo.py一个文件

test_demo.py代码如下

import pytest

@pytest.mark.smoke
def test_func():
    assert 1==1

@pytest.mark.test
def test_func2():
    assert 1==1

def test_func3():
    assert 1==1

直接使用 pytest -m smoke 执行结果如下,可以发现这里产生了两条告警,这就是因为这两条告警未在pytest.ini或者conftest.py中进行注册的原因,在实际项目开发中如果在执行测试的时候发现了这种大片告警打印,解决办法就是在pytest.ini或者conftest.py将这些告警报出的mark都进行注册即可

$ pytest -m smoke
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: D:\src\blog\tests
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items / 2 deselected / 1 selected                                                                                                                           

test_demo.py .                                                                                                                                                    [100%]

=========================================================================== warnings summary ===========================================================================
test_demo.py:3
  D:\src\blog\tests\test_demo.py:3: PytestUnknownMarkWarning: Unknown pytest.mark.smoke - is this a typo?  You can register custom marks to avoid this warning - for deta
ils, see https://docs.pytest.org/en/stable/mark.html
    @pytest.mark.smoke

test_demo.py:7
  D:\src\blog\tests\test_demo.py:7: PytestUnknownMarkWarning: Unknown pytest.mark.test - is this a typo?  You can register custom marks to avoid this warning - for detai
ls, see https://docs.pytest.org/en/stable/mark.html
    @pytest.mark.test

-- Docs: https://docs.pytest.org/en/stable/warnings.html
============================================================= 1 passed, 2 deselected, 2 warnings in 0.02s ==============================================================

如果希望强制限制必须先注册再使用mark,则可以在pytest.ini中加上如下配置即可

[pytest]
addopts = --strict-markers

比如test_demo.py代码:

import pytest

@pytest.mark.smoke
def test_func():
    assert 1==1

@pytest.mark.test
def test_func2():
    assert 1==1

def test_func3():
    assert 1==1

此时继续使用pytest -m smoke执行结果如下,发现此时已经报错了,即强制限制必须对mark进行注册

$ pytest -m smoke
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 0 items / 1 error                                                                                                                                             

================================================================================ ERRORS ================================================================================
____________________________________________________________________ ERROR collecting test_demo.py _____________________________________________________________________
'smoke' not found in `markers` configuration option
======================================================================= short test summary info ========================================================================
ERROR test_demo.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=========================================================================== 1 error in 0.14s ===========================================================================

到此这篇关于Pytest如何使用mark的方法的文章就介绍到这了,更多相关Pytest使用mark内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python读取mat(matlab数据文件)并实现画图

    Python读取mat(matlab数据文件)并实现画图

    这篇文章主要介绍了Python读取mat(matlab数据文件)并实现画图问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • python实现全盘扫描搜索功能的方法

    python实现全盘扫描搜索功能的方法

    今天小编就为大家分享一篇python实现全盘扫描搜索功能的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-02-02
  • PyG搭建GCN模型实现节点分类GCNConv参数详解

    PyG搭建GCN模型实现节点分类GCNConv参数详解

    这篇文章主要为大家介绍了PyG搭建GCN模型实现节点分类GCNConv参数详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Python时间序列处理之ARIMA模型的使用讲解

    Python时间序列处理之ARIMA模型的使用讲解

    今天小编就为大家分享一篇关于Python时间序列处理之ARIMA模型的使用讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • python中base64编码简介

    python中base64编码简介

    Base64是一种任意二进制到文本字符串的编码方法,常用于在URL、Cookie、网页中传输少量二进制数据,Base64是一种用64个字符来表示任意二进制数据的方法,这篇文章主要介绍了python中base64编码,需要的朋友可以参考下
    2022-12-12
  • Python使用Kafka处理数据的方法详解

    Python使用Kafka处理数据的方法详解

    Kafka是一个分布式的流数据平台,它可以快速地处理大量的实时数据。在Python中使用Kafka可以帮助我们更好地处理大量的数据,本文就来和大家详细讲讲具体使用方法吧
    2023-04-04
  • 一个计算身份证号码校验位的Python小程序

    一个计算身份证号码校验位的Python小程序

    闲着无事,便想写个实用点的Python小程序,如何计算机身份证号码的校验位,这样的文章在网上一抓一大把,这里仅简单介绍下吧
    2014-08-08
  • Python中dataclass库实例详解

    Python中dataclass库实例详解

    这篇文章主要介绍了Python中dataclass库,合理使用dataclass将会大大减轻开发中的负担,将我们从大量的重复劳动中解放出来,这既是dataclass的魅力,本文结合实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2022-09-09
  • 基于numpy中的expand_dims函数用法

    基于numpy中的expand_dims函数用法

    今天小编就为大家分享一篇基于numpy中的expand_dims函数用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • python和flask中返回JSON数据的方法

    python和flask中返回JSON数据的方法

    下面小编就为大家整理了一篇python和flask中返回JSON数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-03-03

最新评论