pytest + yaml 框架 -16.提供一些常用的内置函数和方法生成随机测试数据
前言
在测试的过程中经常会用到一些随机值,比如生成随机手机号,随机身份证,姓名等数据。
pip 安装插件
pip install pytest-yaml-yoyo
内置函数功能在 v1.1.2 版本实现
内置方法
目前暂时提供了3个内置函数,和1个内置对象
- current_time(f: str = '%Y-%m-%d %H:%M:%S'), 获取当前时间 默认格式为2022-12-16 22:13:00,可以传f参数自定义格式
- rand_value(target: list) 从返回的 list 结果随机取值, 有小伙伴提到的需求
- rand_str(len_start=None, len_end=None) 生成随机字符串,默认32位
还提供了一个内置的fake 对象,可以生成随机手机号,随机身份证,姓名等数据
使用方法:${fake.name()}, fake.phone_number(), fake.email() 等,具体查看Faker模块提供的方法https://www.cnblogs.com/yoyoketang/p/14869348.html
内置函数使用示例
current_time() 获取当前时间, 使用示例
获取当前时间:
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: ${current_time()}
password: "123456"
validate:
- eq: [status_code, 200]
rand_value(target: list) 从返回的 list 结果随机取值, 有小伙伴提到的需求
提取list值:
-
request:
method: POST
url: http://httpbin.org/post
json:
data: ["hello", "world", "hello world"]
extract:
res: $.json.data
validate:
- eq: [status_code, 200]
随机取一个结果:
-
request:
method: GET
url: http://httpbin.org/get
params:
key: ${rand_value(res)}
validate:
- eq: [status_code, 200]
rand_str(len_start=None, len_end=None) 生成随机字符串,默认32位
rand_str 使用方法:
${rand_str()} 得到32位字符串
${rand_str(3)} 得到3位字符串
${rand_str(3, 10)} 得到3-10位字符串
生成json数据:
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: ${rand_str(5, 10)}
password: ${rand_str(3)}
validate:
- eq: [status_code, 200]
以上yaml,生成的json数据示例
"json": {
"password": "07d",
"username": "c1c91161b4"
}
fake 对象的使用
内置的 fake 对象 (注意是fake,不是faker, 因为faker 是模块名称,避免冲突) ,可以生成随机手机号,随机身份证,姓名等数据
获取当前时间:
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
name: ${fake.name()}
tel: ${fake.phone_number()}
email: ${fake.email()}
validate:
- eq: [status_code, 200]
生成的测试数据
{'name': '王建平', 'tel': 13056609***, 'email': 'jluo@example.net'}
其它更多方法参考Faker模块提供的方法https://www.cnblogs.com/yoyoketang/p/14869348.html
网易云完整视频课程https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
报名咨询wx:283340479 (已报名的同学学习过程中有问题,都可以协助解决)

浙公网安备 33010602011771号