本文共 1354 字,大约阅读时间需要 4 分钟。
今天在使用 pytest 执行测试用例时,我发现 pytest 的用例执行顺序与 unittest 有很大不同。pytest 提供了默认的执行顺序,也允许自定义执行顺序,而 unittest 则默认按 ASCII 码顺序加载测试用例,顺序为 0-9、A-Z、a-z,依次执行测试目录、测试模块、测试类和测试方法。
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/