Postman 進階
1. pre-request scripts

pre-request scripts是一個關聯了收藏夾內request,並且在發送request之前執行的代碼片段。這對於在request header中包含時間戳或者在URL參數中發送一個隨機字符串都是非常有用的。
例如:如果要在request的header中包含一個時間戳,你可以設置一個環境變量由一個函數返回他的值。
postman.setEnvironmentVariable('timestampHeader',new Date());
你可以在header中使 timestampHeader 變量,當request發送的時候,你的pre-request script將被執行,這個timestampHeader 變量的值將會替換{{timestampHeader}}。
注意:我們設置的環境對使用的環境變量必須是有效的。
2.Tests
1)基本結構

Postman給了你一個環境讓你能夠為每個request編寫、執行你的test,而不用擔心任何額外的設置。
一個Postman的test本質上是JavaScript的代碼可以用來為一些特殊的test設置值。你可以在對象中設置一個描述性的鍵作為一個元素,然后聲明他如果是true或false。
tests[“Body contains user_id”] = responseBody.has(“user_id”)
這回核對body中是否包含了user_id這個字符串。如果你需要,你可以增加更多的鍵,這取決於你要用test做多少的事情。
test被保存為收藏夾request的一部分。
2)SNIPPETS
在寫test的時候這里有些事情需要注意,Postman嘗試使得列出常用的片段更簡單。你可以選擇你想添加的片段,然后適當的代碼將被添加到test的編輯器中。這是一個很好的方法來快速的構建test
3.Testing Sandbox
Postman的sandbox是一個JavaScript的執行環境,這使得你能夠為request寫pre-request scripts和test scripts 。不論你寫的代碼是pre-request scripts還是test script都會在sandbox中執行。
1.常用的庫和工具
-
Lodash:
JS utility library -
jQuery (Deprecated):
Cross-platform JavaScript library. This will be removed in future versions of the sandbox. -
BackboneJS (Deprecated):
Provides simple models, views, and collections. This will be removed in future versions of the sandbox. -
SugarJS:
Extends native JS objects with useful methods -
tv4 JSON schema validator:
Validates JSON objects against v4 of the json-schema draft -
CryptoJS:
standard and secure cryptographic algorithms. Supported algorithms: AES, DES, EvpKDF, HMAC-MD5, HMAC-SHA1/3/256/512, MD5, PBKDF2, Rabbit, SHA1/3/224/256/512, TripleDES -
xml2Json(xmlString)
:
This function behaves the same in Newman and Postman -
xmlToJson(xmlString)
(Deprecated):
This function does NOT behave the same in Newman and Postman -
postman.getResponseHeader(headerName)
(Test-only):
returns the response header with name "headerName", if it exists. Returns null if no such header exists. Note: According to W3C specifications, header names are case-insensitive. This method takes care of this.
postman.getResponseHeader("Content-type") and postman.getResponseHeader("content-Type") will return the same value.
2.動態變量
Postman也有一些動態變量,你可以用在你的request中。這個現在主要還是在實現階段,更多的功能以后被被添加進來。注意:動態變量不可以用於SandBox中,你只能在request的URL、headers、body中以放在雙花括號中間的形式
-
{{$guid}}: Adds a v4 style guid {{$timestamp}}: Adds the current timestamp. {{$randomInt}}: Adds a random integer between 0 and 1000
代碼示例
注意:test腳本在從服務器收到response后執行
1.設置環境變量:
postman.setEnvironmentVariable("key", "value");
2.設置全局變量:
postman.setGlobalVariable("key", "value");
3.檢查response的body中是否包含字符串:
tests["Body matches string"] = responseBody.has("string_you_want_to_search");
4.把XML的body轉換成JSON對象:
var jsonObject = xml2Json(responseBody);
5.檢查response的body是都為一個字符串:
tests["Body is correct"] = responseBody === "response_body_string";
6.檢查JSON的值:
var data = JSON.parse(responseBody); tests["Your test name"] = data.value === 100;
7.內容類型存在(檢查不區分大小寫)
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type"); //Note: the getResponseHeader() method returns the header value, if it exists.
8.內容類型存在(區分大小寫):
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");
9.response的響應時間小於200ms:
tests["Response time is less than 200ms"] = responseTime < 200;
10.狀態碼為200:
tests["Status code is 200"] = responseCode.code === 200;
11.Code name contains a string:
tests["Status code name has string"] = responseCode.name.has("Created");
12.成功的POST request狀態碼:
tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;
13.Use TinyValidator for JSON data
var schema = { "items": { "type": "boolean" } }; var data1 = [true, false]; var data2 = [true, 123]; console.log(tv4.error); tests["Valid Data1"] = tv4.validate(data1, schema); tests["Valid Data2"] = tv4.validate(data2, schema);
Postman接口關聯測試
進行接口關聯測試,主要是將第一個接口返回的值設置為環境變量,然后再通過獲取環境變量去獲取對應第一個接口返回的值
例如,
場景:用戶先登錄系統,獲取token令牌,下一步操作購買接口使用登錄返回的token令牌進行操作,這時兩個接口就放在同一個collections文件夾;
第一個登錄接口,設置tests--環境變量設置響應的token值,
第二個購買接口,傳參{{token}}引用環境變量,進行相應的其他操作。
var jsonData = JSON.parse(responseBody); //獲取響應json格式報文 postman.setEnvironmentVariable("token", jsonData.data.result.token); //設置環境變量 token,值為jsonData.data.result.token tests["token"]=jsonData.data.result.token; //驗證響應報文里有token參數返回 tests["Body matches string"] = responseBody.has("User"); //斷言test響應報文結果是否包涵
var 定義一個變量jsonData ,設置token變量,jsonData.data.result.token 這個值是一級一級往下走的json數據
Postman 進階