Pytest如何使用mark的方法

目录
  • 一、常见的内置markers
  • 二、查看所有markers
  • 三、注册自定义marks
  • 四、对未注册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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python Pytest装饰器@pytest.mark.parametrize详解

    Pytest中装饰器@pytest.mark.parametrize('参数名',list)可以实现测试用例参数化,类似DDT 如:@pytest.mark.parametrize('请求方式,接口地址,传参,预期结果',[('get','www.baidu.com','{"page":1}','{"code":0,"msg":"成功"})',('post','www.baidu.com','{"page"

  • Pytest mark使用实例及原理解析

    这篇文章主要介绍了Pytest mark使用实例及原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用方法: 1.注册标签名 2.在测试用例/测试类前面加上:@pytest.mark.标签名 打标记范围:测试用例.测试类.模块文件 注册方式: 1.单个标签: 在conftest.py添加如下代码: def pytest_configure(config): # demo是标签名 config.addinivalue_line("mark

  • 详解pytest实现mark标记功能详细介绍

    mark标记 ​在实际工作中,我们要写的自动化用例会比较多,也不会都放在一个py文件中,如果有几十个py文件,上百个方法,而我们只想运行当中部分的用例时怎么办? ​pytest提供了一个非常好用的mark功能,可以给测试用例打上各种各样的标签,运行用例时可以指定运行某个标签.mark功能作用就是灵活的管理和运行测试用例. ​标签既可以打到方法上,也可以打到类上,标记的两种方式: 直接标记类或方法或函数:@pytest.mark.标签名 类属性:pytestmark = [pytest.mark.

  • Pytest如何使用mark的方法

    目录 一.常见的内置markers 二.查看所有markers 三.注册自定义marks 四.对未注册mark的限制 一.常见的内置markers usefixtures - 为测试函数或者测试类知名使用那些fixture filterwarnings - 为一个测试函数过滤一个指定的告警 skip - 跳过一个测试函数 skipif - 如果满足条件就跳过测试函数 xfail - 标记用例失败 parametrize - 参数化 二.查看所有markers 如下,可以查看到当前环境中的所有ma

  • Pytest测试框架基本使用方法详解

    pytest介绍 pytest是一个非常成熟的全功能的Python测试框架,主要特点有以下几点: 1.简单灵活,容易上手,文档丰富: 2.支持参数化,可以细粒度地控制要测试的测试用例: 3.能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试.接口自动化测试(pytest+requests); 4.pytest具有很多第三方插件,并且可以自定义扩展 如pytest-selenium(集成selenium). pytest-html(完美html测试报告

  • Pytest框架之fixture的详细使用教程

    前言 前面一篇讲了setup.teardown可以实现在执行用例前或结束后加入一些操作,但这种都是针对整个脚本全局生效的 如果有以下场景:用例 1 需要先登录,用例 2 不需要登录,用例 3 需要先登录.很显然无法用 setup 和 teardown 来实现了fixture可以让我们自定义测试用例的前置条件 fixture优势 命名方式灵活,不局限于 setup 和teardown 这几个命名 conftest.py 配置里可以实现数据共享,不需要 import 就能自动找到fixture sc

  • pytest基本用法简介

    1.安装pytest,打开dos窗口输入: pip install pytest 2.通过pycharm工具下载 3.创建pytest测试用例步骤 # 定义测试类 class TestDivide: # 定义测试方法 def test_divide_01(self): result = divide(1,1) print(result) 问题:右键运行没有pytest运行的方式的处理步骤 第一步:检查文件名和文件所在目录是否合法,对应第一点 第二步:修改默认运行方式为pytest 第三步:删除历

  • Python测试框架pytest高阶用法全面详解

    目录 前言 1.pytest安装 1.1安装 1.2验证安装 1.3pytest文档 1.4 Pytest运行方式 1.5 Pytest Exit Code 含义清单 1.6 如何获取帮助信息 1.7 控制测试用例执行 1.8 多进程运行cases 1.9 重试运行cases 1.10 显示print内容 2.Pytest的setup和teardown函数 函数级别setup()/teardown() 类级别 3.Pytest配置文件 4 Pytest常用插件 4.1 前置条件: 4.2 Pyt

  • IOS开发中加载大量网络图片优化方法

    IOS开发中加载大量网络图片如何优化 1.概述 在IOS下通过URL读一张网络图片并不像其他编程语言那样可以直接把图片路径放到图片路径的位置就ok,而是需要我们通过一段类似流的方式去加载网络图片,接着才能把图片放入图片路径显示.比如: -(UIImage *) getImageFromURL:(NSString *)fileURL { //NSLog(@"执行图片下载函数"); UIImage * result; NSData * data = [NSData dataWithCont

  • iOS缓存文件大小显示功能和一键清理功能的实现方法

    缓存占用了系统的大量空间,如何实时动态的显示缓存的大小,使用户清晰的了解缓存的积累情况,有效的进行一键清理呢? 为方便读者和未来自己更好理解,我们创建这样场景.(在表视图的清除缓存一单元格内创建一个UILabel *cacheLabel用于显示当前缓存,当点击单元格弹出提示框,点击确定,清除缓存). 下面是实现代码: #pragma mark - 计算缓存大小 - (NSString *)getCacheSize { //定义变量存储总的缓存大小 long long sumSize = 0; /

  • 两种iOS调用系统发短信的方法

    一.程序外调用系统发短信 这个方法其实很简单,直接调用openURL即可: NSURL *url = [NSURL URLWithString:@"sms://15888888888"]; [[UIApplication sharedApplication]openURL:url]; 二.程序内调用系统发短信 这种方法有一个好处就是用户发短信之后还可以回到App. 首先要导入MessageUI.framework,并引入头文件: #import <MessageUI/Messag

  • 使用PyCharm安装pytest及requests的问题

    电脑环境:windows7 64位      python3.7 问题:在PyCharm中,使用setting下的project Interpreter安装pytest以及requests失败 解决方法:(亲测有效) 1.打开Gitbash,定位到python的安装目录:我的安装目录是 D:\pythonAnZhuang\Python37\Scripts 2.输入:pip install requests,等待安装完成 3.输入:pip install pytest,等待安装完成 4.检测是否安

  • 解决java文件流处理异常 mark/reset not supported问题

    原因: 给定的流不支持mark和reset就会报这个错误. 获取到一个网络流,这个网络流不允许读写头来回移动,也就不允许mark/reset机制. 解决办法: 用BufferedInputStream把原来的流包一层. BufferedInputStream buffInputStream = new BufferedInputStream(fileInputStream); 补充知识:Java BufferedReader之mark和reset方法实践 在读取文本的操作中,常常会在读取到文件末

随机推荐