博客
关于我
Pytest框架 之【用例执行顺序】
阅读量:798 次
发布时间:2023-03-05

本文共 1354 字,大约阅读时间需要 4 分钟。

今天在使用 pytest 执行测试用例时,我发现 pytest 的用例执行顺序与 unittest 有很大不同。pytest 提供了默认的执行顺序,也允许自定义执行顺序,而 unittest 则默认按 ASCII 码顺序加载测试用例,顺序为 0-9、A-Z、a-z,依次执行测试目录、测试模块、测试类和测试方法。

pytest 默认执行顺序

pytest 的默认执行顺序是按测试目录到测试模块的顺序进行排序:

  • 测试目录 -> 测试模块 -> 测试类 -> 测试方法

这种顺序可能会导致用例执行顺序与预期不符,尤其是在测试用例名称较长时,会根据字母排序执行。

pytest 执行顺序示例

以下代码展示了同一测试模块下的用例执行顺序:

import pytestclass TestOrder:    def test_e(self):        print("test_e")    def test_4(self):        print("test_4")    def test_b(self):        print("test_b")    def test_a(self):        print("test_a")    def test_2(self):        print("test_2")    def test_1(self):        print("test_1")

运行结果为:

stu.py test_e.test_4.test_b.test_a.test_2.test_1

可以看出,用例按照预定顺序执行,但如果测试用例名称较长,会根据字母排序执行。

自定义执行顺序

为了更好地控制用例执行顺序,推荐使用 pytest-ordering 插件。安装方式如下:

pip install pytest-ordering

使用方式示例:

import pytestclass Test01:    def test_02(self):        print("\n---用例02---")        @pytest.mark.run(order=2)    def test_01(self):        print("\n---用例01---")        @pytest.mark.run(order=1)    def test_03(self):        print("\n---用例03---")        def test_04(self):        print("\n---用例04---")

运行结果为:

stu.py ---用例03---.---用例01---.---用例02---.---用例04---

需要注意的是,用例执行顺序由标记的 order 参数决定,未标记的用例则按默认顺序执行。

测试用例设计建议

在实际测试用例设计时,建议避免依赖用例执行顺序。每个测试用例应作为独立的功能点进行校验,不应对其他用例有依赖关系。

希望这篇文章能帮助您更好地理解 pytest 的用例执行顺序特性,以及如何通过 pytest-ordering 插件进行自定义配置。如有任何问题或需要进一步帮助,请随时联系我。

转载地址:http://knafk.baihongyu.com/

你可能感兴趣的文章
Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
查看>>
Project Euler 15 Lattice paths
查看>>
Project Euler 48 Self powers( 大数求余 )
查看>>
Project Euler Problem 12: Highly divisible triangular number
查看>>
ProjectEuler 2
查看>>
projection介绍及EPSG:4326和EPSG:3857的投射转换
查看>>
project打开文件时,显示无法识别此文件格式?
查看>>
Prometheus + Grafana on Kubernetes部署
查看>>
prometheus + grafana进行服务器资源监控
查看>>
Prometheus Alertmanager 告警配置详解
查看>>
Prometheus Grafana 展示平台
查看>>
Prometheus pushgateway使用详解
查看>>
Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
查看>>
Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
查看>>
Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
查看>>
Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
查看>>
Prometheus 介绍
查看>>
Prometheus 安全配置详解
查看>>
prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
查看>>
Prometheus 安装部署实战
查看>>