postman的函數精講


postman的sandbox

  ——pre-request scripts 和 test scripts

 

   Postman的sandbox是一個JavaScript的執行環境,這使得你能夠為request寫pre-request scripts和test scripts 。不論你寫的代碼是pre-request scripts還是test script都會在sandbox中執行。

 

sandbox中常用的庫和工具:

(1)Lodash:
JS utility library

(2)jQuery (Deprecated,已棄用):
Cross-platform JavaScript library. This will be removed in future versions of the sandbox.

(3)BackboneJS (Deprecated,已棄用):
Provides simple models, views, and collections. This will be removed in future versions of the sandbox.

(4)SugarJS:
Extends native JS objects with useful methods

(5)tv4 JSON schema validator:
Validates JSON objects against v4 of the json-schema draft

(6)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 (7)xml2Json(xmlString): This function behaves the same in Newman and Postman (8)xmlToJson(xmlString)(Deprecated,已棄用): This function does NOT behave the same in Newman and Postman (9)postman.getResponseHeader(headerName) (Test-only,只能在 Test 中使用 ): 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.

(10)postman.getResponseCookie(cookieName)(Test-only,只能在 Test 中使用 ):
Gets the response cookid with the giben name. You will need to enable the interceptor for this to work.

 

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.

 

 

舊版語法和新版語法區別(當前postman工具同時兼容這些新舊版語法):

  1、舊版語法用 “ postman.*** ”,新版語法用 “ pm.*** ”;

  2、舊版語法:responseCode.code、responseCode.name、responseTime、responseBody、JSON.parse(responseBody).***

     新版語法:response.code、response.status、response.responseTime、response.text()、response.json().***

 

 

一、postman的環境變量

1、舊版環境變量語法:

 1 postman.setEnvironmentVariable(variableName, variableValue)
 2  
 3 postman.setGlobalVariable(variableName, variableValue)
 4  
 5 postman.clearEnvironmentVariable(variableName)
 6  
 7 postman.clearGlobalVariable(variableName)
 8  
 9 postman.clearEnvironmentVariables()
10  
11 postman.clearGlobalVariables()
12  
13 
14 environment: A dictionary of variables in the current environment. Use environment["foo"] to access the value of the "foo" environment variable.
15  
16 globals: A dictionary of global variables. Useglobals["bar"] to access the value of the "bar" global variable.

 

2、新版環境變量語法:

pm.environment.get("variable_key");  //Get an environment variable 
pm.globals.get("variable_key");  //Get a global variable 
pm.variables.get("variable_key");  //Get a variable
pm.collectionVariables.get("variable_key");  //Get a collection variable

pm.environment.set("variable_key", "variable_value");//Set a environment variable
pm.globals.set("variable_key", "variable_value");  //Set a global varlable 
pm.collectionVariables.set("variable_key", "variable_value"); //Set a coilection variable 

pm.environment.unset("variable_key");  //Clear an environment variable 
pm.globals.unset("variable_key");  //Clear a global variable 
pm.collectionVariables.unset("variable_key");  //Clear a collection variable 

 

3、postman的動態變量——環境變量的使用

  注意:動態變量不可以用於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

 

二、postman常用函數

//Send a request 
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});
//Response body:Convert XML body to a JSoN Obiect 
var jsonObject = xml2Json(responseBody);


//Use Tiny Validator for JSON data
var schema = {
    "items": {
        "type": "boolean"
    }
};

var data1 = [true, false];
var data2 = [true, 123];

pm.test('Schema is valid', function () {
    pm.expect(tv4.validate(data1, schema)).to.be.true;
    pm.expect(tv4.validate(data2, schema)).to.be.true;
});

 

三、postman的斷言

  JavaScript中的斷言,常用的“相等(==)”和“等同(===)”的區別:

    1.相等(==)和不相等(!=)是比較運算符,但當類型不同時會進行類型轉換,例如false==0這個條件為真;
    2.等同(===)和不等同(!==)是判斷一不一樣,但是不會進行類型轉換,類型不同就判斷它們不同,所以false===0這個條件為假;
    3.一般為了安全起見,都是使用===進行比較的;

 

