欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

postman的前置处理器prp-request scipt和断言test的使用

程序员文章站 2022-07-12 11:34:35
...

postman的前置处理器prp-request scipt和断言test的使用

prp-request scipt和断言tests常用语法
主要语言为JavaScript,调试脚本建议多使用console.log(),进入控制台查看
① 获取时间戳

var timestamp=new Date().getTime();

② 生成36位随机uuid

function UUID(){
   var len=36;
   var radix=16;  //16进制
   var chars='123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'.split('');
   var uuid=[];radix=radix||chars.length;
   if(len){uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[4]='4';
   for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r];}}}
   return uuid.join('');
}

③ 获取xxxx-xx-xx xx:xx:xx格式时间

function getStamp(addDayCount){
	var date=new Date();
	date.setDate(date.getDate()+addDayCount);  //获取n天后的日期
	var year=date.getFullYear();
	var month=date.getMonth()+1;
	var day=date.getDate();
	var week=date.getDay();
	var hour=date.getHours();
	var minute=date.getMinutes();
	var sencond=date.getSenconds();
	return year+'-'+(month<10?"0"+month:month)+'-'+(day<10?"0"+day:day)+' '+(hour<10?"0"+hour:hour)+':'+(minute<10?"0"+minute:minute)+':'+(sencond<10?"0"+sencond:sencond);
}

④ 设置变量

pm.globals.set("variable_key", "variable_value");     //全局变量
pm.environment.set("variable_key", "variable_value"); //环境变量
pm.variables.set("variable_key", "variable_value");   //局部变量

⑤ 获取变量,在body中引用变量 {{variable_key}}

pm.globals.get("variable_key");     //全局变量
pm.variables.get("variable_key");   //局部变量
pm.environment.get("variable_key"); //环境变量

⑥ 删除变量

pm.globals.unset("variable_key");     //全局变量
pm.variables.unset("variable_key");   //局部变量
pm.environment.unset("variable_key"); //环境变量

断言test特有断言语法(在请求响应结束后执行)
① 断言函数

pm.test("Your test name", function () {
    var jsonData = pm.response.json();    //获取解析json响应数据
    var jsonObject = xml2Json(responseBody);  //获取xml格式数据转json格式数据
    var parse = require('csv-parse/lib/sync');
	var responseJson = parse(pm.response.text());  //解析csv数据
	var $ = cheerio.load(pm.response.text());  //解析html数据
	console.log($.html());
	
    pm.expect(jsonData.statusText).to.eql('SUCCESS');  //断言响应statusText为SUCCESS
    pm.expect(pm.response.text()).to.include("SUCCESS");   //断言SUCCESS是否在响应中存在
    pm.response.to.have.body("response_body_string");  //断言响应内容完全等于"response_body_string"
    pm.response.to.have.header("Content-Type");    //断言请求头中存在"Content-Type"
    pm.response.to.have.status(200);   //断言响应码为200
    pm.expect(pm.response.responseTime).to.be.below(200);  //断言请求响应时间少于200ms
    pm.expect(pm.response.code).to.be.oneOf([201,202]);  //断言请求响应状态码为[201,202]中的一个
});

注意:在postman左侧集合点击edit中的prp-request scipt和tests中编写脚本,代表该集合下每一个请求都要执行一遍前置和断言。

相关标签: postman javascript