postman腳本語法大全,不包括插件語法


 

官方語法例子:https://learning.postman.com/docs/writing-scripts/script-references/test-examples/

官方語法庫:https://www.chaijs.com/api/bdd/

官方動態變量庫:Dynamic variables | Postman Learning Center

 

一、基礎語法使用

變量生效順序,本地變量》迭代變量》環境變量》集合變量》全局變量,具有最接近作用域的變量將覆蓋任何其他變量

1、pm.variables:操作變量

 //括號里”變量名“必須是字符串,下面的變量名都是如此
pm.variables.has("變量名")   //是否存在該變量,返回是boolean類型
pm.variables.get(”變量名“)   //獲取該變量的值
pm.variables.set(”變量名“, 任意類型的變量值)  //設置變量
pm.variables.replaceIn(”變量名“)  //返回腳本中動態變量的值
pm.variables.toObject()  //返回一個對象,其中包含當前作用域中所有變量及其值。根據優先級順序,這將包含來自多個作用域的變量。

 

2、pm.envrionment:操作環境變量

pm.environment.nam //獲取當前活動的環境名字
pm.environment.has("變量名")   //是否存在該環境變量,返回是boolean類型
pm.environment.get(”變量名“)   //獲取該環境變量的值
pm.environment.set(”變量名“, 任意類型的變量值)  //設置環境變量
pm.environment.unset(”變量名“)  //刪除該環境變量
pm.environment.clear()   //清除所有環境變量
pm.environment.replaceIn(”變量名“)  //返回腳本中動態變量的值
pm.environment.toObject()  //返回一個對象,其中包含當前作用域中所有變量及其值。根據優先級順序,這將包含來自多個作用域的變量。

 

3、pm.collectionVariables:操作集合變量

pm.collectionVariables.has("變量名")   //是否存在該集合變量,返回是boolean類型
pm.collectionVariables.get(”變量名“)   //獲取該集合變量的值
pm.collectionVariables.set(”變量名“, 任意類型的變量值)  //設置集合變量
pm.collectionVariables.unset(”變量名“)  //刪除該集合變量
pm.collectionVariables.clear()   //清除所有集合變量
pm.collectionVariables.replaceIn(”變量名“)  //返回腳本中動態變量的值
pm.collectionVariables.toObject()  //返回一個對象,其中包含當前作用域中所有變量及其值。根據優先級順序,這將包含來自多個作用域的變量。

 

4、pm.globals:操作全局變量

pm.globals.has("變量名")   //是否存在該全局變量,返回是boolean類型
pm.globals.get(”變量名“)   //獲取該全局變量的值
pm.globals.set(”變量名“, 任意類型的變量值)  //設置全局變量
pm.globals.unset(”變量名“)  //刪除該全局變量
pm.globals.clear()   //清除所有全局變量
pm.globals.replaceIn(”變量名“)  //返回腳本中動態變量的值
pm.globals.toObject()  //返回一個對象,其中包含當前作用域中所有變量及其值。根據優先級順序,這將包含來自多個作用域的變量。

 

5、pm.iterationData:操作迭代變量

pm.iterationData .has("變量名")   //是否存在該迭代變量,返回是boolean類型
pm.iterationData .get(”變量名“)   //獲取該迭代變量的值
pm.iterationData.unset(”變量名“)  //刪除迭代變量
pm.iterationData .toJSON(”變量名“)  //將 iterationData 對象轉換為 JSON 格式
pm.iterationData .toObject()  //返回一個對象,其中包含當前作用域中所有變量及其值。根據優先級順序,這將包含來自多個作用域的變量。

 

6、pm.request:操作請求數據

pm.request.url
pm.request.headers
pm.request.method
pm.request.body
pm.request.headers.add(header:Header)
pm.request.headers.remove(headerName:String)
pm.request.headers.upsert({key: headerName:String, value: headerValue:String}) //更新現有headernanme的字段值

 

7、pm.respnose:操作響應數據

pm.response.code
pm.response.status
pm.response.headers
pm.response.responseTime
pm.response.responseSize
pm.response.text():Function → String
pm.response.json():Function → Object

 

8、pm.info:操作當前事件信息輸出

pm.info.eventName  //放在Test里就顯示”test“,在Pre-request就顯示”pre-request“
pm.info.iteration  //當前迭代的變量值
pm.info.iterationCount //該請求或者集合計划迭代的次數
pm.info.requestName  //正在運行的請求名稱
pm.info.requestId  //正在運行的請求的唯一 GUID

 

9、pm.cookies:操作cookie

pm.cookies.has(cookieName:String):Function → Boolean
pm.cookies.get(cookieName:String):Function → String
pm.cookies.toObject():Function → Object

