微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

『德不孤』Pytest框架 — 6、Mark分组执行测试用例

目录

1、Pytest中的Mark介绍

Mark主要用于在测试用例/测试类中给用例打标记,实现测试分组功能,并能和其它插件配合设置测试方法执行顺序等。

在实际工作当中,我们要写的自动化用例会比较多,而且不会都放在一个.py文件里。

如下图,现在需要只执行红色部分的测试方法,其它方法不执行。

image

2、Mark的使用

在Pytest当中,先给用例打标记,在运行时,通过标记名来过滤测试用例。

步骤:

  1. @pytest.mark.标签标记在需要执行的用力上。(标签自定义
  2. 执行测试:pytest 测试套件名 -m 标签
  3. 这样执行会有警告,提示标签注册

示例:

# 如:在test_01.py文件的testa()方法上进行mark标识。
@pytest.mark.hellotest
def test_a():
    """购物下单"""
    print("test_01文件函数a")
    assert True

# 其他两个文件中的方法同理。

执行命令,查看结果:

if __name__ == '__main__':
    pytest.main(["-vs", "-m", "hellotest"])

# 同理也可以用命令行的方式执行。

"""
执行结果:

test_01.py::test_a test_01文件函数a
PASSED
test_02.py::test_b test_02文件函数b
PASSED
test_03.py::test_a test_03文件函数a
PASSED

3 passed, 3 deselected, 3 warnings
说明:3个用例通过,3个用例没有选择,有3个警告
"""

这样就简单的实现了Mark标记的使用,但是我们在工作中不这样用,我们需要把Mark标记进行注册

3、Mark的注册和使用

Mark标签官方提供的注册方式有2种,这里只提供一种最简单直接的方式:

通过pytest.ini配置文件注册

pytest.ini文件当中配置:

[pytest] # 固定的section名
markers= # 固定的option名称,注意缩进。
    标签名1: 标签名的说明内容标签名2: 不写也可以
    标签名N

示例:还是上面的练习。

pytest.ini配置文件内容如下:

[pytest]
addopts = -vs
testpaths = scripts
python_files = test*
python_classes = Test*
python_functions = test*
markers=
    hellotest: Mark Description
    smoke

执行命令,查看结果:

if __name__ == '__main__':
    pytest.main(["-m", "hellotest"])

"""
执行结果:

test_01.py::test_a test_01文件函数a
PASSED
test_02.py::test_b test_02文件函数b
PASSED
test_03.py::test_a test_03文件函数a
PASSED

3 passed, 3 deselected, 
说明:3个用例通过,3个用例没有选择,没有警告了。
"""

4、使用Mark完成失败重试

只执行test_01.py文件中的测试用例:

import pytest


@pytest.mark.hellotest
def test_a():
    """购物下单"""
    print("test_01文件函数a")
    assert True


@pytest.mark.Fail_retry
def test_b():
    """购物下单"""
    print("test_01文件函数b")
    assert False


if __name__ == '__main__':
    pytest.main(["-m", "Fail_retry"])


"""
执行结果:

test_01.py::test_b test_01文件函数b
RERUN
test_01.py::test_b test_01文件函数b
RERUN
test_01.py::test_b test_01文件函数b
Failed

1 Failed, 1 deselected, 2 rerun
说明:1个失败,1个取消选择,2次重跑用例
"""

下面是pytest.ini配置文件内容

[pytest]
addopts = -vs --reruns 2(配置重跑两次)
testpaths = scripts
python_files = test_01.py
python_classes = Test*
python_functions = test*
markers=
    hellotest: Mark Description
    Fail_retry:

5、扩展

1)多个Mark标签可以用在同一个用例上。

@pytest.mark.hello
@pytest.mark.world
def test_a():
    """购物下单"""
    print("test_01文件函数a")
    assert True

2)Mark标签也可以用到测试类上。

@pytest.mark.hello
class Test_Mark:

    @pytest.mark.world
    def test_a(self):
        """购物下单"""
        print("test_01文件函数a")
        assert True

工作中的使用场景:冒烟测试,分模块执行测试用例,分接接口执行测试用例等。

参考:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