重点:
1、jmeter中的jsr223 preprocessor中内嵌的javascript版本是ECMA 5.1,postman中可以执行的脚本(ECMA 6),过来需要进行降级实现(ECMA 5.1)
2、jmeter压测中的number of threads(users)代表并发数,ramp-up period(seconds)代表多少秒内发起users,duration(seconds)代表持续多长时间
可被执行的javascript代码:
javascript
//加载外部资源
load("https://www.xxx.com/crypto-js-3.1.2/core.js");
load("https://www.xxx.com/crypto-js-3.1.2/hmac.js");
load("https://www.xxx.com/crypto-js-3.1.2/enc-base64.js");
load("https://www.xxx.com/crypto-js-3.1.2/sha256.js");
//加密函数
function encryptSHA256(content, secret) {
var hmac = CryptoJS.HmacSHA256(content, secret);
return CryptoJS.enc.Base64.stringify(hmac)
}
//随机数函数
function getNonce(len) {
// 密码字典
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// 大写字母密码字典
var bigStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// 小写字母的密码字典
var upperStr = 'abcdefghijklmnopqrstuvwxyz';
// 数字的密码字典
var numStr = '0123456789';
var builder = '';
var count = 0;
var isContainBigChar = false;
var isContainUpperChar = false;
var isContainNumChar = false;
while (count < len - 3) {
//生成 0 ~ 密码字典-1之间的随机数
var i = Math.floor(Math.random() * str.length);
builder += str[i];
count++;
if (!isContainBigChar && bigStr.indexOf(str[i])!=-1) {
isContainBigChar = true;
}
if (!isContainUpperChar && upperStr.indexOf(str[i])!=-1) {
isContainUpperChar = true;
}
if (!isContainNumChar && numStr.indexOf(str[i])!=-1) {
isContainNumChar = true;
}
}
// 如果不存在的,则加,确保一定会存在数字,大写字母,小写字母
if (!isContainBigChar) {
builder += bigStr[Math.floor(Math.random() * bigStr.length)];
}
if (!isContainUpperChar) {
builder += upperStr[Math.floor(Math.random() * upperStr.length)];
}
if (!isContainNumChar) {
builder += numStr[Math.floor(Math.random() * numStr.length)];
}
while (builder.length < len) {
builder += str[Math.floor(Math.random() * str.length)];
}
return builder;
}
//定义http头所需变量
var appKey = '350dd9d1e3fd425681df8cb1eccd4663';
var secretKey = '9fae5a9334a52718a6d9784b32857fb0e06251754f213ea04ce5cfaa8562caaa';
var timestamp = Date.now();
var nonce = getNonce(8);
//获取request内容
var sampler = ctx.getCurrentSampler ();
var args = sampler.getProperty ("HTTPsampler.Arguments");
var httpArg = args.getObjectValue ().getArguments ().get (0);
var jsonObject = httpArg.getObjectValue ().getProperty ("Argument.value").getStringValue ();
jsonObject.appKey=appKey;
jsonObject.timestamp=String(timestamp);
jsonObject.nonce=nonce;
jsonObject.xidList=JSON.stringify(jsonObject.xidList);
//5.1语法
var plainText = '';
for (x in jsonObject) {
plainText += ''+x+'='+[x]+'&';
}
plainText = plainText.slice(0, -1);
//生成加密内容
var sign = encryptSHA256(plainText, secretKey);
//置入变量,在后续请求中使用该变量
vars.put("appKey",appKey)
vars.put("timestamp",timestamp)
vars.put("sign",sign)
vars.put("nonce",nonce)
感谢: teacher c,teacher w.