Postman中的測試指令碼(Test scripts)
阿新 • • 發佈:2020-12-01
一、postman測試指令碼
測試指令碼是在傳送請求之後執行的,並且已經從伺服器接收到響應。
二、測試舉例
1、設定環境變數
pm.environment.set("variable_key", "variable_value");
2、將巢狀物件設定為環境變數
1 var array = [1, 2, 3, 4]; 2 pm.environment.set("array", JSON.stringify(array, null, 2)); 3 4 var obj = { a: [1, 2, 3, 4], b: { c: 'val' } }; 5 pm.environment.set("obj", JSON.stringify(obj));
3、獲取環境變數
pm.environment.get("variable_key");
4、獲取環境變數(其值是嚴格化物件)
var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));
5、清除環境變數
pm.environment.unset("variable_key");
6、設定全域性變數
pm.globals.set("variable_key", "variable_value");
7、獲取全域性變數
pm.globals.get("variable_key");
8、清除全域性變數
pm.globals.unset("variable_key");
9、獲取變數
pm.variables.get("variable_key");
10、檢查響應體是否包含字串
pm.test("Body matches string", function () { pm.expect(pm.response.text()).to.include("string_you_want_to_search"); });
11、檢查響應體是否等於字串
pm.test("Body is correct", function () { pm.response.to.have.body("response_body_string"); });
12、檢查JSON值
pm.test("Your test name", function () { var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); });
13、內容型別存在
pm.test("Content-Type is present", function () { pm.response.to.have.header("Content-Type"); });
14、響應時間小於200毫秒
pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); });
15、狀態程式碼為200
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
16、程式碼名包含字串
pm.test("Status code name has string", function () { pm.response.to.have.status("Created"); });
17、成功後請求狀態程式碼
pm.test("Successful POST request", function () { pm.expect(pm.response.code).to.be.oneOf([201,202]); });
18、為JSON資料使用TinyValidator
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; });
19、解碼BASE64編碼資料
var intermediate, base64Content, // assume this has a base64 encoded value rawContent = base64Content.slice('data:application/octet-stream;base64,'.length); intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here: https://www.npmjs.com/package/crypto-js pm.test('Contents are valid', function() { pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true; // a check for non-emptiness });
20、傳送非同步請求
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
21、將XML體轉換為JSON物件
var jsonObject = xml2Json(responseBody);