在上篇文章中有提到在获取完成配置后,调用runcase()方法,如下:
//执行monitorcase
function runcase(){
url="runcases";
$.post(
url,
{ //传入参数:lineName 业务线名称;frequency 监控频率; smsValue 是否发送短信。
"lineName" : document.getElementById("dropDownToggleName").text,
"frequency" : document.getElementById("monitorFreq").value,
"smsValue" : document.getElementById("smsValue").checked
},
function(data){
removeElementById("accordion");
removeElementById("summary");
var total = data.total;
var itemContent = "<h5 class=summary id=summary> 共找到" + total + "条数据</h5>"
var json_array = data.data;
itemContent += "<div class=panel-group id=accordion>"
for (var i = 0; i < json_array.length; i++) {
if (json_array[i].success == "false") {
itemContent += "<div class='panel panel-danger'>"
} else {
itemContent += "<div class='panel panel-success'>"
}
itemContent += "<div class=panel-heading>"
itemContent += "<h4 class=panel-title style=float:left>"
itemContent += "<a data-toggle=collapse data-parent=#accordion href=#collapse" + json_array[i].id + ">"
itemContent += "用例名称: " + json_array[i].fileName
itemContent += "</a></h4>"
itemContent += "<a style=float:right; href=javascript:copy('" + json_array[i].id + "');>前往接口测试平台</a>"
itemContent += "<div style=clear:both></div>"
itemContent += "</div>"
itemContent += "<div id=collapse" + json_array[i].id + " class='panel-collapse collapse'>"
itemContent += "<div class=panel-body>"
if (json_array[i].success == "false") {
itemContent += " Event: "+ JSON.stringify(json_array[i].failureMessage)
} else {
itemContent += " Event: 测试通过"
}
itemContent += "</div></div></div>"
}
itemContent += "</div>"
removeElementById("accordion");
removeElementById("summary");
$(".seperator1").after(itemContent);;
},"json")
}
web.xml配置
<servlet>
<servlet-name>runcases</servlet-name>
<servlet-class>com.xxx.servlet.RunMonitorCasesServlet</servlet-class>
<init-param>
<param-name>monitorCaseRootPath</param-name>
<param-value>此处配置jmx文件存储路径</param-value>
</init-param>
<init-param>
<param-name>jmeterCommand</param-name>
<param-value>此处配置jmeter执行文件路径</param-value>
</init-param>
<!-- 设置结果文件存储路径 -->
<init-param>
<param-name>caseResultPath</param-name>
<param-value>此处配置结果文件存储路径</param-value>
</init-param>
<!--设置各个业务线邮箱接收人 支持多个邮箱,英文逗号分隔即可 -->
<init-param>
<param-name>serverline1</param-name>
<param-value>xxx@xxx.com</param-value>
</init-param>
<init-param>
<param-name>serverline2</param-name>
<param-value>xxx@xxx.com</param-value>
</init-param>
……
<init-param>
<param-name>testmail</param-name>
<param-value>xxx@xxx.com</param-value>
</init-param>
<!-- 设置各个业务线短信接收人 支持多个手机号,英文逗号分隔即可-->
<init-param>
<param-name>serverline_sms1</param-name>
<param-value>1xxxxxxxxxx</param-value>
</init-param>
<init-param>
<param-name>serverline_sms2</param-name>
<param-value>1xxxxxxxxxx</param-value>
</init-param>
……
</servlet>
<servlet-mapping>
<servlet-name>runcases</servlet-name>
<url-pattern>/runcases</url-pattern>
</servlet-mapping>
RunMonitorCasesServlet中实现了2个功能,
1.执行jmx文件并返回结果
2.将执行结果进行分析
3.发送邮件以及短信
由于发送短信是直接调用公司同事开发的接口,再次就不说明了,本篇值介绍执行jmx文件并返回结果,并分析,下一篇会单独介绍发送邮件~
定义变量
private static final long serialVersionUID = 1L;
// 定义一个ServletConfig对象
private ServletConfig config = null;
//定义case存储路径
private String monitorCaseRootPath = "";
//定义Jmeter执行文件路径
private String jmeterCommand = "";
//定义结果文件存放路径(总路径)
private String caseResultPath = "";
// 获取csv解析结果列表
private ArrayList<String[]> csvList = new ArrayList<String[]>();
//定义时间戳结果差
private Long timejmx = (long) 0;
int csvindex=0;
private static Logger loginfo=Logger.getLogger(RunMonitorCasesServlet.class);
获取文件配置信息
//获取配置文件信息
public void init(ServletConfig config) throws ServletException {
super.init(config); // 继承父类的init()方法
this.config = config; // 获取配置信息
monitorCaseRootPath = config.getInitParameter("monitorCaseRootPath");
jmeterCommand = config.getInitParameter("jmeterCommand");
caseResultPath = config.getInitParameter("caseResultPath");
//配置email信息
serverLine_Mail1 = config.getInitParameter("serverline1");
serverLine_Mail2 = config.getInitParameter("serverline2");
testMail = config.getInitParameter("testmail");
mailMap.put("serverline1",serverLine_Mail1);
mailMap.put("serverline2", serverLine_Mail2);
mailMap.put("test", testMail);
//省略短信配置
}
编写post方法(执行jmx文件)
//定义返回类型和字符集
res.setContentType("application/json; charset=utf-8");
//输出流对象
PrintWriter out = res.getWriter();
//获取请求中传输的业务线名称&监控时长
String lineName = req.getParameter("lineName");
String frequency = req.getParameter("frequency");
String smsValue=req.getParameter("smsValue");
//将监控时长转换为int类型,便于后面进行处理
int frequencyValue = 0;
try {
frequencyValue = Integer.parseInt(frequency);
} catch (NumberFormatException e) {
e.printStackTrace();
}
try {
//定义返回值json
JSONObject jsonObject = new JSONObject();
//定义json包含的数组
JSONArray arraycase = new JSONArray();
//处理case存放路径
File rootFolder = new File(monitorCaseRootPath + lineName);
File[] caseFileList = rootFolder.listFiles();
//定义caseName&当日时间_用于定义结果文件名
String caseName = "";
String caseDate = formatTodayDate();
//创建当日结果文件存放文件夹
File caseResultPathFile=new File(caseResultPath+lineName+File.separator+caseDate+File.separator);
if(!caseResultPathFile.exists()){
caseResultPathFile.mkdirs();
}
//执行case&输出结果
for (int i = 0; i < caseFileList.length; i++) {
// 仅处理文件
if (caseFileList[i].isFile() && caseFileList[i].toString().endsWith(".jmx") ) {
//获取caseName的值
caseName = caseFileList[i].getName();
//创建结果存放文件
File resultFile = new File(
caseResultPath+lineName+File.separator+caseDate+File.separator + caseName.substring(0, caseName.lastIndexOf(".")) +"_"+ caseDate + ".csv");
if(!resultFile.exists()){
resultFile.createNewFile();
}
//执行case并输出csv结果文件
Process process = Runtime.getRuntime()
.exec(jmeterCommand + " -n -t " + caseFileList[i].toString() + " -l " + caseResultPath+lineName+File.separator+caseDate+File.separator
+ caseName.substring(0, caseName.lastIndexOf(".")) +"_"+ caseDate + ".csv");
process.waitFor(4, TimeUnit.SECONDS);
}
}
分析结果文件
//结果处理
//创建失败计数文件,并将每条case计数设置为0
File countFile=new File(caseResultPath+lineName+"countFile.txt");
//定义执行case总数total
int total = 0;
for (int i = 0; i < caseFileList.length; i++) {
if (caseFileList[i].isFile() && caseFileList[i].toString().endsWith(".jmx")) {
total++;
//遍历将id,fileName存入json中
JSONObject jsonObjectcase = new JSONObject();
jsonObjectcase.put("id", total);
jsonObjectcase.put("fileName", caseFileList[i].getName().toString());
caseName = caseFileList[i].getName();
//读取结果文件
int readCount=0;
while(readCount<3) {
//等待2s后读取结果文件
TimeUnit.SECONDS.sleep(2);
csvList = read(
caseResultPath+lineName+File.separator+caseDate+File.separator + caseName.substring(0, caseName.lastIndexOf(".")) +"_"+ caseDate + ".csv");
File file=new File(caseResultPath+lineName+File.separator+caseDate+File.separator + caseName.substring(0, caseName.lastIndexOf(".")) +"_"+ caseDate + ".csv");
long time=file.lastModified();
Date nowTime = new Date(System.currentTimeMillis());
timejmx = nowTime.getTime() - time;
if(csvList.size()==0) {
readCount++;
if(readCount==3) {
jsonObjectcase.put("timedate", time);
jsonObjectcase.put("success", "false");
jsonObjectcase.put("failureMessage", "当日首次写入文件失败");
}
}else if(timejmx / 1000 > frequencyValue) {
readCount++;
if(readCount==3) {
jsonObjectcase.put("timedate", time);
jsonObjectcase.put("success", "false");
jsonObjectcase.put("failureMessage", "无法读取到最近一次执行结果");
}
}else {
int csvindex=csvList.size() - 1;
//读取结果文件的最后一条,将时间戳,结果,错误信息存入json中
jsonObjectcase.put("timedate", csvList.get(csvindex)[0]);
jsonObjectcase.put("success", csvList.get(csvindex)[7]);
jsonObjectcase.put("failureMessage", csvList.get(csvindex)[8]);
readCount=3;
}
}
FileReader fr = new FileReader(countFile);
//创建集合对象
Properties pro = new Properties();
pro.load(fr);
fr.close();
String caseFailValue =pro.getProperty(lineName+"_countnum_caseFail"+total);
String readFailValue =pro.getProperty(lineName+"_countnum_caseFail"+total);
jsonObjectcase.put("caseFailCount",caseFailValue );
jsonObjectcase.put("readFailCount",readFailValue);
//将当前case的所有信息存入到json数组中
arraycase.add(jsonObjectcase);
jsonObject.put("data", arraycase);
}
}
//将执行case的计数存入数组中
jsonObject.put("total", total);
//报警逻辑,根据json+计数文件 操作发送邮件
int caseFailFlag=0;
int readFailFlag=0;
for(int i=0;i<jsonObject.getJSONArray("data").size();i++) {
//文件已经存在
//输入流读取文件
FileReader fr = new FileReader(countFile);
//创建集合对象
Properties pro = new Properties();
pro.load(fr);
fr.close();
//获取count值
String caseid= jsonObject.getJSONArray("data").getJSONObject(i).get("id")+"";
String caseFailValue = pro.getProperty(lineName+"_countnum_caseFail"+caseid);
String readFailValue =pro.getProperty(lineName+"_countnum_readFail"+caseid);
int caseFailCount = Integer.parseInt(caseFailValue);
int readFailCount = Integer.parseInt(readFailValue);
//首先判断本次执行case是否fail,若fail,再进行判断
if(jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage")!="") {
if(!jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("当日首次写入文件失败") ||
!jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("无法读取到最近一次执行结果") ) {
//fail计数增加1,
caseFailCount++;
//fail计数为3时,发送邮件
if(caseFailCount==3) {
pro.setProperty(lineName+"_countnum_caseFail"+caseid, caseFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("caseFailCount",caseFailCount+"");
caseFailFlag=1;
//fail计数为15时,清空计数
}else if(caseFailCount==15){
caseFailCount=0;
pro.setProperty(lineName+"_countnum_caseFail"+caseid, caseFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("caseFailCount",caseFailCount+"");
}else {
pro.setProperty(lineName+"_countnum_caseFail"+caseid, caseFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("caseFailCount",caseFailCount+"");
}
}else {
if(jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("当日首次写入文件失败") &&
jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("无法读取到最近一次执行结果") ) {
readFailCount++;
if(readFailCount==3) {
pro.setProperty(lineName+"_countnum_readFail"+caseid, readFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("readFailCount",readFailCount+"");
readFailFlag=1;
//fail计数为15时,清空计数
}else if(readFailCount==15) {
readFailCount=0;
pro.setProperty(lineName+"_countnum_readFail"+caseid, readFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("readFailCount",readFailCount+"");
}else {
pro.setProperty(lineName+"_countnum_readFail"+caseid, readFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("readFailCount",readFailCount+"");
}
}
}
//本次执行case,结果为成功,将计数清零存储至计数文件
}else {
caseFailCount=0;
readFailCount=0;
pro.setProperty(lineName+"_countnum_caseFail"+caseid, caseFailCount+"");
pro.setProperty(lineName+"_countnum_readFail"+caseid, readFailCount+"");
FileWriter fw = new FileWriter(countFile);
pro.store(fw, "");
fw.close();
jsonObject.getJSONArray("data").getJSONObject(i).put("caseFailCount",caseFailCount+"");
jsonObject.getJSONArray("data").getJSONObject(i).put("readFailCount",readFailCount+"");
};
}
if(caseFailFlag==1) {
send("caseFail",lineName,jsonObject,mailMap);
if(smsValue.equals("true")) {
// 发送短信
}
}
if(readFailFlag==1) {
send("readFail",lineName,jsonObject,mailMap);
}
out.write(jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
out.println(e.toString());
}
out.close();