Pytest自定义用例顺序

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Pytest自定义用例顺序

葬爱家族小阿杰   2022-05-23 我要评论

Unittest用例执行顺序

unittest框架和pytest框架编写的测试用例执行顺序,默认根据ACSII码的顺序加载测试用例,数字与字母的顺序为:09,AZ,a~z。

1.对于类来说,class TestAxx 会优先于class TestBxx被执行。

2.对于方法来说,test_aaa()方法会有优先于test_bbb()被执行。

对于测试目录与测试文件来说,unittest同样是按照这个规则来加载测试用例的。

背景:

我们写接口测试用例的时候,可以按上下接口顺序给它命名test_01…test_02…test_03…等等。

这样写的弊端是用例执行顺序是: test_01<test_02<test_03<test_04<test_05…

如果我想test_04在test_03前面呢? 有人会说,直接将test_04的代码,写到test_03里面去,相当于交换上下的位置,这样是可以。

如果是刚开始写是可以,可是后期变动维护起来显然是不方便。

这样就有人写了个插件来解决了这个问题,插件:pytest-ordering

下载地址:github 上有个 pytest-ordering 插件可以控制用例的执行顺序,github插件地址https://github.com/ftobia/pytest-ordering。

安装:

pip install pytest-ordering

默认执行顺序:

import pytest
 
 
def test_01():
    print("打开浏览器")
 
def test_02():
    print("输入url")
 
def test_03():
    print("输入账号")
 
def test_04():
    print("输入密码")
 
def test_05():
    print("勾选记住用户")
 
def test_06():
    print("单击登录")

运行结果:

在测试用例目录下输入

pytest -vs test.py

使用插件执行顺序:
使用 pytest-ordering 插件后改变测试用例顺序

import pytest
 
@pytest.mark.run(order=1)
def test_01():
    print("打开浏览器")
@pytest.mark.run(order=2)
def test_02():
    print("输入url")
@pytest.mark.run(order=4)
def test_03():
    print("输入账号")
@pytest.mark.run(order=3)
def test_04():
    print("输入密码")
 
@pytest.mark.last
def test_05():
    print("勾选记住用户")
 
def test_06():
    print("单击登录")

运行结果:

还是输入命令:

pytest -vs test.py

出现这个警告不要慌,在项目目录下新建pytest.ini文件,在文件输入以下内容:


这样就实现了自定义测试用例的执行顺序。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们