在HttpRunner中,我们要想从当前 HTTP 请求的响应结果中提取参数,可以通过 extract 关键字来实现。
在这里,我将以一个学生充值金币的接口来模拟测试,这个接口在 Jmeter接口测试实例-牛刀小试 文章中有说明。
这个接口有权限验证,我们需要先通过接口A登录,然后在接口B中进行充值操作。
- test:
name: login case
request:
url: /api/user/login
method: POST
headers:
Content-Type: application/x-www-form-urlencoded
User-Agent: Fiddler
data:
username: test1010
passwd: aA123456
extract:
- sign: content.login_info.sign
validate:
- eq: [status_code, 200]
- eq: [content.error_code, 0]
在这个接口A中,通过 extract 关键字提取 sign 值,sign 将用于后续添加cookie进行身份验证。
extract:
- sign: content.login_info.sign
- test:
name: add gold
request:
url: api/user/gold_add
method: POST
headers:
Content-Type: application/x-www-form-urlencoded
User-Agent: Fiddler
Cookie: test1010=$sign
data:
stu_id: 2114
gold: 500
validate:
- eq: [status_code, 200]
- eq: [content.error_code, 0]
- eq: [content.msg, "操作成功!"]
在这个接口B中,先添加 cookie 完成身份验证( test1010 是上一接口登录的用户),然后进行充值金币操作。
若想使用 extract 提取出来的 sign,是 $sign 的形式进行引用。
Cookie: test1010=$sign
完整的YAML格式用例如下(test_extract.yml):
- config:
name: extract test
request:
base_url: http://api.nnzhp.cn
- test:
name: login case
request:
url: /api/user/login
method: POST
headers:
Content-Type: application/x-www-form-urlencoded
User-Agent: Fiddler
data:
username: test1010
passwd: aA123456
extract:
- sign: content.login_info.sign
validate:
- eq: [status_code, 200]
- eq: [content.error_code, 0]
- test:
name: add gold
request:
url: api/user/gold_add
method: POST
headers:
Content-Type: application/x-www-form-urlencoded
User-Agent: Fiddler
Cookie: test1010=$sign
data:
stu_id: 2114
gold: 500
validate:
- eq: [status_code, 200]
- eq: [content.error_code, 0]
- eq: [content.msg, "操作成功!"]
在当前 YAML用例 的目录下,执行命令:hrun test_extract.yml
点击 log,查看报告详情,可以看到接口A中通过extract提取的数据 sign ,在接口B中引用成功。
原文:https://www.cnblogs.com/wintest/p/11779526.html