标题
python pytest 测试实战2
课程价值
- 掌握 pytest fixture 用法
- 掌握 pytest 常用插件
- 掌握 allure
- 了解 pytest hook 函数
大纲
- pytest fixture 高级用法
- conftest.py 用法
- pytest 配置
- pytest 常用插件
- allure 生成测试报告
- pytest hook 函数
时长
180分钟
PPT
https://pdf.ceshiren.com/xly3/python-pytest测试实战2
实战内容
参考资料
- allure 下载: https://repo1.maven.org/maven2/io/qameta/allure/allure-commandline/2.13.7/
- hook 函数:_pytest.hookspec — pytest documentation
fixture
定义
@pytest.fixture()
def fixture_method():
print("setup 操作")
yield
print("teardown 操作")
调用方式
- 测试用例中传入 fixture 方法名
@pytest.mark.usefixtures("fixture 方法名")
- 自动调用
@pytest.fixture(autouse=True)
作用域
- 控制方法:
@pytest.fixture(scope="")
- scope 的取值
- function 默认值
- class
- module
- session
fixture 方法返回值获取
- 把返回值写到 fixture 方法的 yield 后面
- 在测试用例中使用 fixture 方法名获取返回值
conftest.py 用法
- conftest.py 文件名是不能改变的
- conftest.py 和要运行的用例需要在同一个包下面
- conftest.py 生效遵循就近原则
pytest 配置
- 写在 pytest.ini 文件中
- pytest 的主配置文件,一般放在项目工程的根目录
- 指定 pytest 的运行方式
- 不能使用任何中文符号
[pytest]
markers = add
div
sub
mul
;运行时的参数
addopts = -vs
;自定义测试文件命名规则
;python_files = check_* test_*
;自定义测试类命名规则
;python_classes = Check* Test*
;自定义测试方法命名规则
;python_functions= test_* check_*
; 指定执行路径
testpaths = sub_demo
; 忽略路径
norecursedirs = datas
pytest 常用插件
pip install pytest-rerunfailures 失败重跑
pip install pytest-assume 多重较验
pip install pytest-ordering 控制用例的执行顺序
pip install pytest-xdist 分布式并发执行测试用例
pip install pytest-html 测试报告
pip install pytest-sugar 命令行显示美化
allure 生成测试报告
安装
- 本地工具安装:下载zip包,解压zip包,把 bin 目录配置到环境变量
- 安装 pytest 插件:
pip install allure-pytest
用法 - 生成 allure 测试结果:pytest —alluredir=./result
- 展示报告:allure serve ./result
- 生成最终版本的报告:allure generate ./result
- 清除上一次的记录:allure generate result --clean result/html -o result/html
- 打开报告:allure open -h 127.0.0.1 -p 8883 ./result/
pytest hook 函数
- hook 函数定义在 conftest.py 文件中
- pytest_collection_modifyitems 收集上来的测试用例实现定制化功能
课后作业
- 补全计算器(加减乘除)的测试用例
- 使用数据的数据驱动,完成加减乘除用例的自动生成
- 创建 fixture 方法实现执行测试用例前打印【开始计算】,执行测试用例之后打印【计算结束】
- 控制测试用例顺序按照【加-减-乘-除】这个顺序执行
- 结合allure 生成测试结果报告