1、使用 tests 方式斷言

 1 ''
 2 //tests斷言功能,相當於python中print()函數的輸出功能,可以在斷言結果中顯示
 3 //tests斷言語法:tests["斷言后的輸出文案或者用例名稱"] = 判斷結果的布爾值
 4 //         說明:多個斷言語句中,tests后面的中括號里面的文案不能重復,否則只會顯示一個
 5 //              如果等號后邊的值為“true”,那么就斷言成功,否則斷言失敗
 6 ''
 7 tests["這是測試斷言文案01"] = true;
 8 tests["這是測試斷言文案02"] = false;
 9 tests["這是測試斷言文案03"] = 1+1 === 2;
10 tests["這是測試斷言文案04"] = 1+1 > 2;
11 tests["這是測試斷言文案05"] = 2>1 && 2>2;
12 tests["這是測試斷言文案06"] = 2>1 || 2>2;
13 tests["這是測試斷言文案07"] = !(2>1 || 2>2);
14 tests["這是測試斷言文案08"] = "123456abcdef".has("56a");
15 
16 
17 tests["1、斷言響應結果中包含success"] = responseBody.has("success");
18 tests["2、斷言響應結果中包含success"] = JSON.parse(responseBody).msg === "success";
19 tests["3、斷言響應結果中包含success"] = pm.response.text().has("success");
20 tests["4、斷言響應結果中包含success"] = pm.response.json().msg.has("success");

 

 2、使用 chai.js庫 斷言 

  chai.js是一套TDD(測試驅動開發)/BDD(行為驅動開發)的斷言庫,包含有3個斷言庫,支持BDD風格的expect/should和TDD風格的assert。可以高效的和任何js測試框架(支持在postman中應用)搭配使用。

 1 // 斷言語法:pm.test("用例文案",function(){ 斷言語句 })
 2 pm.test('case01',function(){
 3     pm.response.to.have.status(200);
 4     pm.response.to.have.status("OK");
 5 })
 6 
 7 pm.test('case02',function(){
pm.expect(1+1==2).to.be.true;
8 pm.expect(responseCode.code) === 200; 9 pm.expect(pm.response.code).to.equal(200); //等價於上面一句的用法 10 11 pm.expect(responseCode.name).to.equal("OK"); 12 pm.expect(pm.response.status).to.equal("OK"); 13 pm.expect(pm.response.status).to.contain("OK"); 14 pm.expect(pm.response.status).to.contains("OK"); 15 16 pm.expect(responseTime).to.greaterThan(10); 17 pm.expect(pm.response.responseTime).to.greaterThan(10); 18 19 //responseBody是一個字符串文本 20 pm.expect(responseBody).to.contains("success"); 21 //如果要取出responseBody里面的值,可以先將其轉換成json對象再進行取值 22 pm.expect(JSON.parse(responseBody).msg).to.equal("success"); 23 //pm.response.text() 是字符串文本 24 pm.expect(pm.response.text()).to.contains("success"); 25 pm.expect(pm.response.text()).to.have.string("success"); 26 //pm.response.json() 是一個json對象,里面的值如果是字典格式要用點(.),如果是數組格式要用中括號([])來取值 27 pm.expect(pm.response.json().msg).to.contains("success"); 28 29 //語法中的postman不能換成pm 30 pm.expect(postman.getResponseHeader("Connection")).to.equal("keep-alive"); 31 //注意不要省掉了【postman.getResponseCookie('cookies的name值').value】后面的value 32 // pm.expect(postman.getResponseCookie('cookies的name值').value).to.contain("要包含的字符"); 33 })

 

 3、postman中斷言——正則表達式

1 tests["判斷是否包含某些字符"] = "123456abcdef".match(new RegExp('12(.+?)de')); 
2 
3 tests[responseBody] = true;
4 var m = responseBody.match(new RegExp('\"msg\"\:\"(.+?)\"\,\"data\"'))[1];
5 tests["提取響應體中的msg值:"+ m] = true;

 

 


免責聲明!

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



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