pytest之测试用例执行顺序

前言

在unittest框架中,默认按照ACSII码的顺序加载测试用例并执行,顺序为:09、AZ、a~z,测试目录、测试模块、测试类、测试方法/测试函数都按照这个规则来加载测试用例。

而 pytest 中的用例执行顺序与unittest 是不一样的,pytest有默认的执行顺序,还可以自定义执行顺序。

pytest 默认执行顺序

  • 测试目录、测试模块,按照排序顺序执行

    执行顺序如下:

  • 同一测试模块下的执行顺序

    复制代码
    import pytest
    
    class TestOrder:
    
        def test_e(self):
            print("test_e")
    
        def test_4(self):
            print("test_4")
    
    
    def test_b():
        print("test_a")
    
    def test_a():
        print("test_a")
    
    def test_2():
        print("test_2")
    
    def test_1():
        print("test_1")
    
    
    if __name__ == '__main__':
        pytest.main()

    执行顺序如下:

自定义执行顺序

pytest 框架支持自定义测试用例的执行顺序,需要安装pytest-ordering插件。

安装

复制代码
pip install pytest-ordering

使用

需要使用 @pytest.mark.run(),代码如下:

复制代码
import pytest

class TestOrder:

    def test_e(self):
        print("test_e")

    def test_4(self):
        print("test_4")


def test_b():
    print("test_a")

@pytest.mark.run(order=2)
def test_a():
    print("test_a")

@pytest.mark.run(order=1)
def test_2():
    print("test_2")

def test_1():
    print("test_1")


if __name__ == '__main__':
    pytest.main()

执行顺序如下:

在测试模块中,先执行被@pytest.mark.run() 标记的测试方法/测试函数,再按默认顺序执行其他的。

总结

虽然 pytest 可以自定义测试用例执行顺序,但是实际测试用例设计的过程中,不应该让用例的执行有先后顺序,即任意单独的测试用例都是独立的完整的功能点的校验,不对其他用例有依赖。

相关推荐
测试老哥1 小时前
Postman参数化详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·postman
运维行者_3 小时前
Azure数据库监控:如何在2025年选择合适的工具
运维·服务器·网络·数据库·flask·自动化·azure
星释11 小时前
使用Appium在iOS上实现自动化
ios·appium·自动化
王磊鑫13 小时前
软件测试全攻略:Postman工具的使用
测试工具·postman
江梦寻19 小时前
最新Chrome与Selenium完美兼容指南(含驱动下载与配置)
前端·chrome·selenium·测试工具·edge·edge浏览器
宇钶宇夕20 小时前
电路图识图基础知识-电机顺序启动控制电路解析(二十二)
运维·自动化
{⌐■_■}1 天前
【ubuntu】虚拟机安装配置,sh脚本自动化,包含 apt+时间同步+docker+mysql+redis+pgsql
ubuntu·docker·自动化
奔跑吧邓邓子1 天前
探索Selenium:自动化测试的神奇钥匙
自动化测试·selenium·测试工具
葬爱家族小阿杰1 天前
python执行测试用例,allure报乱码且未成功生成报告
开发语言·python·测试用例
XxxxHe1 天前
博客系统测试报告
功能测试·测试工具