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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM