Pytest测试框架一、引言测试框架抽象出来的工具集合提供大量组件、工具、功能用例发现用例管理环境管理用例执行测试报告大部分语言都有测试框架javajunittestngpythonunittestpytest二、启动与规则1. 安装在终端命令行安装pip install pytest #安装 pip install pytest-U #升级到最新版 pip show pytest #终端查看安装目录2. 启动在python中编写一个测试用例test_simple.pydeftest_addition():#测试用例验证基本算术 assert112#assert是pytest的断言如果表达式为True则测试通过 deftest_multiplication():a2b3assert a*b4终端命令行启动pytest test_simple.py #或直接输入Pytest运行全部用例代码启动同文件夹下创建一个新的文件main.pyimport pytest pytest.main()3. 结果输出启动后运行结果如下 test session starts platform win32 -- Python 3.12.9, pytest-9.0.2, pluggy-1.6.0 rootdir: E:\ruance\code collected 2 items test_simple.py .F [100%] FAILURES _______________________________________ test_multiplication _______________________________________ def test_multiplication(): a 2 b 3 assert a*b 4 E assert (2 * 3) 4 test_simple.py:7: AssertionError short test summary info FAILED test_simple.py::test_multiplication - assert (2 * 3) 4 1 failed, 1 passed in 0.15s 代表分别为执行环境版本、根目录、用例数量执行过程文件名称、用例结果、执行进度失败详情用例内容、断言提示整体摘要结果情况、结果数量、花费时间用例结果缩写如下缩写单词含义.passed通过Ffailed失败用例执行时报错Eerror出错fixture执行时报错sskipped跳过Xxpassed预期外的通过不符合预期xxfailed预期内的失败符合预期4. 用例规则4.1 用例发现规则测试框架在识别、加载用例的过程称为用例发现pytest的用例发现步骤遍历所有目录例外 venv 或 . 开头的目录打开python文件test_ 开头或者 _test 结尾的文件遍历所有的Test开头类收集所有的 test_ 开头的函数或方法4.2 用例内容规则Pytest 对用例的要求可调用的函数、方法、类、对象名字 test_ 开头没有参数参数有另外的含义没有返回值默认为None5. 配置框架配置可以改变 pytest 默认的规则命令参数ini配置文件所有的配置方式可以获取pytest -h哪些配置分别什么方式-开头参数小写字母开头ini配置大写字母开头环境遍历配置文件pytest.ini常用参数-v增加详细程度-s在用例中正常的使用输入输出-x快速退出当遇到失败的用例停止执行-m用例筛选6. 标记mark标记可以让用例与众不同进而可以被筛选的6.1 用户自定义标记用户自定义标记只能实现用例筛选步骤:先注册 (ini文件)[pytest] #注册mark markers api: 接口测试 web: UI测试 ut: 单元测试 login: 登录相关 pay: 支付相关再标记import pytest def add(a,b): return ab class TestAdd: # 方法类 pytest.mark.api # 标记mark def test_add1(self): # 函数 res add(1,3) assert res 4 pytest.mark.ui def test_add2(self): res add(1,3) assert res 13 pytest.mark.pay def test_add3(self): res add([1],[3]) assert res [1,3] def test_input(): a input(number)后筛选pytest -m web6.2 框架内置标记用户自定义标记为用例增加特殊执行效果和用户自定义标记区别不需注册可直接使用不仅可筛选还可增加特殊效果不同的标记增加不同的特殊效果skip 无条件跳过skipif有条件跳过xfail预期失败parametrize: 参数化usefixtures: 使用fixture数据驱动测试 参数化测试 数据文件根据数据文件的内容动态决定用例的数量、内容7. 数据驱动测试参数数据文件驱动用例执行数量、内容创建data.csva,b,c 1,1,2 2,3,5 3,3,6 4,4,7用例pytest.mark.ddt pytest.mark.parametrize( a,b,c, read_csv(data.csv) ) def test_ddt(self,a,b,c): res add(int(a),int(b)) assert res int(c)8. 夹具fixture夹具在用例执行之前、执行之后自动运行代码场景之前加密参数 / 之后解密结果之前启动浏览器 / 之后关闭浏览器之前注册、登录账号 / 之后删除账号8.1 创建fixturepytest.fixture def f(): # 前置操作 yield # 开始执行用例 # 后置操作创建函数添加装饰器添加yield关键字8.2 使用fixture在用例参数列表中加入fixture名字即可给用例加上“usefixture”标记def test_1(f): pass pytest.mark.usefixtures(f) def test_2(): pass全部自动执行pytest.fixture(autouseTrue)8.3 高级用法自动使用依赖使用linux使用linux进行编译git使用git进行版本控制fixture使用fixture进行前后置自动操作返回内容接口自动化封装接口关联范围共享默认范围function全局范围session使用conftest.py9. 插件管理pytest插件生态是pytest的优势之处插件类型分为两类不需要安装内置插件需要安装第三方插件插件的启用管理启用-pabc禁用**-p no: **abc插件使用方式参数配置文件fixturemark10. 常用第三方插件pytest有1400插件https://docs.pytest.org/en/stable/reference/plugin_list.html10.1 pytest-html用途生成HTML测试报告安装pip install pytest-html使用pytest --htmlreport.html --self-contained-html写入pytest.ini配置文件中--htmlreport.html --self-contained-html10.2 pytest-xdist用途分布式执行安装pip install pytest-xdist使用pytest -n N只有在任务本身耗时长超出调用成本很多的时候才有意义分布式执行有并发问题资源竞争、乱序10.3 pytest-rerunfailures用途用例失败之后重新执行安装pip install pytest-rerunfailures使用--reruns 5 --reruns-delay 110.4 pytest-result-log用途把用例的执行结果记录到日志文件中安装pip install pytest-result-log使用写入pytest.ini配置文件中log_file ./logs/pytest.log log_file_level INFO log_file_format %(levelname)-8s %(asctime)s [%(name)s:%(lineno)s] :%(message)s log_file_date_format %Y-%m-%d %H:%M:%S # 记录用例执行结果 result_log_enable 1 # 记录用例分割线 result_log_seperator 1 # 分割线等级 result_log_level_seperate warnig # 异常信息等级 result_log_level_verbose info注意新结果会覆盖之前日志11. 企业级测试报告allureallure是一个测试报告框架安装pip install allure-pytest # 先安装 Scoop如果没有 Set-ExecutionPolicy RemoteSigned -Scope CurrentUser irm get.scoop.sh | iex # 安装 allure与所需java环境 scoop install openjdk scoop install allure配置pytest.ini--alluredir./allure-results生成并查看报告# 生成报告 allure generate --clean report # 查看报告 allure serve ./allure-results也可以main函数import pytest import os pytest.main() # 执行命令 os.system(allure generate --clean report allure serve ./allure-results)这里os功能类似于shell它让你能在 Python 代码中执行操作系统相关的命令和操作。allure支持对用例进行分组和关联敏捷开发术语allure.epic #史诗 项目 allure.feature #主题 模块 allure.story #故事 功能 allure.title #标题 用例使用相同装饰器的用例自动在同一组