软件测试/测试开发/全日制|pytest如何标记测试用例

发布时间 2024-01-10 19:04:54作者: 霍格沃兹测试开发学社

前言

在pytest中,有时候我们并不需要对所有的用例全部执行。pytest提供了一种机制:有选择的挑选用例去执行,即标记测试函数。下面详细介绍几种方法给函数标记。

使用pytest.mark在函数上进行标记

标记格式

@表示这是一个装饰器,pytest.mark是pytest固定的写法,mark_name可以使用自定义标记和内置标记。如下:

@pytest.mark.mark_name

常用内置标记

示例如下:

import pytest

def test_01():
    print('hello')

@pytest.mark.skip()
def test_add():
    print('happy')

def test_02():
    print('fun')

if __name__ == '__main__':
    pytest.main(['-s', '-v','test_02.py'])

执行结果如下:

============================= test session starts =============================
collecting ... collected 3 items

test_02.py::test_01 PASSED                                                 [ 33%]hello

test_02.py::test_add SKIPPED (unconditional skip)                          [ 66%]
Skipped: unconditional skip

tes_t02.py::test_02 PASSED                                                 [100%]fun


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

自定义标记

注册标签名

通过pytest.ini配置文件注册标签,格式如下:

[pytest] # 固定的section名

markers= # 固定的option名称

  标签名1: 标签名的说明内容。

  标签名2

  标签名N

在测试用例/测试类中给用例打标记(只能使用已注册的标记名)

在测试用例的前面加上:@pytest.mark.已注册标签名。运行时,根据用例标签过滤(-m 标签名)。

示例如下:

import pytest

def test_01():
    print('hello')

@pytest.mark.do
def test_add():
    print('happy')

def test_02():
    print('fun')

再创建pytest.ini文件,不需要同目录,内容如下:

[pytest]
markers =
    do: do
    undo: undo

注:Windows系统中pytest.ini文件不可添加注释,否则将会报错。

命令行执行,命令及输出如下:

pytest -s -v -m do test_02.py
======================================================================== test session starts ========================================================================
platform win32 -- Python 3.7.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- d:\python3.7.6\python.exe
cachedir: .pytest_cache
rootdir: D:\pythonProject\my_selenium_project\testcases\pytest, configfile: pytest.ini
collected 3 items / 2 deselected / 1 selected                                                                                                                        

tes_t02.py::test_add happy
PASSED

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

conftest.py中定义钩子函数

示例如下:

def pytest_configure(config):
    marker_list = [
        "smoke: marks test as smoke",
        "login",
        "order: 下单场景"
    ]
    for marker in marker_list:
        config.addinivalue_line("markers", marker)

注:使用该方法需注意定义的格式,不能轻易修改函数名及入参。

使用示例:

import pytest
 
# 标记测试函数
@pytest.mark.smoke
def test_01():
    print("执行test_01")
 
def test_02():
    print("执行test_02")
 
    
# 标记测试类
@pytest.mark.order
class TestOrder:
    
    def test_order(self):
        print("下单")
 
    def test_pay(self):
        print("支付")
 
        
# 多个标签 
@pytest.mark.smoke
@pytest.mark.login
def test_login():
    print("登录")

给测试类打标签,还有另外一种方式,如下:

# 标记测试类(单个标签)
class TestOrder:
    
    # 给类中的所有测试方法打上order标签
    pytestmark = pytest.mark.order
    
    def test_order(self):
        print("下单")
 
    def test_pay(self):
        print("支付")
    
    
# 标记测试类(多个标签)
class TestOrder:
    
    # 给类中的所有测试方法打上order、smoke标签
    pytestmark = [pytest.mark.order, pytest.mark.smoke]
    
    def test_order(self):
        print("下单")
 
    def test_pay(self):
        print("支付")

执行的时候加上参数-m加标签名即可。

注:在测试模块中直接使用pytest.main()执行当前模块中的被打标签的用例是无效的,我们需要将执行代码分离出来,放在单独的执行模块里面,如放在run.py里,代码如下:

# run.py
 
import pytest
 
if __name__ == '__main__':
    pytest.main(["-s", "-m", "smoke or order"])

总结

pytest的标记功能让我们能够为测试用例添加元数据,使得测试用例能够更灵活地进行分类和选择性地运行。合理地使用标记,可以提高测试的组织性和可维护性,并且让测试执行更具效率。通过标记,你可以更好地管理和执行测试,提高代码质量和稳定性。希望本文能够帮到大家!

获取更多技术资料,请点击!

推荐

Python全栈开发与自动化测试开发班
由浅入深实战进阶,从小白到高手

以Python全栈开发为基础,深入教授自动化测试技能,为学员打造全面的技术能力。通过系统学习和实际项目实战,学员将具备在职场中脱颖而出的竞争力。不仅能够灵活运用Python进行开发,还能够保障项目质量通过自动化测试手段。这是一个全面提升职业竞争力的机会。

课程详情
Python开发必备基础技能与项目实战
Pvthon 编程语言/算法和数据结构/面向对象编程Web后端开发/前端开发/测试管理平台项目实战

人工智能ChatGPT实战
人工智能辅助学习各种开发和测试技能/Pytorch深度学框架/平台开发实战

数据分析与自动化办公
数据采集/Pandas与数据处理技术/ECharts与数据可视化技术/爬虫实战/自动化办公/批量文件处理

UI自动化测试与高级项目实战
Web自动化测试/App自动化测试/ PageObject设计模式

接口自动化测试
接口协议分析/Mock实战/服务端接口测试

性能测试
性能测试流程与方法/JMeter 脚本参数化/Grafana监控系统搭建

简历指导与模拟面试
1V1简历指导/模拟真实面试/测试开发岗面试全攻略名企私教服务
名企专家1v1辅导/行业专家技术指导/针对性解决工作难题/绩效提升辅导与晋升复盘

课程亮点
名企私教服务 先学习后付费 高额奖学金
专属社群+晚自习在线答疑
5V1全方位辅导作业+考试强化学习效果
简历修改 模拟面试 就业内推 面试复盘