使用指定用於訪問請求 Cookie 的域。pm.cookies.jar
pm.cookies.jar():Function → Object
//使用名稱和值設置 Cookie:
jar.set(URL:String, cookie name:String, cookie value:String, callback(error, cookie)):Function → Object

//使用PostmanCookie或兼容對象設置 Cookie
jar.set(URL:String, { name:String, value:String, httpOnly:Bool }, callback(error, cookie)):Function → Object
例如:
const jar = pm.cookies.jar();
jar.set("httpbin.org", "session-id", "abc123", (error, cookie) => {
  if (error) {
    console.error(`An error occurred: ${error}`);
  } else {
    console.log(`Cookie saved: ${cookie}`);
  }
});

//獲取cookie
jar.get(URL:String, cookieName:String, callback (error, value)):Function → Object

//獲取所有cookie
jar.getAll(URL:String, callback (error, cookies)):Function

//刪除cookie
jar.unset(URL:String, token:String, callback(error)):Function → Object

//清除cookie
jar.clear(URL:String, callback (error)):Function → Object

 

10、pm.sendRequest:可以使用該方法從預請求或測試腳本異步發送請求

// Example with a plain string URL
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
  if (error) {
    console.log(error);
  } else {
  console.log(response);
  }
});

// Example with a full-fledged request
const postRequest = {
  url: 'https://postman-echo.com/post',
  method: 'POST',
  header: {
    'Content-Type': 'application/json',
    'X-Foo': 'bar'
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({ key: 'this is json' })
  }
};
pm.sendRequest(postRequest, (error, response) => {
  console.log(error ? error : response.json());
});

// Example containing a test
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
  if (error) {
    console.log(error);
  }

  pm.test('response should be okay to process', () => {
    pm.expect(error).to.equal(null);
    pm.expect(response).to.have.property('code', 200);
    pm.expect(response).to.have.property('status', 'OK');
  });
});

 

 11、postman.setNextRequest:設置集合工作流,在當前請求之后運行指定的請求(集合中定義的請求名稱,例如"獲取客戶")

//通過請求名字或者請求ID進行下一步的請求
postman.setNextRequest(requestName:String):Function
postman.setNextRequest(requestId:String):Function
//停止工作流
postman.setNextRequest(null);

 

 12、腳本可視化

pm.visualizer.set(layout:String, data:Object, options:Object):Function  //layout必選,其他兩個參數自選
//例子
var template = `<p>{{res.info}}</p>`;
pm.visualizer.set(template, {
    res: pm.response.json()
});

pm.getData(callback):Function  //用於檢索可視化模板字符串中的響應數據
//例子
pm.getData(function (error, data) {
  var value = data.res.info;
});
//回調函數接受error和data兩個參數,error傳遞任何錯誤信息,data傳遞數據到pm.visualizer.set

 

13、pm.test:斷言

測試檢查響應是否有效
pm.test("response should be okay to process", function () {
  pm.response.to.not.be.error;
  pm.response.to.have.jsonBody('');
  pm.response.to.not.have.jsonBody('error');
});

可選的回調可以傳遞給 ,以測試異步函數
pm.test('async test', function (done) {
  setTimeout(() => {
    pm.expect(pm.response.code).to.equal(200);
    done();
  }, 1500);
});

pm.test.index():Function → Number  //在代碼中獲取從特定位置執行的測試總數

 

 

 二、斷言和語法例子

 

輸出變量值或者變量類型,打印日志

console.log(pm.collectionVariables.get("name"));
console.log(pm.response.json().name);
console.log(typeof pm.response.json().id);

if (pm.response.json().id) { console.log("id was found!"); // do something } else { console.log("no id ..."); //do something else }
//for循環讀取
for(條件){
語句;
}

狀態碼檢測:

//pm.test.to.have方式
pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});
//expect方式
pm.test("Status code is 200", () => {
  pm.expect(pm.response.code).to.eql(200);
});

 

多個斷言作為單個測試的結果:

pm.test("The response has all properties", () => {
    //parse the response JSON and test three properties
    const responseJson = pm.response.json();
    pm.expect(responseJson.type).to.eql('vip');
    pm.expect(responseJson.name).to.be.a('string');
    pm.expect(responseJson.id).to.have.lengthOf(1);
});

 

不同類型的返回結果解析

//獲取返回的json數據
const responseJson = pm.response.json();
//將number轉換為JSON格式
JSON.stringify(pm.response.code)
//將json數據轉換為數組
JSON.parse(jsondata) //獲取xml數據 const responseJson
= xml2Json(pm.response.text()); //獲取csv數據 const parse = require('csv-parse/lib/sync'); const responseJson = parse(pm.response.text()); //獲取html數據 const $ = cheerio.load(pm.response.text()); //output the html for testing console.log($.html());

直接處理未解析的返回數據,使用include

