fix: 有附件的案例或场景转JMX时,附件也要加过去

有附件的案例或场景转JMX时,附件也要加过去
This commit is contained in:
song.tianyang 2021-03-09 19:10:27 +08:00
parent add62bacaa
commit 3d822ac0bb
14 changed files with 197 additions and 61 deletions

View File

@ -378,11 +378,8 @@ public class APITestController {
String testName = runRequest.getName();
//将jmx处理封装为通用方法
jmxString = apiTestService.updateJmxString(jmxString,testName,false);
JmxInfoDTO dto = new JmxInfoDTO();
JmxInfoDTO dto = apiTestService.updateJmxString(jmxString,testName,false);
dto.setName(runRequest.getName() + ".jmx");
dto.setXml(jmxString);
return dto;
}

View File

@ -1,32 +1,18 @@
package io.metersphere.api.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.metersphere.api.dto.document.ApiDocumentInfoDTO;
import io.metersphere.api.dto.document.ApiDocumentRequest;
import io.metersphere.api.dto.document.ApiDocumentShareRequest;
import io.metersphere.api.dto.document.ApiDocumentSimpleInfoDTO;
import io.metersphere.api.dto.document.ApiDocumentShareDTO;
import io.metersphere.api.dto.document.ApiDocumentShareRequest;
import io.metersphere.api.service.APITestService;
import io.metersphere.api.service.ApiDefinitionService;
import io.metersphere.api.service.ApiDocumentService;
import io.metersphere.base.domain.ApiDefinition;
import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiDocumentShare;
import io.metersphere.base.domain.ApiDocumentShareExample;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.python.antlr.ast.Str;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author song.tianyang
@ -68,28 +54,4 @@ public class ApiDocumentController {
ApiDocumentShareDTO returnDTO = apiDocumentService.conversionApiDocumentShareToDTO(apiShare);
return returnDTO;
}
@GetMapping("/updateJmxByFile")
public String updateJmxByFile(){
StringBuilder jmxBuilder = new StringBuilder();
try {
String filePath = "/Users/admin/Downloads/成功吧 (20).jmx";
File file = new File(filePath);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String strLine = null;
while(null != (strLine = bufferedReader.readLine())){
if(StringUtils.isNotEmpty(strLine)){
jmxBuilder.append(strLine);
}
}
}catch(Exception e){
e.printStackTrace();
}
String jmx = apiTestService.updateJmxString(jmxBuilder.toString(),null,false);
return jmx;
}
}

View File

@ -1,8 +1,11 @@
package io.metersphere.api.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
/**
* @author song.tianyang
* @Date 2021/1/5 5:48 下午
@ -10,7 +13,9 @@ import lombok.Setter;
*/
@Getter
@Setter
@AllArgsConstructor
public class JmxInfoDTO {
private String name;
private String xml;
private Map<String, String> attachFiles;
}

View File

