pytest:指定测试用例执行顺序

在自动化测试中,测试用例的执行顺序有时对测试结果具有重要影响。本文将介绍如何在pytest框架中使用pytest-ordering插件以及Collection hooks来控制测试用例的执行顺序。

方式1: 使用pytest-ordering插件控制执行顺序

1.1 安装pytest-ordering插件

首先,需要安装pytest-ordering插件。可以通过pip命令安装:

bash 复制代码
pip install pytest-ordering
使用序号指定执行顺序

示例代码:

python 复制代码
import pytest

@pytest.mark.run(order=2)
def test_login():
    print("Executing test case:login")
    
@pytest.mark.run(order=-1)
def test_create_order():
    print("Executing test case:create_order")

@pytest.mark.run(order=1)
def test_register():
    print("Executing test case:register")

在这个示例中,首先执行test_register,其次执行test_login,最后执行create_order。

使用函数名指定执行顺序

示例代码:

python 复制代码
import pytest


@pytest.mark.run(after='test_register')
def test_login():
    print("Executing test case:login")

@pytest.mark.run(after='test_login')
def test_create_order():
    print("Executing test case:create_order")

@pytest.mark.run(order=1)
def test_register():
    print("Executing test case:register")

在这个示例中,首先执行test_register,其次执行test_login,最后执行create_order。

使用序数词指定执行顺序

安装插件后,可以通过用序数词(如first, second, third等)作为装饰器参数来指定测试用例的执行顺序。

示例代码:

python 复制代码
import pytest

@pytest.mark.run('last')
def test_create_order():
    print("Executing test case:create_order")

@pytest.mark.run('second')
def test_login():
    print("Executing test case:login")

@pytest.mark.run('first')
def test_register():
    print("Executing test case:register")

在这个示例中,首先执行test_register,其次执行test_login,最后执行create_order。

方式2:使用Collection hooks控制执行顺序

2.1 理解Collection hooks

Collection hooks是pytest的一个特性,允许在测试用例收集阶段进行自定义操作。可以通过实现pytest_collection_modifyitems钩子来控制测试用例的执行顺序。

2.2 实现Collection hooks

创建一个conftest.py文件,并在其中实现pytest_collection_modifyitems钩子,可以按参照以下代码,控制它们的执行顺序:

python 复制代码
import pytest

def pytest_collection_modifyitems(config, items):
    # 根据需要对items进行排序
    specified_order = ["test_case_2", "test_case_1"] # 指定测试用例执行顺序
    items.sort(key=lambda x: specified_order.index(x.name.split("[")[0]) if x.name.split("[")[0] in specified_order else float('inf'))
测试用例示例

假设有两个测试用例test_case_1test_case_2

python 复制代码
# test_case.py
def test_case_1():
    print("Executing test case 1")

def test_case_2():
    print("Executing test case 2")
执行结果

3. 参考资料

相关推荐
卓码软件测评10 分钟前
第三方CMA/CNAS软件测评机构:【Apifox在Dubbo接口调试和RPC服务测试中的测试应用】
网络·测试工具·性能优化·测试用例
测试老哥11 分钟前
2026软件测试面试大全(含答案+文档)
自动化测试·软件测试·python·测试工具·面试·职场和发展·测试用例
程序员杰哥33 分钟前
接口测试之文件上传
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
测试人社区-千羽1 小时前
飞机自动驾驶系统测试:安全关键系统的全面验证框架
人工智能·安全·面试·职场和发展·自动化·自动驾驶·测试用例
兴趣使然黄小黄2 小时前
【Pytest】Pytest框架快速入门
python·pytest
少云清2 小时前
【接口测试】7_接口测试基础 _单接口和业务场景测试用例
测试用例·单接口·业务场景测试
曲莫终3 小时前
springboot集成h2内存数据库运行测试用例
数据库·spring boot·测试用例
程序员汤圆17 小时前
软件测试面试题总结【含答案】
测试工具·单元测试·测试用例
syt_biancheng17 小时前
博客系统全流程测试总结
python·selenium·测试用例·压力测试·postman
Blossom.11820 小时前
基于多模态大模型的工业质检系统:从AOI到“零样本“缺陷识别的产线实践
运维·人工智能·python·机器学习·自动化·测试用例·知识图谱