pm.test("Body contains string",() => {
  pm.expect(pm.response.text()).to.include("customer_id");
});

pm.test("Body is string", function () {
  pm.response.to.have.body("whole-body-text");
});

測試響應正文reponseBody中的特定值

pm.test("Person is Jane", () => {
  const responseJson = pm.response.json();
  pm.expect(responseJson.name).to.eql("Jane");
  pm.expect(responseJson.age).to.eql(23);
});
//獲取響應正文
responseBody
pm.response.text()

測試某個值是否為集合中的一種,使用oneof

pm.test("Successful POST request", () => {
  pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

測試響應header

//測試響應頭是否存在
pm.test("Content-Type header is present", () => {
  pm.response.to.have.header("Content-Type");
});
//測試響應頭的特定值
pm.test("Content-Type header is application/json", () => {
  pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});

//獲取響應頭”Server“數據
  postman.getResponseHeader("Server")

測試cookie

//測試是否存在相應的cookie
pm.test("Cookie JSESSIONID is present", () => {
  pm.expect(pm.cookies.has('JSESSIONID')).to.be.true;
});
//測試該cookie是否等於特定值
pm.test("Cookie isLoggedIn has value 1", () => {
  pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');
});

測試響應時間是否在范圍內,使用below

pm.test("Response time is less than 200ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(200);
});

測試reponsebody中某個值和某個變量的值一致

pm.test("Response property matches environment variable", function () {
pm.expect(pm.response.json().name).to.eql(pm.environment.get("name"));
});

測試響應數據的類型

/* response has this structure:
{
  "name": "Jane",
  "age": 29,
  "hobbies": [
    "skating",
    "painting"
  ],
  "email": null
}
*/
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
  pm.expect(jsonData).to.be.an("object");
  pm.expect(jsonData.name).to.be.a("string");
  pm.expect(jsonData.age).to.be.a("number");
  pm.expect(jsonData.hobbies).to.be.an("array");
  pm.expect(jsonData.website).to.be.undefined;
  pm.expect(jsonData.email).to.be.null;
});

測試數據為空,或者包含特定項

/*
response has this structure:
{
  "errors": [],
  "areas": [ "goods", "services" ],
  "settings": [
    {
      "type": "notification",
      "detail": [ "email", "sms" ]
    },
    {
      "type": "visual",
      "detail": [ "light", "large" ]
    }
  ]
}
*/

const jsonData = pm.response.json();
pm.test("Test array properties", () => {
    //errors array is empty
  pm.expect(jsonData.errors).to.be.empty;
    //areas includes "goods"
  pm.expect(jsonData.areas).to.include("goods");
    //get the notification settings object
  const notificationSettings = jsonData.settings.find(m => m.type === "notification");
  pm.expect(notificationSettings).to.be.an("object", "Could not find the setting");
    //detail array should include "sms"
  pm.expect(notificationSettings.detail).to.include("sms");
    //detail array should include all listed
  pm.expect(notificationSettings.detail).to.have.members(["email", "sms"]);
});

斷言對象包含鍵、屬性

pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
pm.expect({a: 1}).to.have.property('a');
pm.expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b');

斷言值為父對象的一部分,使用deep,數據里嵌套的數據不會被檢查到

/*
response has the following structure:
{
  "id": "d8893057-3e91-4cdd-a36f-a0af460b6373",
  "created": true,
  "errors": []
}
*/

pm.test("Object is contained", () => {
  const expectedObject = {
    "created": true,
    "errors": []
  };
  pm.expect(pm.response.json()).to.deep.include(expectedObject);
});

斷言選定的測試活動環境

pm.test("Check the active environment", () => {
  pm.expect(pm.environment.name).to.eql("Production");
});

斷言響應結構

const schema = {
 "items": {
 "type": "boolean"
 }
};
const data1 = [true, false];
const 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;
});

 

 

常見斷言錯誤分析

//問題:AssertionError: expected <value> to deeply equal '<value>'
//原因:相比較的雙方類型不一致導致,如字符串和數字對比
pm.expect(1).to.eql("1");    //例子

//問題:ReferenceError: jsonData is not defined
//原因:引用尚未聲明或超出測試代碼范圍的 JSON 對象時,通常會發生這種情況
pm.test("Test 1", () => { const jsonData = pm.response.json(); pm.expect(jsonData.name).to.eql("John"); }); //正確操作例子 pm.test("Test 2", () => { pm.expect(jsonData.age).to.eql(29); // jsonData is not defined }); //錯誤操作例子

//問題:AssertionError: expected undefined to deeply equal..
//原因:斷言的屬性未定義錯誤
pm.expect(jsonData.name).to.eql("John"); //該jsonData.name未被定義,出現AssertionError: expected undefined to deeply equal 'John'namejsonData


 

 發送異步請求

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

 


免責聲明!

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



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