一、Pre Request Scripts
Postman v0.10+ 版本支援pre-request scripts。

prerequest script.png
pre-request scripts是一個關聯了收藏夾内request,并且在發送request之前執行的代碼片段。這對于在request header中包含時間戳或者在URL參數中發送一個随機字元串都是非常有用的。
例如:如果要在request的header中包含一個時間戳,你可以設定一個環境變量由一個函數傳回他的值。
postman.setEnvironmentVariable('timestampHeader',new Date());
你可以在header中使 timestampHeader 變量,當request發送的時候,你的pre-request script将被執行,這個timestampHeader 變量的值将會替換{{timestampHeader}}。
注意:我們設定的環境對使用的環境變量必須是有效的。
二、Writing Tests
1.基本結構
![Uploading prerequest script_871640.png . . .]
Basic structure.png
Postman給了你一個環境讓你能夠為每個request編寫、執行你的test,而不用擔心任何額外的設定。
一個Postman的test本質上是JavaScript的代碼可以用來為一些特殊的test設定值。你可以在對象中設定一個描述性的鍵作為一個元素,然後聲明他如果是true或false。
tests[“Body contains user_id”] = responseBody.has(“user_id”)
這回核對body中是否包含了user_id這個字元串。如果你需要,你可以增加更多的鍵,這取決于你要用test做多少的事情。
test被儲存為收藏夾request的一部分,這對于後端或前端的工程師來確定API運作的正常都是非常有意義的。
2.SNIPPETS
在寫test的時候這裡有些事情需要注意,Postman嘗試使得列出常用的片段更簡單。你可以選擇你想添加的片段,然後适當的代碼将被添加到test的編輯器中。這是一個很好的方法來快速的建構test
3.檢視結果
view result.png
Postman在你執行一個request的時候執行test,當然你可以選擇不考慮test。結果被顯示在一個tab裡,并在頭部顯示多少test通過了測試。你設定在test中的變量将會被列在這裡。如果值是true,這個test就會通過。你可以保持test tab活動直到你確定所有的test執行完。
三、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.環境和全局變量
-
: Sets an environment variable "variableName", and assigns the string "variableValue" to it. You must have an environment selected for this method to work. Note: Only strings can be stored. Storing other types of data will result in unexpected behavior.postman.setEnvironmentVariable(variableName, variableValue)
-
postman.setGlobalVariable(variableName, variableValue)
:
Sets a global variable "variableName", and assigns the string "variableValue" to it. Note: Only strings can be stored. Storing other types of data will result in unexpected behavior.
-
postman.clearEnvironmentVariable(variableName)
:
Clears the environment variable named "variableName". You must have an environment selected for this method to work.
-
postman.clearGlobalVariable(variableName)
:
Clears the global variable named "variableName".
-
postman.clearEnvironmentVariables()
:
Clears all environment variables. You must have an environment selected for this method to work.
-
postman.clearGlobalVariables()
:
Clears all global variables.
-
environment
:
A dictionary of variables in the current environment. Use environment["foo"]
to access the value of the "foo" environment variable.
-
globals
:
A dictionary of global variables. Useglobals["bar"]
to access the value of the "bar" global variable.
3.動态變量
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
4. Cookies
+ responseCookies {array} (Postman-only):
Gets all cookies set for the domain. You will need to enable the Interceptor for this to work.
-
postman.getResponseCookie(cookieName)(Postman-only):
Gets the response cookie with the given name. You will need to enable the interceptor for this to work. Check out the blog post.
5.Request/response相關屬性
-
request {object}:
Postman makes the request object available to you while writing scripts. This object is read-only. Changing properties of this object will have no effect. Note: Variables will NOT be resolved in the request object. The request object is composed of the following:
-
data {object}:
this is a dictionary of form data for the request. (request.data["key"]=="value")
-
headers {object}:
this is a dictionary of headers for the request (request.headers["key"]=="value")
-
method {string}:
GET/POST/PUT etc.
-
url {string}:
the url for the request.
-
-
responseHeaders {object}(Test-only)(Deprecated):
This is a map of the response headers. This is case-sensitive, and should not be used. Check thepostman.getResponseHeader()
method listed above.
-
responseBody {string}(Test-only):
A string containing the raw response body text. You can use this as an input to JSON.parse, or xml2Json.
-
responseTime {number}(Test-only):
The response time in milliseconds
-
responseCode {object}(Test-only):
Contains three properties:
-
code {number}:
The response code (200 for OK, 404 for Not Found etc)
-
name {string}:
The status code text
-
detail {string}:
An explanation of the response code
-
-
tests {object}(Test-only):
This object is for you to populate. Postman will treat each property of this object as a boolean test.
-
iteration {number}:
Only available in the Collection Runner and Newman. Represents the current test run index. Starts from 0.
(Test-only): This object is only available in the test script section. Using this in a pre-request script will throw an error.
四、Testing 執行個體
我們來看一些Postman用于test的例子。這些例子中的大多數在Postman中是有效的,他們像一行JavaScript語句一樣簡答。在你的request中你可以有很多的test。
注意:test腳本在從伺服器收到response後執行
1.設定環境變量:
postman.setEnvironmentVariable("key", "value");
2.設定全局變量:
postman.setGlobalVariable("key", "value");
3.檢查response的body中是否包含字元串:
4.把XML的body轉換成JSON對象:
var jsonObject = xml2Json(responseBody);
5.檢查response的body是都為一個字元串:
6.檢查JSON的值:
var data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;
7.内容類型存在(檢查不區分大小寫)
8.内容類型存在(區分大小寫):
9.response的響應時間小于200ms:
10.狀态碼為200:
11.Code name contains a string:
12.成功的POST request狀态碼:
13.Use TinyValidator for JSON data
var schema = {
"items": {
"type": "boolean"
}
};
var data1 = [true, false];
var data2 = [true, ];
console.log(tv4.error);
tests["Valid Data1"] = tv4.validate(data1, schema);
tests["Valid Data2"] = tv4.validate(data2, schema);
14.Sample data files
JSON files are composed of key/value pairs:
Download JSON file
For CSV files, the top row needs to contain variable names
Download CSV file
Postman 使用手冊系列教程:
Postman軟體安裝
Postman使用手冊1——導入導出和發送請求檢視響應
Postman使用手冊2——管理收藏
Postman使用手冊3——環境變量
Postman使用手冊4——API test