Postman使用手冊4——API test

一如绸、Pre Request Scripts

Postman v0.10+ 版本支持pre-request scripts峡扩。

prerequest script.png

pre-request scripts是一個關(guān)聯(lián)了收藏夾內(nèi)request,并且在發(fā)送request之前執(zhí)行的代碼片段咪辱。這對于在request header中包含時間戳或者在URL參數(shù)中發(fā)送一個隨機字符串都是非常有用的棋电。

例如:如果要在request的header中包含一個時間戳茎截,你可以設(shè)置一個環(huán)境變量由一個函數(shù)返回他的值。

postman.setEnvironmentVariable('timestampHeader',new Date());

你可以在header中使 timestampHeader 變量赶盔,當(dāng)request發(fā)送的時候企锌,你的pre-request script將被執(zhí)行,這個timestampHeader 變量的值將會替換{{timestampHeader}}于未。

注意:我們設(shè)置的環(huán)境對使用的環(huán)境變量必須是有效的撕攒。

二、Writing Tests

1.基本結(jié)構(gòu)


![Uploading prerequest script_871640.png . . .]


Basic structure.png

Postman給了你一個環(huán)境讓你能夠為每個request編寫烘浦、執(zhí)行你的test抖坪,而不用擔(dān)心任何額外的設(shè)置。

一個Postman的test本質(zhì)上是JavaScript的代碼可以用來為一些特殊的test設(shè)置值闷叉。你可以在對象中設(shè)置一個描述性的鍵作為一個元素柳击,然后聲明他如果是true或false。

tests[“Body contains user_id”] = responseBody.has(“user_id”) 

這回核對body中是否包含了user_id這個字符串片习。如果你需要捌肴,你可以增加更多的鍵蹬叭,這取決于你要用test做多少的事情。

test被保存為收藏夾request的一部分状知,這對于后端或前端的工程師來確保API運行的正常都是非常有意義的秽五。

2.SNIPPETS


在寫test的時候這里有些事情需要注意,Postman嘗試使得列出常用的片段更簡單饥悴。你可以選擇你想添加的片段坦喘,然后適當(dāng)?shù)拇a將被添加到test的編輯器中。這是一個很好的方法來快速的構(gòu)建test

3.查看結(jié)果


view result.png

Postman在你執(zhí)行一個request的時候執(zhí)行test西设,當(dāng)然你可以選擇不考慮test瓣铣。結(jié)果被顯示在一個tab里,并在頭部顯示多少test通過了測試贷揽。你設(shè)置在test中的變量將會被列在這里棠笑。如果值是true,這個test就會通過禽绪。你可以保持test tab活動直到你確保所有的test執(zhí)行完蓖救。

三、Testing Sandbox

Postman的sandbox是一個JavaScript的執(zhí)行環(huán)境印屁,這使得你能夠為request寫pre-request scripts和test scripts 循捺。不論你寫的代碼是pre-request scripts還是test script都會在sandbox中執(zhí)行。

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.環(huán)境和全局變量

  • postman.setEnvironmentVariable(variableName, variableValue) : 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.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.動態(tài)變量

Postman也有一些動態(tài)變量雄人,你可以用在你的request中从橘。這個現(xiàn)在主要還是在實現(xiàn)階段,更多的功能以后被被添加進來础钠。注意:動態(tài)變量不可以用于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相關(guān)屬性

  • 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的例子阵漏。這些例子中的大多數(shù)在Postman中是有效的,他們像一行JavaScript語句一樣簡答翻具。在你的request中你可以有很多的test履怯。

注意:test腳本在從服務(wù)器收到response后執(zhí)行

1.設(shè)置環(huán)境變量:

postman.setEnvironmentVariable("key", "value");

2.設(shè)置全局變量:

 postman.setGlobalVariable("key", "value"); 

3.檢查response的body中是否包含字符串:

tests["Body matches string"] = responseBody.has("string_you_want_to_search");

4.把XML的body轉(zhuǎn)換成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.內(nèi)容類型存在(檢查不區(qū)分大小寫)

tests["Content-Type is present"] = postman.getResponseHeader("Content-Type"); //Note: the getResponseHeader() method returns the header value, if it exists.

8.內(nèi)容類型存在(區(qū)分大小寫):

tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");

9.response的響應(yīng)時間小于200ms:

tests["Response time is less than 200ms"] = responseTime < 200;

10.狀態(tài)碼為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狀態(tài)碼:

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);

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——導(dǎo)入導(dǎo)出和發(fā)送請求查看響應(yīng)
Postman使用手冊2——管理收藏
Postman使用手冊3——環(huán)境變量
Postman使用手冊4——API test

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市裆泳,隨后出現(xiàn)的幾起案子叹洲,更是在濱河造成了極大的恐慌,老刑警劉巖工禾,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件运提,死亡現(xiàn)場離奇詭異蝗柔,居然都是意外死亡,警方通過查閱死者的電腦和手機民泵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門癣丧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人栈妆,你說我怎么就攤上這事胁编。” “怎么了鳞尔?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵嬉橙,是天一觀的道長。 經(jīng)常有香客問我寥假,道長市框,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任昧旨,我火速辦了婚禮蒋得,結(jié)果婚禮上乒疏,老公的妹妹穿的比我還像新娘额衙。我一直安慰自己,他們只是感情好怕吴,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布窍侧。 她就那樣靜靜地躺著,像睡著了一般转绷。 火紅的嫁衣襯著肌膚如雪伟件。 梳的紋絲不亂的頭發(fā)上斧账,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音煞肾,去河邊找鬼咧织。 笑死,一個胖子當(dāng)著我的面吹牛籍救,可吹牛的內(nèi)容都是我干的闪萄。 我是一名探鬼主播梧却,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼桃煎!你這毒婦竟也來了篮幢?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤为迈,失蹤者是張志新(化名)和其女友劉穎三椿,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體葫辐,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡搜锰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了耿战。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蛋叼。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖剂陡,靈堂內(nèi)的尸體忽然破棺而出狈涮,到底是詐尸還是另有隱情,我是刑警寧澤鸭栖,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布歌馍,位于F島的核電站,受9級特大地震影響晕鹊,放射性物質(zhì)發(fā)生泄漏松却。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一溅话、第九天 我趴在偏房一處隱蔽的房頂上張望晓锻。 院中可真熱鬧,春花似錦飞几、人聲如沸砚哆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽躁锁。三九已至,卻和暖如春绪钥,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背关炼。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工程腹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人儒拂。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓寸潦,卻偏偏與公主長得像色鸳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子见转,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,470評論 5 6
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,475評論 0 23
  • 這是預(yù)覽模式標(biāo)題 一級標(biāo)題 二級標(biāo)題 三級標(biāo)題 四級標(biāo)題 五級標(biāo)題 六級標(biāo)題 列表 無序列表 文本1 文本2 文本...
    JUN0508閱讀 242評論 0 0
  • 喜歡他的第587天. 時間過得很快命雀,轉(zhuǎn)眼就要各奔東西。他曾經(jīng)說過我們不會分開斩箫,可命運又能被誰左右吏砂。他說過,只要走進...
    拯救地球的洛閱讀 360評論 0 1
  • 大家晚上好乘客。不二法門的朋友這兩天剛突破一千的數(shù)目狐血。只是單純地想謝謝大家的支持。 我知道這個數(shù)目對于一個公眾號來說小...
    郭綠獅閱讀 257評論 0 1