@ -472,11 +472,13 @@ public class APITestService {
* @return
* @author song tianyang
*/
public String updateJmxString(String jmxString, String testNameParam, boolean isFromScenario) {
public JmxInfoDTO updateJmxString(String jmxString, String testNameParam, boolean isFromScenario) {
// 与1.7分支合并时如果该方法产生冲突请以master为准
String attribute_testName = "testname";
String[] requestElementNameArr = new String[]{"HTTPSamplerProxy", "TCPSampler", "JDBCSampler", "DubboSample"};
List<String> attachmentFilePathList = new ArrayList<>();
try {
//将ThreadGroup的testname改为接口名称
Document doc = DocumentHelper.parseText(jmxString);// 获取可续保保单列表报文模板
@ -511,6 +513,9 @@ public class APITestService {
for (Element configTestElement : hashTreeConfigTestElementList) {
this.updateDubboDefaultConfigGuiElement(configTestElement);
}
//HTTPSamplerProxy 进行附件转化 1.elementProp里去掉路径 2elementProp->filePath获取路径并读出来
attachmentFilePathList.addAll(this.parseAttachmentFileInfo(element));
}
}
jmxString = root.asXML();
@ -521,7 +526,60 @@ public class APITestService {
if (!jmxString.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")) {
jmxString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + jmxString;
}
return jmxString;
//处理附件
Map<String, String> attachmentFiles = new HashMap<>();
int fileIndex = 0;
for (String filePath: attachmentFilePathList) {
File file = new File(filePath);
if(file.exists() && file.isFile()){
try{
FileMetadata fileMetadata = fileService.saveFile(file,FileUtil.readAsByteArray(file),fileIndex++);
attachmentFiles.put(fileMetadata.getId(),fileMetadata.getName());
}catch (Exception e){
e.printStackTrace();
}
}
}
JmxInfoDTO returnDTO = new JmxInfoDTO("Demo.jmx",jmxString,attachmentFiles);
return returnDTO;
}
private List<String> parseAttachmentFileInfo(Element parentHashTreeElement) {
List<String> attachmentFilePathList = new ArrayList<>();
List<Element> parentElementList = parentHashTreeElement.elements();
for (Element parentElement: parentElementList) {
String qname = parentElement.getQName().getName();
if (StringUtils.equals(qname,"HTTPSamplerProxy")){
List<Element> elementPropElementList = parentElement.elements("elementProp");
for (Element element : elementPropElementList) {
if(StringUtils.equals(element.attributeValue("name"),"HTTPsampler.Files")){
String name = element.getName();
List<Element> collectionPropList = element.elements("collectionProp");
for (Element prop: collectionPropList) {
List<Element> elementProps = prop.elements();
for (Element elementProp: elementProps) {
if(StringUtils.equals(elementProp.attributeValue("elementType"),"HTTPFileArg")){
try{
String filePath = elementProp.attributeValue("name");
File file = new File(filePath);
if(file.exists() && file.isFile()){
attachmentFilePathList.add(filePath);
String fileName = file.getName();
elementProp.attribute("name").setText(fileName);
}
}catch (Exception e){
}
}
}
}
}
}
}
}
return attachmentFilePathList;
}
private void updateDubboDefaultConfigGuiElement(Element configTestElement) {

View File

@ -767,22 +767,10 @@ public class ApiAutomationService {
HashTree jmeterHashTree = generateHashTree(apiScenarios, request, null);
String jmx = testPlan.getJmx(jmeterHashTree);
jmx = apiTestService.updateJmxString(jmx, testName, true);
//将ThreadGroup的testname改为接口名称
// Document doc = DocumentHelper.parseText(jmx);// 获取可续保保单列表报文模板
// Element root = doc.getRootElement();
// Element rootHashTreeElement = root.element("hashTree");
// Element innerHashTreeElement = rootHashTreeElement.elements("hashTree").get(0);
// Element theadGroupElement = innerHashTreeElement.elements("ThreadGroup").get(0);
// theadGroupElement.attribute("testname").setText(testName);
// jmx = root.asXML();
JmxInfoDTO dto = apiTestService.updateJmxString(jmx, testName, true);
String name = request.getName() + ".jmx";
JmxInfoDTO dto = new JmxInfoDTO();
dto.setName(name);
dto.setXml(jmx);
return dto;
}
@ -931,7 +919,7 @@ public class ApiAutomationService {
if (StringUtils.isNotEmpty(item.getScenarioDefinition())) {
String jmx = generateJmx(item);
if (StringUtils.isNotEmpty(jmx)) {
ApiScenrioExportJmx scenrioExportJmx = new ApiScenrioExportJmx(item.getName(), apiTestService.updateJmxString(jmx, null, true));
ApiScenrioExportJmx scenrioExportJmx = new ApiScenrioExportJmx(item.getName(), apiTestService.updateJmxString(jmx, null, true).getXml());
resList.add(scenrioExportJmx);
}
}

View File

@ -150,6 +150,11 @@ public class PerformanceTestController {
return fileService.getFileMetadataByTestId(testId);
}
@GetMapping("/file/getMetadataById/{metadataId}")
public FileMetadata getMetadataById(@PathVariable String metadataId) {
return fileService.getFileMetadataById(metadataId);
}
@PostMapping("/file/download")
public ResponseEntity<byte[]> downloadJmx(@RequestBody FileOperationRequest fileOperationRequest) {
byte[] bytes = fileService.loadFileAsBytes(fileOperationRequest.getId());

View File

@ -12,4 +12,5 @@ import java.util.Map;
public class SaveTestPlanRequest extends TestPlanRequest {
private List<FileMetadata> updatedFileList;
private Map<String, Integer> fileSorts;
private List<String> conversionFileIdList;
}

View File

@ -138,10 +138,35 @@ public class PerformanceTestService {
this.importFiles(importFileIds, loadTest.getId(), request.getFileSorts());
// 保存上传的文件
this.saveUploadFiles(files, loadTest.getId(), request.getFileSorts());
//关联转化的文件
this.conversionFiles(loadTest.getId(),request.getConversionFileIdList());
return loadTest.getId();
}
private void conversionFiles(String id, List<String> conversionFileIdList) {
for (String metaFileId : conversionFileIdList) {
if(!this.loadTestFileExsits(id,metaFileId)){
LoadTestFile loadTestFile = new LoadTestFile();
loadTestFile.setTestId(id);
loadTestFile.setFileId(metaFileId);
loadTestFileMapper.insert(loadTestFile);
}
}
}
private boolean loadTestFileExsits(String testId, String metaFileId) {
boolean fileExsits = fileService.isFileExsits(metaFileId);
LoadTestFileExample example = new LoadTestFileExample();
example.createCriteria().andTestIdEqualTo(testId).andFileIdEqualTo(metaFileId);
long loadTestFiles = loadTestFileMapper.countByExample(example);
if(!fileExsits && loadTestFiles>0){
return false;
}else {
return true;
}
}
private void saveUploadFiles(List<MultipartFile> files, String testId, Map<String, Integer> fileSorts) {
if (files != null) {
for (int i = 0; i < files.size(); i++) {

View File

@ -12,6 +12,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@ -113,6 +114,26 @@ public class FileService {
return fileMetadata;
}
public FileMetadata saveFile(File file, byte[] fileByte, Integer sort) {
final FileMetadata fileMetadata = new FileMetadata();
fileMetadata.setId(UUID.randomUUID().toString());
fileMetadata.setName(file.getName());
fileMetadata.setSize(file.length());
fileMetadata.setCreateTime(System.currentTimeMillis());
fileMetadata.setUpdateTime(System.currentTimeMillis());
FileType fileType = getFileType(fileMetadata.getName());
fileMetadata.setType(fileType.name());
fileMetadata.setSort(sort);
fileMetadataMapper.insert(fileMetadata);
FileContent fileContent = new FileContent();
fileContent.setFileId(fileMetadata.getId());
fileContent.setFile(fileByte);
fileContentMapper.insert(fileContent);
return fileMetadata;
}
public FileMetadata saveFile(byte[] fileByte, String fileName, Long fileSize) {
final FileMetadata fileMetadata = new FileMetadata();
fileMetadata.setId(UUID.randomUUID().toString());
@ -185,4 +206,15 @@ public class FileService {
public void updateFileMetadata(FileMetadata fileMetadata) {
fileMetadataMapper.updateByPrimaryKeySelective(fileMetadata);
}
public boolean isFileExsits(String fileId) {
FileMetadataExample example = new FileMetadataExample();
example.createCriteria().andIdEqualTo(fileId);
long fileCount = fileMetadataMapper.countByExample(example);
if(fileCount>0){
return true;
}else {
return false;
}
}
}

View File

@ -55,6 +55,8 @@
let jmxObj = {};
jmxObj.name = response.data.name;
jmxObj.xml = response.data.xml;
jmxObj.attachFiles = response.data.attachFiles;
jmxObj.attachByteFiles = response.data.attachByteFiles;
this.$store.commit('setTest', {
name: row.name,
jmx: jmxObj

View File

@ -597,6 +597,8 @@ export default {
let jmxObj = {};
jmxObj.name = response.data.name;
jmxObj.xml = response.data.xml;
jmxObj.attachFiles = response.data.attachFiles;
jmxObj.attachByteFiles = response.data.attachByteFiles;
this.$store.commit('setTest', {
name: row.name,
jmx: jmxObj

View File

@ -87,6 +87,8 @@
let jmxObj = {};
jmxObj.name = response.data.name;
jmxObj.xml = response.data.xml;
jmxObj.attachFiles = response.data.attachFiles;
jmxObj.attachByteFiles = response.data.attachByteFiles;
this.$store.commit('setTest', {
name: row.name,
jmx: jmxObj

View File

@ -129,6 +129,15 @@ export default {
let file = new File([blob], apiTest.jmx.name);
this.$refs.basicConfig.beforeUploadJmx(file);
this.$refs.basicConfig.handleUpload({file: file});
if(JSON.stringify(apiTest.jmx.attachFiles) != "{}"){
let attachFiles = [];
for(let fileID in apiTest.jmx.attachFiles){
attachFiles.push(fileID);
}
if(attachFiles.length > 0){
this.$refs.basicConfig.selectAttachFileById(attachFiles);
}
}
this.active = '1';
this.$store.commit("clearTest");
}
@ -191,6 +200,7 @@ export default {
//
this.test.updatedFileList = this.$refs.basicConfig.updatedFileList();
this.test.fileSorts = this.$refs.basicConfig.fileSorts();
this.test.conversionFileIdList = this.$refs.basicConfig.conversionMetadataIdList();
//
this.test.loadConfiguration = JSON.stringify(this.$refs.pressureConfig.convertProperty());
this.test.testResourcePoolId = this.$refs.pressureConfig.resourcePool;
@ -215,6 +225,30 @@ export default {
}
};
},
stringToByte(str) {
var bytes = new Array();
var len, c;
len = str.length;
for(var i = 0; i < len; i++) {
c = str.charCodeAt(i);
if(c >= 0x010000 && c <= 0x10FFFF) {
bytes.push(((c >> 18) & 0x07) | 0xF0);
bytes.push(((c >> 12) & 0x3F) | 0x80);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if(c >= 0x000800 && c <= 0x00FFFF) {
bytes.push(((c >> 12) & 0x0F) | 0xE0);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if(c >= 0x000080 && c <= 0x0007FF) {
bytes.push(((c >> 6) & 0x1F) | 0xC0);
bytes.push((c & 0x3F) | 0x80);
} else {
bytes.push(c & 0xFF);
}
}
return bytes;
},
cancel() {
this.$router.push({path: '/performance/test/all'})
},

View File

@ -47,7 +47,8 @@
label="ThreadGroup">
<template v-slot:default="{row}">
<el-select v-model="row.tgType" :placeholder="$t('commons.please_select')" size="small">
<el-option v-for="tg in threadGroupForSelect" :key="tg.tagName" :label="tg.name" :value="tg.testclass"></el-option>
<el-option v-for="tg in threadGroupForSelect" :key="tg.tagName" :label="tg.name"
:value="tg.testclass"></el-option>
</el-select>
</template>
</el-table-column>
@ -163,11 +164,13 @@ export default {
result: {},
projectLoadingResult: {},
getFileMetadataPath: "/performance/file/metadata",
getFileMetadataById: "/performance/file/getMetadataById",
jmxDownloadPath: '/performance/file/download',
jmxDeletePath: '/performance/file/delete',
fileList: [],
tableData: [],
uploadList: [],
metadataIdList:[],
fileNumLimit: 10,
threadGroups: [],
loadFileVisible: false,
@ -211,6 +214,7 @@ export default {
this.fileList = [];
this.tableData = [];
this.uploadList = [];
this.metadataIdList = [];
this.result = this.$get(this.getFileMetadataPath + "/" + test.id, response => {
let files = response.data;
if (!files) {
@ -280,6 +284,22 @@ export default {
};
jmxReader.readAsText(file);
},
selectAttachFileById(metadataIdArr) {
this.metadataIdList = metadataIdArr;
for (let i = 0; i < metadataIdArr.length; i++) {
let id = metadataIdArr[i];
this.result = this.$get(this.getFileMetadataById + "/" + id, response => {
let files = response.data;
if (files) {
this.fileList.push(JSON.parse(JSON.stringify(files)));
this.tableData.push(JSON.parse(JSON.stringify(files)));
this.tableData.map(f => {
f.size = (f.size / 1024).toFixed(2) + ' KB';
});
}
})
}
},
handleDownload(file) {
let data = {
name: file.name,
@ -364,6 +384,9 @@ export default {
updatedFileList() {
return this.fileList;//
},
conversionMetadataIdList() {
return this.metadataIdList;//
},
fileSorts() {
let fileSorts = {};
this.tableData.forEach((f, index) => {