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

相关推荐
Apifox1 小时前
【测试套件】当用户说“我只想跑 P0 用例”时,我们到底在说什么
单元测试·测试·ab测试
金銀銅鐵3 天前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
金銀銅鐵4 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
姚青&6 天前
PyCharm 配置与界面化运行
pytest
姚青&6 天前
Pytest 测试用例断言
测试用例·pytest
米码收割机6 天前
【测试平台】测试用例管理平台(前后端源码+部署文档)【独一无二】
测试用例
金智维科技官方6 天前
智能体,重构企业自动化未来
人工智能·自动化·agent·智能体·数字员工
梦想的旅途26 天前
企业微信API:外部群自动化推送实战指南
大数据·机器人·自动化·企业微信·rpa
xiaoginshuo6 天前
流程自动化从传统RPA升级到AI Agent,如何匹配合适的自动化方案
人工智能·自动化·rpa
姚青&6 天前
Pytest 命名规则
pytest