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

相关推荐
Sopaco2 小时前
告别项目文档滞后:Litho(deepwiki-rs)在CI/CD中的自动化文档生成实践
运维·ci/cd·自动化
white-persist3 小时前
MCP协议深度解析:AI时代的通用连接器
网络·人工智能·windows·爬虫·python·自动化
GAOJ_K8 小时前
从汽车传动到航空航天:滚珠花键的跨领域精密革命
人工智能·科技·机器人·自动化·制造
你好龙卷风!!!18 小时前
SpringCloud,vue3应用使用AlibabaCloudToolkit自动化部署到远程服务器上的docker
云原生·自动化
小熊出擊1 天前
【pytest】finalizer 执行顺序:FILO 原则
python·测试工具·单元测试·pytest
旗讯数字1 天前
企业OCR实战:基于OCR技术实现双节差旅报销单表格解析与文字信息自动化采集
运维·自动化·ocr·表格识别
云闲不收1 天前
接口请求工具对比 apifox apipost swagger postman等
测试工具·postman
xjf77111 天前
Nx项目中使用Vitest对原生JS组件进行单元测试
javascript·单元测试·前端框架·nx·vitest·前端测试
zzywxc7871 天前
AI 在金融、医疗、教育、制造业等领域都有广泛且深入的应用,以下是这些领域的一些落地案例
人工智能·金融·自动化·prompt·ai编程·xcode
sitellla1 天前
Testify Go测试工具包入门教程
git·测试工具·其他·golang