240
生活,简单就好!

HttpRunner学习3--extract提取数据和引用

前言

在HttpRunner中,我们要想从当前 HTTP 请求的响应结果中提取参数,可以通过 extract 关键字来实现。

本人环境:HttpRunner V1.5.8

测试场景

在这里,我将以一个学生充值金币的接口来模拟测试,这个接口在 Jmeter接口测试实例-牛刀小试 文章中有说明。

学生金币充值接口:http://doc.nnzhp.cn/index.php?s=/6&page_id=11

这个接口有权限验证,我们需要先通过接口A登录,然后在接口B中进行充值操作。

extract提取数据

在这里,登录接口返回的响应数据是 JSON 结构,如下:

{
        "error_code": 0,
        "login_info": {
                "login_time": "20191101194758",
                "sign": "e2011d7942dd5fbfebd927e05daea3c2",
                "userId": 2172
        }
}

对于 JSON 结构的响应结果,可使用 content 结合 . 运算符的方式来表示数据。

content.error_code:表示 error_code 对应的值
content.login_info.userId:表示 userId 对应的值

YAML格式用例如下:

- 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中引用成功。

posted @ 2019-11-01 20:51  wintest  阅读(3473)  评论(2编辑  收藏  举报