项目每次接口测试请求postman需要添加header信息等,非常的繁琐,使用Tests和Prescript联合可以解决。
登录接口Tests添加脚本
// 打印用于调试
// 把返回的字符串转换成json对象
var jsobj = JSON.parse(responseBody);
const sessionId = jsobj.data.authUser.sessionId;
console.log('登录成功--------------- sessionId:' +sessionId);
// 设置sessionid到环境变量
pm.environment.set("sessionId", sessionId);
测试接口目录下添加脚本
const sessionId = pm.environment.get("sessionId");
pm.request.headers.add({
key: 'sessionId',
value: sessionId
});
let requestUrl = pm.request.url;
console.log('开始请求api,url: ' + requestUrl)
if(!requestUrl.getPath().startsWith('/services/')){
return;
}
const apiHost = pm.environment.get("api-host");
requestUrl = apiHost + requestUrl.getPath();
const apiToken = pm.environment.get("api-token");
const apiSecret = pm.environment.get("api-secret");
const requestMethod = pm.request.method;
console.log('----------------- 开始获取 API header------------------------');
var nowDate = new Date();
var date = new Date(nowDate.valueOf() - 8 * 60 * 60 * 1000);
var EEE = getEnglishWeek(date.getDay());
var dd = formatNumber(date.getDate());
var MMM = getEnglishMonth(date.getMonth());
var yyyy = date.getFullYear();
var mm = formatNumber(date.getMinutes());
var ss = formatNumber(date.getSeconds());
var zzz = "GMT";
var HH = formatNumber(date.getHours());
var authorizationDate = EEE + ", " + dd + " " + MMM + " " + yyyy + " " + HH + ":" + mm + ":" + ss + " " + zzz;
var orderNo = yyyy + "" + (date.getMonth() + 1) + dd + HH + mm + ss;
var line = '\n';
var signedString = requestMethod + line + authorizationDate + line + requestUrl;
var signSha1 = CryptoJS.HmacSHA1(signedString, apiSecret);
var sign = CryptoJS.enc.Base64.stringify(signSha1);
var authorization = "WallTech " + apiToken + ":" + sign;
console.log('----------------- 获取 API header 成功------------------------');
console.log('Authorization :' + authorization);
console.log('X-WallTech-Date :' + authorizationDate);
pm.request.headers.add({
key: 'Authorization',
value: authorization
});
pm.request.headers.add({
key: 'X-WallTech-Date',
value: authorizationDate
});
function getEnglishWeek(number){
var week;
if(number==0) week="Sun"
if(number==1) week="Mon"
if(number==2) week="Tue"
if(number==3) week="Wed"
if(number==4) week="Thu"
if(number==5) week="Fri"
if(number==6) week="Sat"
return week;
};
function getEnglishMonth(number){
var month;
if(number==0) month="Jan"
if(number==1) month="Feb"
if(number==2) month="Mar"
if(number==3) month="Apr"
if(number==4) month="May"
if(number==5) month="Jun"
if(number==6) month="Jul"
if(number==7) month="Aug"
if(number==8) month="Sep"
if(number==9) month="Oct"
if(number==10) month="Nov"
if(number==11) month="Dec"
return month;
}
function formatNumber(number){
if(number < 10){
return "0" + number + "";
}
return number + "";
}
这里有个问题,pm.request.url 获取到的路径里面不能带变量参数,获取到的不是最终替换变量的路径,而是之前的,如果用到了需要用正则替换。