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

 

posted on 2021-12-27 17:10  执剑之心  阅读(2214)  评论(0编辑  收藏  举报