0
点赞
收藏
分享

微信扫一扫

pytest + yaml 框架 -16.提供一个常用的内置函数和方法生成随机测试数据

前言

在测试的过程中经常会用到一些随机值,比如生成随机手机号,随机身份证,姓名等数据。

内置方法

目前暂时提供了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模块提

内置函数使用示例

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位字符串

以上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': '王建平', 't



举报

相关推荐

一个提供在线版框架的网站

0 条评论