Pytest测试框架
特点:
1、非常容易上手,入门简单,文档丰富,稳定中有很多参考实例
2、支持简单的单元测试和复杂的功能测试
3、支持参数化
4、执行测试用例过程中,支持跳过操作
5、支持重复执行失败的case
6、支持运行有Nose,unitest编写的测试用例
7、pytest支持很多第三方插件
8、方便和持续集成工具集成
1、pytest 配置文件 pytest.ini ---注意文件中不能包含中文 pytest.ini文件不支持注释,所以文件中一定不能有注释
[pytest] addopts = -s -v --html=report/report.html# 标识pytest执行时增加的参数 -s代表控制台输出结果,如果代码里有print 就在控制台输出,-v表示打印详细运行日志 testpath = ./testpro #匹配搜索的目录 python_files = test_*.py #匹配测试文件 python_classes = Test* # 匹配测试类 python_functions = test* # 匹配测试方法
2、生成测试报告--安装插件pytest-html插件
在配置文件中设置html命令即可,注意文件夹 report需要手动创建,直接运行pytest.main()即可生成测试报告,比unitest要简单很多
addopts = -s -v --html=report/report.html
3、控制执行顺序
-unitest 测试用例执行顺序是根据测试方法名称的assII码值的大小来的 0-9,a-z
unitest官方文档:https://docs.python.org/zh-cn/3/library/unittest.html
-pytest 正常情况下是根据代码写的测试方法的顺序来执行的,可以通过pytest-ordering 插件来控制pytest测试用例执行的顺序。
-使用 装饰器 @pytest.mark.run(order=x) # x表示的是整数 既可以是正数也可以是负数,
-全为负数或者正数时值越小,优先级越高
-既有正数又有负数时,正数优先级高
-没有确定执行顺序的用例优先于负数
@pytest.mark.last # 设置用例最后执行
4、失败重试
pytest-rerunfaliues 插件安装
使用 在配置文件中配置
addopts = -s -v --reruns 3 --html=./report.html
直接运行代码 可以看到日志中运行失败的重复执行了三次
RERUN test_01.py::Test_Function::test_add[1-2-4] running setup before function running teardown after funtion RERUN test_01.py::Test_Function::test_add[1-2-4] running setup before function running teardown after funtion RERUN test_01.py::Test_Function::test_add[1-2-4] running setup before function running teardown after funtion FAILED
5、参数化
@pytest.mark.parametrize("x,y,expect", [(1, 2, 4), (3, 4, 7)])
装饰器接收两个参数:一个是变量,一个是变量的取值
@pytest.mark.parametrize("x,y,expect", [(1, 2, 4), (3, 4, 7)]) @pytest.mark.run(order=3) def test_add(self, x, y, expect): assert add(x, y) == expect