应用场景&参数关联

场景一:
假设我们需要查看某个用户的个人信息,一般情况下我们需要先登录这个用户才能查看用户的个人信息,在接口自动化测试中,一般可以通过获取登录接口的token,在请求用户信息接口的时候带上这个token来实现“登录并查看用户个人信息”,这时候extract就发挥作用了,通过请求登录接口,提取登录token,将登录token写入查看用户接口。

下面上实例:
/api/get-token 获取到的token,通过变量$token 被 /api/users/$user_id 引用

  1. - config:
  2. name: testcase description
  3. base_url: http://127.0.0.1:5000
  4. variables:
  5. device_sn: ${gen_random_string(15)}
  6. - test:
  7. name: /api/get-token
  8. variables:
  9. app_version: 2.8.6
  10. os_platform: ios
  11. request:
  12. headers:
  13. Content-Type: application/json
  14. User-Agent: python-requests/2.18.4
  15. app_version: $app_version
  16. device_sn: $device_sn
  17. os_platform: $os_platform
  18. json:
  19. sign: ${get_sign($device_sn, $os_platform, $app_version)}
  20. method: POST
  21. url: /api/get-token
  22. extract:
  23. token: content.token
  24. validate:
  25. - eq: [status_code, 200]
  26. - eq: [headers.Content-Type, application/json]
  27. - eq: [content.success, true]
  28. output:
  29. token
  30. - test:
  31. name: /api/users/$user_id
  32. variables:
  33. # user_id: ${gen_random_userid(4)}
  34. user_id: $user_id
  35. request:
  36. headers:
  37. Content-Type: application/json
  38. User-Agent: python-requests/2.18.4
  39. device_sn: $device_sn
  40. token: $token
  41. json:
  42. name: user1
  43. password: '123456'
  44. method: POST
  45. url: /api/users/$user_id
  46. validate:
  47. - eq: [status_code, 201]
  48. - eq: [headers.Content-Type, application/json]
  49. - eq: [content.success, true]
  50. - eq: [content.msg, user created successfully.]
  51. output:
  52. user_id

提取response返回数据

应用场景二:
查看某个用户的购买记录,假设这一场景需要通过调用两个接口实现,即通过调用登录接口获取用户的userid字段,用户购买记录接口的请求参数即为userid。
实现方法:
通过调用登录接口,获取并提取response内容,例如userid,再设置变量$userid,传入购买记录接口。

实例:
假设我们返回的数据格式如下,这时候我们要提取 userPhone

  1. {
  2. "success":true,
  3. "statuscode":200,
  4. "errorcode":0,
  5. "errormsg":null,
  6. "data":{
  7. "userCity":"",
  8. "designerFlag":false,
  9. "userFrom":"EPS10",
  10. "userOrganize":"df74f270-ac9b-4407-a46f-89898987777fff",
  11. "userAuthState":0,
  12. "isAutoPay":0,
  13. "userNo":"RP201810291155200907",
  14. "userPhone":"13088889981",
  15. "userOrgPackage":{
  16. "orgPackageStatetime":"2020-01-19T11:39:52.000+0000",
  17. "orgPackageSt":"2020-01-19T11:38:54.000+0000",
  18. "orgPackageEt":"2021-01-19T11:38:54.000+0000",
  19. "orgPackageRemark":null,
  20. "orgPackageBuyMethod":1,
  21. "orgPackagePayMethod":1,
  22. "orgPackagePrice":0,
  23. "orgPackagePriceRemark":null,
  24. "orgPackageCt":"2020-01-19T11:39:52.000+0000",
  25. "orgPackageUt":"2020-01-19T11:39:52.000+0000"
  26. }
  27. }
  28. }

关于content对象

content对象相当于request中的r.content,content对象的提取方式有两种,
content.key 和 content.int,关于提取list中的字段,用的方法是content.int
例如:
content.statuscode:提取的是 “statuscode”:200的值 200
content.data.userPhone:提取的是 “userPhone”:”13088889981”的值 13088889981