场景一:
假设我们需要查看某个用户的个人信息,一般情况下我们需要先登录这个用户才能查看用户的个人信息,在接口自动化测试中,一般可以通过获取登录接口的token,在请求用户信息接口的时候带上这个token来实现“登录并查看用户个人信息”,这时候extract就发挥作用了,通过请求登录接口,提取登录token,将登录token写入查看用户接口。
下面上实例:
/api/get-token 获取到的token,通过变量$token 被 /api/users/$user_id 引用
- config:
name: testcase description
base_url: http://127.0.0.1:5000
variables:
device_sn: ${gen_random_string(15)}
- test:
name: /api/get-token
variables:
app_version: 2.8.6
os_platform: ios
request:
headers:
Content-Type: application/json
User-Agent: python-requests/2.18.4
app_version: $app_version
device_sn: $device_sn
os_platform: $os_platform
json:
sign: ${get_sign($device_sn, $os_platform, $app_version)}
method: POST
url: /api/get-token
extract:
token: content.token
validate:
- eq: [status_code, 200]
- eq: [headers.Content-Type, application/json]
- eq: [content.success, true]
output:
token
- test:
name: /api/users/$user_id
variables:
# user_id: ${gen_random_userid(4)}
user_id: $user_id
request:
headers:
Content-Type: application/json
User-Agent: python-requests/2.18.4
device_sn: $device_sn
token: $token
json:
name: user1
password: '123456'
method: POST
url: /api/users/$user_id
validate:
- eq: [status_code, 201]
- eq: [headers.Content-Type, application/json]
- eq: [content.success, true]
- eq: [content.msg, user created successfully.]
output:
user_id
应用场景二:
查看某个用户的购买记录,假设这一场景需要通过调用两个接口实现,即通过调用登录接口获取用户的userid字段,用户购买记录接口的请求参数即为userid。
实现方法:
通过调用登录接口,获取并提取response内容,例如userid,再设置变量$userid,传入购买记录接口。
实例:
假设我们返回的数据格式如下,这时候我们要提取 userPhone
{
"success":true,
"statuscode":200,
"errorcode":0,
"errormsg":null,
"data":{
"userCity":"",
"designerFlag":false,
"userFrom":"EPS10",
"userOrganize":"df74f270-ac9b-4407-a46f-89898987777fff",
"userAuthState":0,
"isAutoPay":0,
"userNo":"RP201810291150907",
"userPhone":"13088889981",
"userOrgPackage":{
"orgPackageStatetime":"2020-01-19T11:39:52.000+0000",
"orgPackageSt":"2020-01-19T11:38:54.000+0000",
"orgPackageEt":"2021-01-19T11:38:54.000+0000",
"orgPackageRemark":null,
"orgPackageBuyMethod":1,
"orgPackagePayMethod":1,
"orgPackagePrice":0,
"orgPackagePriceRemark":null,
"orgPackageCt":"2020-01-19T11:39:52.000+0000",
"orgPackageUt":"2020-01-19T11:39:52.000+0000"
}
}
}
关于content对象
content对象相当于request中的r.content,content对象的提取方式有两种,
content.key 和 content.int,关于提取list中的字段,用的方法是content.int
例如:
content.statuscode:提取的是 "statuscode":200的值 200
content.data.userPhone:提取的是 "userPhone":"13088889981"的值 13088889981
HttpRunner,从零到熟练运用,个人实战总结请见:https://www.yuque.com/zaygee/httprunner