博客
关于我
Pytest框架 之【用例执行顺序】
阅读量:799 次
发布时间: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/

你可能感兴趣的文章
Python - 安装了扩展的远程 Webdriver
查看>>
python - 将字符串中的日期与今天的日期进行比较
查看>>
python - 数据描述符(class 内置 get/set/delete方法 )
查看>>
Python - 根据值绘制彩色网格
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 类 __hash__ 方法和集合
查看>>
Python - 轻松将文本文件内容转换为字典值/键
查看>>
Python - 递归和列表
查看>>
python -- 小数据池 is和 == 再谈编码
查看>>
Python -- 算法实现
查看>>
python --- 元组(tuple)
查看>>
python --- 列表(list)
查看>>
python --- 协程
查看>>
python --- 字符串 str
查看>>
python ----元组方法以及修改细节
查看>>
python ----字典dict
查看>>
python / 解决 pyinstaller 打包后运行时提示找不到模块的问题
查看>>
Python 10 个习惯用法,短平快第一期
查看>>