前置脚本常用
1、时间戳生成(秒级):
pm.globals.set('timestamp', pm.variables.replaceIn("{{$timestamp}}"))
2、 生成随机字符串
let username = generateRandomStr("yanchi_", "@test.com", 8)
pm.globals.set("username", username)
console.log(username)
function generateRandomStr(prefix = '', suffix = '', length = 6) {let characters = 'abcdefghijklmnopqrstuvwxyz0123456789';let randomStr = '';for (let i = 0; i < length; i++) {let randomIndex = Math.floor(Math.random() * characters.length);randomStr += characters[randomIndex];}return `${prefix}${randomStr}${suffix}`;
}console.log(generateRandomStr("yanchi_", "@test.com", 8))
后置脚本常用
1、用例断言
let caseName = pm.info.requestName
let reg1 = /\(.*\)/
let parenthesisContent = caseName.match(reg1)[0]
let reg2 = /\d+/g
let caseStatus = parenthesisContent.match(reg2)
if (caseStatus){caseStatus = caseStatus[caseStatus.length - 1]let jsonData = pm.response.json()pm.test("返回值:\n" + JSON.stringify(jsonData), function () {pm.expect(jsonData.status == caseStatus).to.be.true;})console.log('当前用例参与断言,状态码为:' + caseStatus)
}else {console.log('当前用例不参与断言')
}
2、返回值日志输出到断言中
let jsonData = pm.response.json()
pm.test("返回值:\n" + JSON.stringify(jsonData), function () {pm.response.to.have.status(200)pm.expect(jsonData.code == '000').to.be.true;
})