最近有小伙伴提到API层的接口参数很多,全部设置为变量,后面用例引用会写很多值,会很费精力。 希望能在定义变量的时候,给默认值,这样在用例里面可以选择性的给部分参数设置变量值。
先在API层定义接口,请求参数使用default()
给变量默认值
api/post.yml
name: post
request:
method: POST
url: http://httpbin.org/post
json:
user: ${user | default("test")}
email: ${email | default("123@qq.com")}
tel: ${tel | default("123456")}
address: ${address | default("上海市")}
上面定义了四个变量user,email, tel, address并且都给了默认值。
在用例层引用API时,如果没有设置变量,那么会直接取到默认值,变量不是必须传参了
config:
name: 用例分层设置变量默认值
test_x1:
name: 引用api层
api: api/post.yml
validate:
- eq: [status_code, 200]
运行结果可以看出会用到默认值
2023-06-29 10:06:47 [INFO]: 运行用例-> test_x1
2023-06-29 10:06:47 [INFO]: 取值表达式: user | default("test"), 取值结果:test <class 'str'>
2023-06-29 10:06:47 [INFO]: 取值表达式: email | default("123@qq.com"), 取值结果:123@qq.com <class 'str'>
2023-06-29 10:06:47 [INFO]: 取值表达式: tel | default("123456"), 取值结果:123456 <class 'int'>
2023-06-29 10:06:47 [INFO]: 取值表达式: address | default("上海市"), 取值结果:上海市 <class 'str'>
2023-06-29 10:06:47 [INFO]: -------- request info ----------
2023-06-29 10:06:47 [INFO]: yml raw -->: {'method': 'POST', 'url': 'http://httpbin.org/post', 'json': {'user': 'test', '
email': '123@qq.com', 'tel': 123456, 'address': '上海市'}}
2023-06-29 10:06:47 [INFO]: method -->: POST
2023-06-29 10:06:47 [INFO]: url -->: http://httpbin.org/post
2023-06-29 10:06:47 [INFO]: headers -->: {'User-Agent': 'python-requests/2.30.0', 'Accept-Encoding': 'gzip, deflate', 'A
ccept': '*/*', 'Connection': 'keep-alive'}
2023-06-29 10:06:47 [INFO]: json -->: {"user": "test", "email": "123@qq.com", "tel": 123456, "address": "\u4e0a\u6d77
\u5e02"}
用例中也可以给设置部分变量
test_x2:
name: 引用api层
variables:
user: yoyo
address: 上海市闵行区
api: api/post.yml
validate:
- eq: [status_code, 200]
运行结果
2023-06-29 10:10:10 [INFO]: 运行用例-> test_x2
2023-06-29 10:10:10 [INFO]: 取值表达式: user | default("test"), 取值结果:yoyo <class 'str'>
2023-06-29 10:10:10 [INFO]: 取值表达式: email | default("123@qq.com"), 取值结果:123@qq.com <class 'str'>
2023-06-29 10:10:10 [INFO]: 取值表达式: tel | default("123456"), 取值结果:123456 <class 'int'>
2023-06-29 10:10:10 [INFO]: 取值表达式: address | default("上海市"), 取值结果:上海市闵行区 <class 'str'>
2023-06-29 10:10:10 [INFO]: -------- request info ----------
2023-06-29 10:10:10 [INFO]: yml raw -->: {'method': 'POST', 'url': 'http://httpbin.org/post', 'json': {'user': 'yoyo', '
email': '123@qq.com', 'tel': 123456, 'address': '上海市闵行区'}}
2023-06-29 10:10:10 [INFO]: method -->: POST
2023-06-29 10:10:10 [INFO]: url -->: http://httpbin.org/post
2023-06-29 10:10:10 [INFO]: headers -->: {'User-Agent': 'python-requests/2.30.0', 'Accept-Encoding': 'gzip, deflate', 'A
ccept': '*/*', 'Connection': 'keep-alive'}
2023-06-29 10:10:10 [INFO]: json -->: {"user": "yoyo", "email": "123@qq.com", "tel": 123456, "address": "上海市闵行区
"}
2023-06-29 10:10:10 [INFO]: ------ response info 200 OK ------
从运行结果可以看出设置的变量会替换默认值