1臭墨,BeanShell 后置處理程序處理響應(yīng)內(nèi)容中文亂碼
prev.setDataEncoding("utf-8");
2第步,把字符串里面@{參數(shù)}替換成jmeter的變量
//下面這段是要把字符串里面@{參數(shù)}替換成jmeter的變量
import java.util.regex.Matcher;
import java.util.regex.Pattern;
def replaceVariables(String body) {
Pattern pattern = Pattern.compile("@\\{(.+?)\\}");
Matcher matcher = pattern.matcher(body);
int matchCount = 0; // 用于計(jì)數(shù)匹配到的變量個(gè)數(shù)
while (matcher.find()) {
String variableName = matcher.group(1);
String variableValue = vars.get(variableName);
body = body.replace("@{" + variableName + "}", variableValue);
matchCount++;
}
log.info("Match count: " + matchCount); // 打印匹配到的變量個(gè)數(shù)
return body;
}
//替換url
def path = replaceVariables(vars.get("path"));
vars.put("path", path);
log.info("path: " + path);
//替換body
def body = replaceVariables(vars.get("body"));
vars.put("body", body);
log.info("body: " + body);
//看看body里面需要傳幾個(gè)字段看幼,只算到第一層
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText(body)
//def jsonObject = jsonSlurper.parseText(vars.get("body"))
def keyCount = jsonObject.size()
vars.put("keyCount", keyCount.toString())
//設(shè)置counterN為0,用來(lái)控制循環(huán)次數(shù)
vars.put("counterN", "0")
3,JSR233取樣器 隨機(jī)生成不同類型參數(shù)并放進(jìn)jmeter
import org.apache.commons.lang3.RandomStringUtils
def generateRandomString(String length) {
if (length == null || length.isEmpty()) {
length = "8" // 默認(rèn)長(zhǎng)度為8
}
String value = ''
// 生成數(shù)字
value = RandomStringUtils.randomNumeric(Integer.parseInt(length))
vars.put("Var_1", value)
// 生成字母
value = RandomStringUtils.randomAlphabetic(Integer.parseInt(length))
vars.put("Var_2", value)
// 生成數(shù)字+字母
value = RandomStringUtils.randomAlphanumeric(Integer.parseInt(length))
vars.put("Var_3", value)
// 生成特殊符號(hào)
def specialChars = "!@#\$%^&*()"
value = String.valueOf(specialChars.charAt(new Random().nextInt(specialChars.length())))
vars.put("Var_4", value)
// 空
value = ''
vars.put("Var_5", value)
// SQL注入
value = "'; DROP TABLE users; --"
vars.put("Var_6", value)
// XML攻擊
value = "<foo><![CDATA[<script>alert('XSS');</script>]]></foo>"
vars.put("Var_7", value)
// null
value = "null"
vars.put("Var_8", value)
}
def length = vars.get("length")
generateRandomString(length)
//循環(huán)一次就加1
int counter = Integer.parseInt(vars.get("counterN")) +1;
vars.put("counterN",Integer.toString(counter));
4,把body變?yōu)檎?qǐng)求參數(shù)
//下面這段是要把body變?yōu)檎?qǐng)求參數(shù)
import groovy.json.JsonBuilder
log.info(vars.get("body"))
// 定義參數(shù)字符串
String paramStr = vars.get("body")
// 解析參數(shù)字符串為變量
def jsonSlurper = new groovy.json.JsonSlurper()
def params = jsonSlurper.parseText(paramStr)
// 構(gòu)建請(qǐng)求體
def requestBody = new JsonBuilder(params).toPrettyString()
// 設(shè)置請(qǐng)求體
sampler.addNonEncodedArgument('', requestBody, '')
// 設(shè)置請(qǐng)求體的Content-Type
sampler.setPostBodyRaw(true)
sampler.setProperty('HTTPSampler.content_type', 'application/json')
5,提取響應(yīng)內(nèi)容
import groovy.json.JsonSlurper
def extractValueFromJson(json, key) {
def slurper = new JsonSlurper()
def data = slurper.parseText(json)
for (entry in data) {
if (entry.key == key) {
return getValue(entry.value)
} else if (entry.value instanceof Map) {
def value = extractValueFromMap(entry.value, key)
if (value != null) {
return value
}
} else if (entry.value instanceof List) {
def value = extractValueFromList(entry.value, key)
if (value != null) {
return value
}
}
}
return null
}
def extractValueFromMap(map, key) {
for (entry in map) {
if (entry.key == key) {
return getValue(entry.value)
} else if (entry.value instanceof Map) {
def value = extractValueFromMap(entry.value, key)
if (value != null) {
return value
}
} else if (entry.value instanceof List) {
def value = extractValueFromList(entry.value, key)
if (value != null) {
return value
}
}
}
return null
}
def extractValueFromList(list, key) {
for (item in list) {
if (item instanceof Map) {
def value = extractValueFromMap(item, key)
if (value != null) {
return value
}
} else if (item instanceof List) {
def value = extractValueFromList(item, key)
if (value != null) {
return value
}
}
}
return null
}
def getValue(value) {
if (value instanceof List) {
return value[0]
} else {
return value
}
}
def res = prev.getResponseDataAsString()
// 獲取out_res變量?jī)?nèi)容
def out_res = new JsonSlurper().parseText(vars.get("out_res"))
// 遍歷 out_res 中的鍵值對(duì),并提取出json中相應(yīng)的值
out_res.each { k, v ->
//提取v節(jié)點(diǎn)值
def extractedValue = extractValueFromJson(res, v)
// 將提取出的值保存到 JMeter 變量中
vars.put(k, extractedValue?.toString() ?: "")
log.info(k +": " + v)
log.info(k +": " + extractedValue)
}
6速那,寫(xiě)excel
import jxl.*
import jxl.write.*
import jxl.write.Number
//// 引入日期時(shí)間類
//import java.text.SimpleDateFormat
//// 獲取當(dāng)前日期時(shí)間
//def dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm")
//def dateTime = dateFormat.format(new Date())
//// Excel 文件路徑及名稱
//def filePath = "./data/results_${dateTime}.xls"
def filePath = "./data/results.xls"
// 檢查文件是否存在,如果不存在則創(chuàng)建新文件
def file = new File(filePath)
if (!file.exists()) {
def workbook = Workbook.createWorkbook(file)
def sheet = workbook.createSheet("Sheet1", 0)
// 創(chuàng)建表頭
sheet.addCell(new Label(0, 0, "請(qǐng)求標(biāo)題"))
sheet.addCell(new Label(1, 0, "請(qǐng)求頭"))
sheet.addCell(new Label(2, 0, "請(qǐng)求內(nèi)容"))
sheet.addCell(new Label(3, 0, "響應(yīng)頭"))
sheet.addCell(new Label(4, 0, "響應(yīng)內(nèi)容"))
workbook.write()
workbook.close()
}
// 打開(kāi)現(xiàn)有文件或新創(chuàng)建的文件
def existingWorkbook = Workbook.getWorkbook(file)
def writableWorkbook = Workbook.createWorkbook(file, existingWorkbook)
def sheet = writableWorkbook.getSheet(0)
String requestTitle = sampler.getName();
String requestHeaders = sampler.getHeaderManager().getHeaders().toString();
String requestBody = new String(sampler.getArguments().getArgument(0).getValue());
String responseHeaders = prev.getResponseHeaders();
String responseBody = prev.getResponseDataAsString();
//log.info("requestTitle: {}", requestTitle)
//log.info("requestHeaders: {}", requestHeaders)
//log.info("requestBody: {}", requestBody)
//log.info("responseHeaders: {}", responseHeaders)
//log.info("responseBody: {}", responseBody)
// 獲取行數(shù)尿背,用于追加數(shù)據(jù)
def rowCount = sheet.getRows()
// 將請(qǐng)求相關(guān)信息寫(xiě)入 Excel 文件
sheet.addCell(new Label(0, rowCount, requestTitle))
sheet.addCell(new Label(1, rowCount, requestHeaders))
sheet.addCell(new Label(2, rowCount, requestBody))
sheet.addCell(new Label(3, rowCount, responseHeaders))
sheet.addCell(new Label(4, rowCount, responseBody))
existingWorkbook.close()
writableWorkbook.write()
writableWorkbook.close()
7,jmeter把cookie提取出來(lái)存為全局參數(shù)
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
CookieManager cookieManager = sampler.getCookieManager();
StringBuilder cookieString = new StringBuilder();
for (int i = 0; i < cookieManager.getCookieCount(); i++) {
Cookie cookie = cookieManager.get(i);
cookieString.append(cookie.getName()).append("=")
.append(cookie.getValue())
.append("; ");
}
//vars.put("cookies", cookieString.toString());
//vars.put("cookies", cookieString.toString());
props.put("cookies", cookieString.toString());