前言
在HttpRunner中,我們要想從當前 HTTP 請求的響應結果中提取參數,可以通過 extract 關鍵字來實現。
本人環境:HttpRunner V1.5.8
測試場景
在這里,我將以一個學生充值金幣的接口來模擬測試,這個接口在 Jmeter接口測試實例-牛刀小試 文章中有說明。
這個接口有權限驗證,我們需要先通過接口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中引用成功。