pytest + yaml 框架 -8.一个yaml 文件可以支持多个用例了
前言
一个yaml 文件中可以写多个用例,yaml 文件相当于py模块,每个用例相当于模块里面定义 pytest 的一个函数,
用例名称最好是test开头,如果不是test开头,也会帮你自动拼接成test开头的
pip 安装插件
pip install pytest-yaml-yoyo
yaml 文件写多个用例功能在 v1.0.6 版本上实现
基本用例执行
在pytest 用例中,我们可以在一个模块写多个函数式的用例,每个用例test开头,如下
import pytest
def test1():
"""用例1"""
print("hello 111")
def test2():
"""用例2"""
print("hello 222")
def test3():
"""用例3"""
print("hello 333")
if __name__ == '__main__':
pytest.main(['-s', 'test_sample.py'])
执行后会看到3个用例
collected 3 items
test_sample.py hello 111
.hello 222
.hello 333
.
=============== 3 passed in 0.01s ===========
根据以上pytest的基本运行原理,于是我们也可以在yaml文件中写出同等的效果
test1:
name: 用例1
print: hello 11111
test2:
name: 用例2
print: hello 22222
test3:
name: 用例3
print: hello 3333
输入pytest 运行yaml 用例文件
(venv) D:\demo>pytest test_case.yml -s
=================================== test session starts ===================================
platform win32 -- Python 3.8.5, pytest-7.2.0, pluggy-1.0.0
collected 3 items
test_case.yml hello 11111
.hello 22222
.hello 3333
.
==================================== 3 passed in 0.15s ====================================
可以看出执行效果是完全一样的
重新定义了yaml用例格式
为了框架的可扩展性,config 和 teststeps 都不是必须的了,当然以前的格式还是会兼容
config:
name: demo
teststeps:
-
name: GET请求示例
request:
method: GET
url: http://httpbin.org/get
validate:
- eq: [status_code, 200]
test1:
name: 用例1
print: hello 11111
test2:
name: 用例2
print: hello 22222
用例部分支持2种格式,可以是一个键值对格式
test1:
name: 用例1
print: hello 11111
也可以是一个list
test1:
-
name: 用例1
print: hello 11111
如果一个用例有多个步骤需要执行,那么用例应该是一个list,会按顺序去执行
config:
name: demo
test1:
name: 用例1
print: hello 11111
test2:
-
name: get
request:
method: GET
url: http://httpbin.org/get
validate:
- eq: [status_code, 200]
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: test
password: "123456"
validate:
- eq: [status_code, 200]
支持中文命名
用例的函数名称也可以使用中文命名了,这样更直观
config:
name: demo
用例演示1:
name: 用例1
print: hello 11111
用例是多个步骤2:
-
name: get
request:
method: GET
url: http://httpbin.org/get
validate:
- eq: [status_code, 200]
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: test
password: "123456"
validate:
- eq: [status_code, 200]
原有的用例规则不变,只是teststeps
不是必须的关键字,可以用其它的名称,也可以继续使用teststeps
(为了兼容大家的使用习惯)
完整的教程已上传到gitee https://gitee.com/yoyoketang/pytest-yaml-yoyo上,如果觉得对你有帮助,可以给个 star
网易云完整视频课程https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
报名咨询wx:283340479 (已报名的同学学习过程中有问题,都可以协助解决)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-12-06 关于面试总结3-SQL查询