api测试保存jmx

This commit is contained in:
q4speed 2020-04-27 17:10:21 +08:00
parent 573d42230a
commit ec113b1b16
9 changed files with 862 additions and 82 deletions

View File

@ -134,6 +134,25 @@
<version>5.1</version> <version>5.1</version>
</dependency> </dependency>
<!-- jmeter -->
<!-- <dependency>-->
<!-- <groupId>org.apache.jmeter</groupId>-->
<!-- <artifactId>ApacheJMeter_core</artifactId>-->
<!-- <version>${jmeter.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_http</artifactId>
<version>${jmeter.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- easyexcel --> <!-- easyexcel -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>

View File

@ -11,11 +11,13 @@ import io.metersphere.base.domain.ApiTestWithBLOBs;
import io.metersphere.commons.constants.RoleConstants; import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.utils.PageUtils; import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager; import io.metersphere.commons.utils.Pager;
import io.metersphere.controller.request.testplan.SaveTestPlanRequest;
import io.metersphere.service.FileService; import io.metersphere.service.FileService;
import io.metersphere.user.SessionUtils; import io.metersphere.user.SessionUtils;
import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
@ -46,9 +48,9 @@ public class APITestController {
return PageUtils.setPageInfo(page, apiTestService.list(request)); return PageUtils.setPageInfo(page, apiTestService.list(request));
} }
@PostMapping(value = "/save") @PostMapping(value = "/save", consumes = {"multipart/form-data"})
public String save(@RequestBody SaveAPITestRequest request) { public String save(@RequestPart("request") SaveAPITestRequest request, @RequestPart(value = "files") List<MultipartFile> files) {
return apiTestService.save(request); return apiTestService.save(request, files);
} }
@GetMapping("/get/{testId}") @GetMapping("/get/{testId}")
@ -61,8 +63,8 @@ public class APITestController {
apiTestService.delete(request); apiTestService.delete(request);
} }
@PostMapping("/run") @PostMapping(value = "/run", consumes = {"multipart/form-data"})
public void run(@RequestBody SaveAPITestRequest request) { public String run(@RequestPart("request") SaveAPITestRequest request, @RequestPart(value = "files") List<MultipartFile> files) {
apiTestService.run(request); return apiTestService.run(request, files);
} }
} }

View File

@ -5,7 +5,8 @@ import io.metersphere.api.dto.DeleteAPITestRequest;
import io.metersphere.api.dto.QueryAPITestRequest; import io.metersphere.api.dto.QueryAPITestRequest;
import io.metersphere.api.dto.SaveAPITestRequest; import io.metersphere.api.dto.SaveAPITestRequest;
import io.metersphere.base.domain.*; import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.*; import io.metersphere.base.mapper.ApiTestFileMapper;
import io.metersphere.base.mapper.ApiTestMapper;
import io.metersphere.base.mapper.ext.ExtApiTestMapper; import io.metersphere.base.mapper.ext.ExtApiTestMapper;
import io.metersphere.commons.constants.APITestStatus; import io.metersphere.commons.constants.APITestStatus;
import io.metersphere.commons.exception.MSException; import io.metersphere.commons.exception.MSException;
@ -14,9 +15,12 @@ import io.metersphere.service.FileService;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -29,12 +33,6 @@ public class ApiTestService {
@Resource @Resource
private ExtApiTestMapper extApiTestMapper; private ExtApiTestMapper extApiTestMapper;
@Resource @Resource
private ProjectMapper projectMapper;
@Resource
private FileMetadataMapper fileMetadataMapper;
@Resource
private FileContentMapper fileContentMapper;
@Resource
private ApiTestFileMapper apiTestFileMapper; private ApiTestFileMapper apiTestFileMapper;
@Resource @Resource
private FileService fileService; private FileService fileService;
@ -48,13 +46,27 @@ public class ApiTestService {
return extApiTestMapper.list(request); return extApiTestMapper.list(request);
} }
public String save(SaveAPITestRequest request) { public String save(SaveAPITestRequest request, List<MultipartFile> files) {
if (files == null) {
throw new IllegalArgumentException(Translator.get("file_cannot_be_null"));
}
final ApiTestWithBLOBs test; final ApiTestWithBLOBs test;
if (StringUtils.isNotBlank(request.getId())) { if (StringUtils.isNotBlank(request.getId())) {
// 删除原来的文件
deleteFileByTestId(request.getId());
test = updateTest(request); test = updateTest(request);
} else { } else {
test = createTest(request); test = createTest(request);
} }
// 保存新文件
files.forEach(file -> {
final FileMetadata fileMetadata = fileService.saveFile(file);
ApiTestFile apiTestFile = new ApiTestFile();
apiTestFile.setTestId(test.getId());
apiTestFile.setFileId(fileMetadata.getId());
apiTestFileMapper.insert(apiTestFile);
});
return test.getId(); return test.getId();
} }
@ -66,8 +78,8 @@ public class ApiTestService {
apiTestMapper.deleteByPrimaryKey(request.getId()); apiTestMapper.deleteByPrimaryKey(request.getId());
} }
public void run(SaveAPITestRequest request) { public String run(SaveAPITestRequest request, List<MultipartFile> files) {
save(request); return save(request, files);
} }
private ApiTestWithBLOBs updateTest(SaveAPITestRequest request) { private ApiTestWithBLOBs updateTest(SaveAPITestRequest request) {
@ -101,4 +113,17 @@ public class ApiTestService {
return test; return test;
} }
public void deleteFileByTestId(String testId) {
ApiTestFileExample ApiTestFileExample = new ApiTestFileExample();
ApiTestFileExample.createCriteria().andTestIdEqualTo(testId);
final List<ApiTestFile> ApiTestFiles = apiTestFileMapper.selectByExample(ApiTestFileExample);
apiTestFileMapper.deleteByExample(ApiTestFileExample);
if (!CollectionUtils.isEmpty(ApiTestFiles)) {
final List<String> fileIds = ApiTestFiles.stream().map(ApiTestFile::getFileId).collect(Collectors.toList());
fileService.deleteFileByIds(fileIds);
}
}
} }

View File

@ -5,11 +5,18 @@ import io.metersphere.base.mapper.FileContentMapper;
import io.metersphere.base.mapper.FileMetadataMapper; import io.metersphere.base.mapper.FileMetadataMapper;
import io.metersphere.base.mapper.ApiTestFileMapper; import io.metersphere.base.mapper.ApiTestFileMapper;
import io.metersphere.base.mapper.LoadTestFileMapper; import io.metersphere.base.mapper.LoadTestFileMapper;
import io.metersphere.commons.constants.FileType;
import io.metersphere.commons.exception.MSException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@ -58,25 +65,6 @@ public class FileService {
return fileContentMapper.selectByPrimaryKey(fileId); return fileContentMapper.selectByPrimaryKey(fileId);
} }
public void deleteFileByTestId(String testId) {
LoadTestFileExample loadTestFileExample = new LoadTestFileExample();
loadTestFileExample.createCriteria().andTestIdEqualTo(testId);
final List<LoadTestFile> loadTestFiles = loadTestFileMapper.selectByExample(loadTestFileExample);
loadTestFileMapper.deleteByExample(loadTestFileExample);
if (!CollectionUtils.isEmpty(loadTestFiles)) {
final List<String> fileIds = loadTestFiles.stream().map(LoadTestFile::getFileId).collect(Collectors.toList());
FileMetadataExample fileMetadataExample = new FileMetadataExample();
fileMetadataExample.createCriteria().andIdIn(fileIds);
fileMetadataMapper.deleteByExample(fileMetadataExample);
FileContentExample fileContentExample = new FileContentExample();
fileContentExample.createCriteria().andFileIdIn(fileIds);
fileContentMapper.deleteByExample(fileContentExample);
}
}
public void deleteFileByIds(List<String> ids) { public void deleteFileByIds(List<String> ids) {
if (CollectionUtils.isEmpty(ids)) { if (CollectionUtils.isEmpty(ids)) {
return; return;
@ -89,4 +77,33 @@ public class FileService {
example2.createCriteria().andFileIdIn(ids); example2.createCriteria().andFileIdIn(ids);
fileContentMapper.deleteByExample(example2); fileContentMapper.deleteByExample(example2);
} }
public FileMetadata saveFile(MultipartFile file) {
final FileMetadata fileMetadata = new FileMetadata();
fileMetadata.setId(UUID.randomUUID().toString());
fileMetadata.setName(file.getOriginalFilename());
fileMetadata.setSize(file.getSize());
fileMetadata.setCreateTime(System.currentTimeMillis());
fileMetadata.setUpdateTime(System.currentTimeMillis());
FileType fileType = getFileType(fileMetadata.getName());
fileMetadata.setType(fileType.name());
fileMetadataMapper.insert(fileMetadata);
FileContent fileContent = new FileContent();
fileContent.setFileId(fileMetadata.getId());
try {
fileContent.setFile(file.getBytes());
} catch (IOException e) {
MSException.throwException(e);
}
fileContentMapper.insert(fileContent);
return fileMetadata;
}
private FileType getFileType(String filename) {
int s = filename.lastIndexOf(".") + 1;
String type = filename.substring(s);
return FileType.valueOf(type.toUpperCase());
}
} }

View File

@ -22,6 +22,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -39,10 +40,6 @@ public class PerformanceTestService {
@Resource @Resource
private ExtLoadTestMapper extLoadTestMapper; private ExtLoadTestMapper extLoadTestMapper;
@Resource @Resource
private FileMetadataMapper fileMetadataMapper;
@Resource
private FileContentMapper fileContentMapper;
@Resource
private LoadTestFileMapper loadTestFileMapper; private LoadTestFileMapper loadTestFileMapper;
@Resource @Resource
private FileService fileService; private FileService fileService;
@ -62,7 +59,19 @@ public class PerformanceTestService {
public void delete(DeleteTestPlanRequest request) { public void delete(DeleteTestPlanRequest request) {
loadTestMapper.deleteByPrimaryKey(request.getId()); loadTestMapper.deleteByPrimaryKey(request.getId());
fileService.deleteFileByTestId(request.getId()); deleteFileByTestId(request.getId());
}
public void deleteFileByTestId(String testId) {
LoadTestFileExample loadTestFileExample = new LoadTestFileExample();
loadTestFileExample.createCriteria().andTestIdEqualTo(testId);
final List<LoadTestFile> loadTestFiles = loadTestFileMapper.selectByExample(loadTestFileExample);
loadTestFileMapper.deleteByExample(loadTestFileExample);
if (!CollectionUtils.isEmpty(loadTestFiles)) {
final List<String> fileIds = loadTestFiles.stream().map(LoadTestFile::getFileId).collect(Collectors.toList());
fileService.deleteFileByIds(fileIds);
}
} }
public String save(SaveTestPlanRequest request, List<MultipartFile> files) { public String save(SaveTestPlanRequest request, List<MultipartFile> files) {
@ -71,7 +80,7 @@ public class PerformanceTestService {
} }
final LoadTestWithBLOBs loadTest = saveLoadTest(request); final LoadTestWithBLOBs loadTest = saveLoadTest(request);
files.forEach(file -> { files.forEach(file -> {
final FileMetadata fileMetadata = saveFile(file); final FileMetadata fileMetadata = fileService.saveFile(file);
LoadTestFile loadTestFile = new LoadTestFile(); LoadTestFile loadTestFile = new LoadTestFile();
loadTestFile.setTestId(loadTest.getId()); loadTestFile.setTestId(loadTest.getId());
loadTestFile.setFileId(fileMetadata.getId()); loadTestFile.setFileId(fileMetadata.getId());
@ -102,35 +111,6 @@ public class PerformanceTestService {
return loadTest; return loadTest;
} }
private FileMetadata saveFile(MultipartFile file) {
final FileMetadata fileMetadata = new FileMetadata();
fileMetadata.setId(UUID.randomUUID().toString());
fileMetadata.setName(file.getOriginalFilename());
fileMetadata.setSize(file.getSize());
fileMetadata.setCreateTime(System.currentTimeMillis());
fileMetadata.setUpdateTime(System.currentTimeMillis());
FileType fileType = getFileType(fileMetadata.getName());
fileMetadata.setType(fileType.name());
fileMetadataMapper.insert(fileMetadata);
FileContent fileContent = new FileContent();
fileContent.setFileId(fileMetadata.getId());
try {
fileContent.setFile(file.getBytes());
} catch (IOException e) {
MSException.throwException(e);
}
fileContentMapper.insert(fileContent);
return fileMetadata;
}
private FileType getFileType(String filename) {
int s = filename.lastIndexOf(".") + 1;
String type = filename.substring(s);
return FileType.valueOf(type.toUpperCase());
}
public String edit(EditTestPlanRequest request, List<MultipartFile> files) { public String edit(EditTestPlanRequest request, List<MultipartFile> files) {
// //
LoadTestWithBLOBs loadTest = loadTestMapper.selectByPrimaryKey(request.getId()); LoadTestWithBLOBs loadTest = loadTestMapper.selectByPrimaryKey(request.getId());
@ -151,7 +131,7 @@ public class PerformanceTestService {
if (files != null) { if (files != null) {
files.forEach(file -> { files.forEach(file -> {
final FileMetadata fileMetadata = saveFile(file); final FileMetadata fileMetadata = fileService.saveFile(file);
LoadTestFile loadTestFile = new LoadTestFile(); LoadTestFile loadTestFile = new LoadTestFile();
loadTestFile.setTestId(request.getId()); loadTestFile.setTestId(request.getId());
loadTestFile.setFileId(fileMetadata.getId()); loadTestFile.setFileId(fileMetadata.getId());

View File

@ -32,6 +32,8 @@
<script> <script>
import MsApiScenarioConfig from "./components/ApiScenarioConfig"; import MsApiScenarioConfig from "./components/ApiScenarioConfig";
import {Test} from "./model/ScenarioModel" import {Test} from "./model/ScenarioModel"
import Jmx from "./model/JMX";
import {get, post, scenario} from "./model/test"
export default { export default {
name: "MsApiTestConfig", name: "MsApiTestConfig",
@ -91,7 +93,7 @@
saveTest: function () { saveTest: function () {
this.change = false; this.change = false;
this.result = this.$post("/api/save", this.getParam(), response => { this.result = this.$request(this.getOptions("/api/save"), response => {
this.test.id = response.data; this.test.id = response.data;
this.$success(this.$t('commons.save_success')); this.$success(this.$t('commons.save_success'));
}); });
@ -99,7 +101,7 @@
runTest: function () { runTest: function () {
this.change = false; this.change = false;
this.result = this.$post("/api/run", this.getParam(), response => { this.result = this.$request(this.getOptions("/api/run"), response => {
this.test.id = response.data; this.test.id = response.data;
this.$success(this.$t('commons.save_success')); this.$success(this.$t('commons.save_success'));
}); });
@ -107,13 +109,32 @@
cancel: function () { cancel: function () {
this.$router.push('/api/test/list/all'); this.$router.push('/api/test/list/all');
}, },
getParam: function () { getOptions: function (url) {
return { let formData = new FormData();
let request = {
id: this.test.id, id: this.test.id,
projectId: this.test.projectId, projectId: this.test.projectId,
name: this.test.name, name: this.test.name,
scenarioDefinition: JSON.stringify(this.test.scenarioDefinition) scenarioDefinition: JSON.stringify(this.test.scenarioDefinition)
} }
let requestJson = JSON.stringify(request);
formData.append('request', new Blob([requestJson], {
type: "application/json"
}));
let jmx = new Jmx(get, "baidu", ["www.baidu.com"]).generate();
let blob = new Blob([jmx], {type: "application/octet-stream"});
formData.append("files", new File([blob], "baidu.jmx"));
return {
method: 'POST',
url: url,
data: formData,
headers: {
'Content-Type': undefined
}
};
} }
}, },

View File

@ -12,18 +12,20 @@
{{$t('api_test.scenario.config')}} {{$t('api_test.scenario.config')}}
</span> </span>
</div> </div>
<el-dropdown trigger="click" @command="handleCommand"> <!-- 暂时去掉将来再-->
<span class="el-dropdown-link el-icon-more scenario-btn"/> <!-- <el-dropdown trigger="click" @command="handleCommand">-->
<el-dropdown-menu slot="dropdown"> <!-- <span class="el-dropdown-link el-icon-more scenario-btn"/>-->
<el-dropdown-item :command="{type:'delete', index:index}">删除场景</el-dropdown-item> <!-- <el-dropdown-menu slot="dropdown">-->
</el-dropdown-menu> <!-- <el-dropdown-item :command="{type:'delete', index:index}">删除场景</el-dropdown-item>-->
</el-dropdown> <!-- </el-dropdown-menu>-->
<!-- </el-dropdown>-->
</template> </template>
<ms-api-request-config :requests="scenario.requests" :open="select"/> <ms-api-request-config :requests="scenario.requests" :open="select"/>
</ms-api-collapse-item> </ms-api-collapse-item>
</ms-api-collapse> </ms-api-collapse>
</div> </div>
<el-button class="scenario-create" type="primary" size="mini" icon="el-icon-plus" plain @click="createScenario"/> <!-- 暂时去掉将来再-->
<!-- <el-button class="scenario-create" type="primary" size="mini" icon="el-icon-plus" plain @click="createScenario"/>-->
</el-aside> </el-aside>
<el-main class="scenario-main"> <el-main class="scenario-main">

View File

@ -0,0 +1,619 @@
let Xml4js = function (options = {}) {
this.depth = 0;
this.encoding = options.encoding || 'UTF-8';
this.xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
};
Xml4js.prototype = {
toString: function () {
return this.xml;
},
write: function () {
let context = this,
elem,
attr = null,
value = null,
callback = false,
fn = null,
hasValue = null,
empty = null;
elem = arguments[0];
if (elem === '<hashTree/>') {
this.xml += '<hashTree/>\n'
return;
}
if (typeof arguments[1] == 'object') {
attr = arguments[1];
} else if (typeof arguments[1] == 'function') {
callback = true;
fn = arguments[1];
} else {
value = arguments[1];
}
if (typeof arguments[2] == 'function') {
if (!callback) {
callback = true;
fn = arguments[2];
}
} else {
if (value === null) {
value = arguments[2];
}
}
hasValue = value !== null;
empty = !hasValue && !callback;
function indent(depth) {
if (depth == null)
return '';
let space = '';
for (let i = 0; i < depth; i++)
if (context.tabs)
space += "\t";
else
space += ' ';
return space;
}
if (elem === 'cdata') {
this.xml += indent(this.depth) + '<![CDATA[' + value + ']]>\n';
} else {
this.xml += indent(this.depth) + '<' + elem;
if (attr) {
for (let key in attr) {
if (attr.hasOwnProperty(key)) {
this.xml += ' ';
this.xml += key + '="' + attr[key] + '"';
}
}
}
if (value !== null)
this.xml += '>' + value + '</' + elem + '>\n';
if (callback) {
this.xml += '>\n'
this.depth++;
if (fn instanceof Function) {
fn();
}
this.depth--;
this.xml += indent(this.depth) + '</' + elem + '>\n'
}
if (empty)
this.xml += '/>\n';
}
}
};
/**
*
*JMX 构造对象
*/
let Jmx = function (data, name, ds) {
this.data = data;
this.name = name;
let domains = {};
ds.forEach(function (d) {
domains[d] = d;
});
this.domains = domains;
this.xml = new Xml4js();
};
Jmx.prototype = {
generate: function () {
generateXml(this.xml, this.preprocessing());
return this.xml.toString();
},
preprocessing: function () {
let domainAlias = {};
let index = 1;
Object.getOwnPropertyNames(this.domains).forEach(function (key) {
domainAlias[key] = "BASE_URL_" + index;
index = index + 1;
});
let UserAgent = null;
let hsps = [];
let domains = this.domains;
this.data.forEach(function (item) {
let url = new URL(item.url);
if (domains[url.hostname]) {
let hsp = new HTTPSamplerProxy(item.label.replace(/&/gi, "&amp;"));
hsp.stringProp("HTTPSampler.domain", "${" + domainAlias[url.hostname] + "}");
hsp.stringProp("HTTPSampler.protocol", url.protocol.split(":")[0]);
hsp.stringProp("HTTPSampler.path", url.pathname);
hsp.stringProp("HTTPSampler.method", item.method);
if (url.port === "") {
hsp.intProp("HTTPSampler.port", 0);
} else {
hsp.intProp("HTTPSampler.port", url.port);
}
hsp.addArguments(item.url, item.body);
hsps.push(hsp);
if (item.headers.length === 0) {
hsps.push("<hashTree/>");
} else {
let cphmh = new CollectionPropHeaderManagerHeaders();
item.headers.forEach(function (h) {
if (h.name === 'User-Agent') {
UserAgent = h.value;
} else {
cphmh.addValue(new elementPropHeaderManager(h.name, h.value));
}
});
// Add Header
let ephm = new HeaderManager();
ephm.addValue(cphmh);
let ht = new HashTree();
ht.addValue(ephm);
ht.addValue("<hashTree/>");
hsps.push(ht);
}
}
});
let jmeterTestPlan = new JmeterTestPlan();
let hashTree = new HashTree();
jmeterTestPlan.addValue(hashTree);
let testPlan = new TestPlan(this.name);
testPlan.boolProp("TestPlan.functional_mode", false);
testPlan.boolProp("TestPlan.serialize_threadgroups", false);
testPlan.boolProp("TestPlan.tearDown_on_shutdown", true);
testPlan.stringProp("TestPlan.comments", "");
testPlan.stringProp("TestPlan.user_define_classpath", "");
testPlan.addArguments();
hashTree.addValue(testPlan);
let hashTree1 = new HashTree();
hashTree.addValue(hashTree1);
//HeaderManager
let hm = new HeaderManager();
hm.userAgent(UserAgent);
hashTree1.addValue(hm);
hashTree1.addValue("<hashTree/>");
//Arguments
let arg = new Arguments();
arg.addArguments(domainAlias);
hashTree1.addValue(arg);
hashTree1.addValue("<hashTree/>");
//DNSCacheManager
let dns = new DNSCacheManager();
dns.init();
hashTree1.addValue(dns);
hashTree1.addValue("<hashTree/>");
//AuthManager
let auth = new AuthManager();
auth.init();
hashTree1.addValue(auth);
hashTree1.addValue("<hashTree/>");
//CookieManager
let cookie = new CookieManager();
cookie.init();
hashTree1.addValue(cookie);
hashTree1.addValue("<hashTree/>");
//CacheManager
let cache = new CacheManager();
cache.boolProp("clearEachIteration", true);
cache.boolProp("useExpires", false);
cache.boolProp("CacheManager.controlledByThread", false);
hashTree1.addValue(cache);
hashTree1.addValue("<hashTree/>");
let threadGroup = new ThreadGroup();
hashTree1.addValue(threadGroup);
threadGroup.intProp("ThreadGroup.num_threads", 1);
threadGroup.intProp("ThreadGroup.ramp_time", 1);
threadGroup.longProp("ThreadGroup.delay", 0);
threadGroup.longProp("ThreadGroup.duration", 0);
threadGroup.stringProp("ThreadGroup.on_sample_error", "continue");
threadGroup.boolProp("ThreadGroup.scheduler", false);
let lc = new LoopController();
threadGroup.addValue(lc);
lc.boolProp("LoopController.continue_forever", false);
lc.stringProp("LoopController.loops", 1);
let ht = new HashTree();
hashTree1.addValue(ht);
hsps.forEach(function (hsp) {
ht.addValue(hsp);
});
return jmeterTestPlan;
}
};
function generateXml(xml, hashTree) {
if (hashTree instanceof HashTree) {
if (hashTree.values.length > 0 && !(hashTree.values[0] instanceof HashTree)) {
xml.write(hashTree.element, hashTree.attributes, hashTree.values[0]);
} else {
xml.write(hashTree.element, hashTree.attributes, function () {
if (hashTree.values.length > 0) {
hashTree.values.forEach(function (v) {
generateXml(xml, v);
})
}
});
}
} else {
xml.write(hashTree);
}
}
/**
* HashTree 初始对象
*/
let HashTree = function (element, attributes, value) {
this.element = element || "hashTree";
this.attributes = attributes || {};
this.values = [];
if (value !== undefined) {
this.values.push(value);
}
};
HashTree.prototype.addValue = function (hashTree) {
this.values.push(hashTree)
};
HashTree.prototype.commonValue = function (element, name, value) {
this.values.push(new HashTree(element, {name: name}, value))
};
HashTree.prototype.intProp = function (name, value) {
this.commonValue("intProp", name, value);
};
HashTree.prototype.longProp = function (name, value) {
this.commonValue("longProp", name, value);
};
HashTree.prototype.stringProp = function (name, value) {
this.commonValue("stringProp", name, value);
};
HashTree.prototype.boolProp = function (name, value) {
this.commonValue("boolProp", name, value);
};
/**
* HashTree 的帮助对象
*/
let CHashTree = function (element, guiclass, testclass, testname, enabled) {
HashTree.call(this, element, {
guiclass: guiclass,
testclass: testclass,
testname: testname || "TEST",
enabled: enabled || "true"
});
};
CHashTree.prototype = new HashTree();
/**
* JmeterTestPlan
*
*/
let JmeterTestPlan = function (options = {}) {
HashTree.call(this, "jmeterTestPlan",
{
version: options.version || "1.2",
properties: options.properties || "5.0",
jmeter: options.jmeter || "5.2.1"
});
};
JmeterTestPlan.prototype = new HashTree();
/**
* TestPlan
*
*/
let TestPlan = function (name) {
CHashTree.call(this, "TestPlan", "TestPlanGui", "TestPlan", name);
};
TestPlan.prototype = new CHashTree();
TestPlan.prototype.addArguments = function () {
let ht = new HashTree("elementProp", {
name: "TestPlan.user_defined_variables",
elementType: "Arguments"
});
ht.addValue(new HashTree("collectionProp", {name: "Arguments.arguments"}));
this.values.push(ht);
};
/**
* HeaderManager
*
*/
let HeaderManager = function () {
CHashTree.call(this, "HeaderManager", "HeaderPanel", "HeaderManager", "HTTP Header manager");
};
HeaderManager.prototype = new CHashTree();
HeaderManager.prototype.userAgent = function (userAgent) {
let cp = new HashTree("collectionProp", {
name: "HeaderManager.headers",
});
let ep = new HashTree("elementProp", {
name: "User-Agent",
elementType: "Header"
});
ep.stringProp("Header.name", "User-Agent");
ep.stringProp("Header.value", userAgent);
cp.addValue(ep);
this.values.push(cp);
};
/**
* Arguments
*
*/
let Arguments = function () {
CHashTree.call(this, "Arguments", "ArgumentsPanel", "Arguments", "User Defined Variables");
};
Arguments.prototype = new CHashTree();
Arguments.prototype.addArguments = function (domianAlias) {
let cp = new HashTree("collectionProp", {name: "Arguments.arguments"});
if (domianAlias) {
Object.getOwnPropertyNames(domianAlias).forEach(function (key) {
cp.addValue(addArgumentsCommon(domianAlias[key], key, true, true));
});
}
this.values.push(cp);
};
/**
* DNSCacheManager
*
*/
let DNSCacheManager = function () {
CHashTree.call(this, "DNSCacheManager", "DNSCachePanel", "DNSCacheManager", "DNS Cache Manager");
};
DNSCacheManager.prototype = new CHashTree();
DNSCacheManager.prototype.init = function () {
let cp = new HashTree("collectionProp", {name: "DNSCacheManager.servers"});
this.values.push(cp);
this.boolProp("DNSCacheManager.clearEachIteration", true);
this.boolProp("DNSCacheManager.isCustomResolver", false);
};
/**
* AuthManager
*
*/
let AuthManager = function () {
CHashTree.call(this, "AuthManager", "AuthPanel", "AuthManager", "HTTP Authorization Manager");
};
AuthManager.prototype = new CHashTree();
AuthManager.prototype.init = function () {
let cp = new HashTree("collectionProp", {name: "AuthManager.auth_list"});
this.values.push(cp);
this.boolProp("AuthManager.controlledByThreadGroup", false);
};
/**
* CookieManager
*
*/
let CookieManager = function () {
CHashTree.call(this, "CookieManager", "CookiePanel", "CookieManager", "HTTP Cookie Manager");
};
CookieManager.prototype = new CHashTree();
CookieManager.prototype.init = function () {
let cp = new HashTree("collectionProp", {name: "CookieManager.cookies"});
this.values.push(cp);
this.boolProp("CookieManager.clearEachIteration", true);
this.boolProp("CookieManager.controlledByThreadGroup", false);
};
/**
* CacheManager
*
*/
let CacheManager = function () {
CHashTree.call(this, "CacheManager", "CacheManagerGui", "CacheManager", "HTTP Cache Manager");
};
CacheManager.prototype = new CHashTree();
/**
* ThreadGroup
*
*/
let ThreadGroup = function () {
CHashTree.call(this, "ThreadGroup", "ThreadGroupGui", "ThreadGroup", "Group1");
};
ThreadGroup.prototype = new CHashTree();
let LoopController = function () {
HashTree.call(this, "elementProp", {
name: "ThreadGroup.main_controller",
elementType: "LoopController",
guiclass: "LoopControlPanel",
testclass: "LoopController",
testname: "Loop Controller",
enabled: "true"
});
};
LoopController.prototype = new HashTree();
/**
* HTTPSamplerProxy
*
*/
let HTTPSamplerProxy = function (name) {
HashTree.call(this, "HTTPSamplerProxy", {
guiclass: "HttpTestSampleGui",
testclass: "HTTPSamplerProxy",
testname: name,
enabled: "true"
});
};
HTTPSamplerProxy.prototype = new HashTree();
HTTPSamplerProxy.prototype.addArguments = function (url, body) {
let ht = new HashTree("elementProp", {
name: "HTTPSampler.Arguments",
elementType: "Arguments",
guiclass: "HTTPArgumentsPanel",
testclass: "Arguments",
enabled: "true"
});
let cp = new HashTree("collectionProp", {name: "Arguments.arguments"});
ht.addValue(cp);
let params = getUrlParams(url);
params.forEach(function (item) {
cp.addValue(addArgumentsCommon(item.name, item.value, false));
});
if (body) {
this.boolProp("HTTPSampler.postBodyRaw", true);
if (body instanceof Array) {
cp.addValue(addArgumentsBody(body[0], true));
} else {
cp.addValue(addArgumentsBody(body, true));
}
}
this.values.push(ht);
};
function addArgumentsCommon(name, value, alwaysEncode, metadata) {
let ht = new HashTree("elementProp", {
name: name,
elementType: "HTTPArgument"
});
ht.boolProp("HTTPArgument.always_encode", alwaysEncode);
if (typeof (name) == 'string') {
ht.stringProp("Argument.name", name);
}
ht.stringProp("Argument.value", value);
if (!metadata) {
ht.stringProp("Argument.metadata", "=");
}
return ht;
}
function addArgumentsBody(value, alwaysEncode, metadata) {
let ht = new HashTree("elementProp", {
name: name,
elementType: "HTTPArgument"
});
ht.boolProp("HTTPArgument.always_encode", alwaysEncode);
ht.stringProp("Argument.value", value);
if (!metadata) {
ht.stringProp("Argument.metadata", "=");
}
return ht;
}
function getUrlParams(url) {
let params = [];
if (url.indexOf('?') === -1) {
return params;
}
let queryString = url.split('?')[1];
queryString = queryString.split('#')[0];
let arr = queryString.split('&');
arr.forEach(function (item) {
let a = item.split('=');
params.push({
name: a[0],
value: a[1]
});
});
return params;
}
let ElementPropHeaderManager = function () {
HashTree.call(this, "elementProp", {
name: "HTTPSampler.header_manager",
elementType: "HeaderManager"
});
};
ElementPropHeaderManager.prototype = new HashTree();
let CollectionPropHeaderManagerHeaders = function () {
HashTree.call(this, "collectionProp", {
name: "HeaderManager.headers"
});
};
CollectionPropHeaderManagerHeaders.prototype = new HashTree();
let elementPropHeaderManager = function (name, value) {
let ht = new HashTree("elementProp", {
name: name,
elementType: "Header"
});
ht.stringProp("Header.name", name);
ht.stringProp("Header.value", value);
return ht;
};
export default Jmx;

View File

@ -0,0 +1,95 @@
export const get = [{
"headers": [{"name": "Upgrade-Insecure-Requests", "value": "1"}, {
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}, {
"name": "Accept",
"value": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}],
"label": "https://www.baidu.com/",
"method": "GET",
"requestId": "21478",
"request_subtype": "",
"request_type": "top_level",
"tabId": 394,
"timestamp": 1587958164590,
"url": "https://www.baidu.com/"
}, {
"headers": [{"name": "Accept", "value": "application/json, text/javascript, */*; q=0.01"}, {
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}],
"label": "https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195&hisdata=&csor=0",
"method": "GET",
"requestId": "21522",
"request_subtype": "",
"request_type": "ajax",
"tabId": 394,
"timestamp": 1587958165726,
"url": "https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195&hisdata=&csor=0"
}, {
"headers": [{"name": "Accept", "value": "text/plain, */*; q=0.01"}, {
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}, {"name": "X-Requested-With", "value": "XMLHttpRequest"}],
"label": "https://www.baidu.com/home/xman/data/tipspluslist?indextype=manht&_req_seqid=0xacf4e73f00017936&asyn=1&t=1587958166015&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195",
"method": "GET",
"requestId": "21540",
"request_subtype": "",
"request_type": "ajax",
"tabId": 394,
"timestamp": 1587958166018,
"url": "https://www.baidu.com/home/xman/data/tipspluslist?indextype=manht&_req_seqid=0xacf4e73f00017936&asyn=1&t=1587958166015&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195"
}, {
"headers": [{"name": "Accept", "value": "text/plain, */*; q=0.01"}, {
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}, {"name": "X-Requested-With", "value": "XMLHttpRequest"}],
"label": "https://www.baidu.com/home/msg/data/personalcontent?num=8&indextype=manht&_req_seqid=0xacf4e73f00017936&asyn=1&t=1587958166028&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195",
"method": "GET",
"requestId": "21541",
"request_subtype": "",
"request_type": "ajax",
"tabId": 394,
"timestamp": 1587958166031,
"url": "https://www.baidu.com/home/msg/data/personalcontent?num=8&indextype=manht&_req_seqid=0xacf4e73f00017936&asyn=1&t=1587958166028&sid=1447_31124_21122_31424_31341_30903_31229_30824_26350_31164_31195"
}];
export const post = [{
"body": ["{\"id\":null,\"projectId\":\"e15d2d02-7404-485f-944b-2f2dbd456e3e\",\"name\":\"test second\",\"scenarioDefinition\":\"[{\\\"name\\\":null,\\\"url\\\":null,\\\"variables\\\":[],\\\"headers\\\":[],\\\"requests\\\":[{\\\"randomId\\\":2311,\\\"name\\\":null,\\\"url\\\":null,\\\"method\\\":\\\"GET\\\",\\\"parameters\\\":[],\\\"headers\\\":[],\\\"body\\\":{\\\"type\\\":null,\\\"text\\\":null,\\\"kvs\\\":[]},\\\"assertions\\\":{\\\"text\\\":[],\\\"regex\\\":[],\\\"responseTime\\\":{\\\"type\\\":\\\"RESPONSE_TIME\\\",\\\"responseInTime\\\":null}},\\\"extract\\\":[]}]}]\"}"],
"headers": [{"name": "Accept", "value": "application/json, text/plain, */*"}, {
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
}, {"name": "Content-Type", "value": "application/json;charset=UTF-8"}],
"label": "http://localhost:8080/api/save",
"method": "POST",
"requestId": "26129",
"request_subtype": "",
"request_type": "ajax",
"tabId": 466,
"timestamp": 1587968228917,
"url": "http://localhost:8080/api/save"
}]
export const scenario = [{
"name": "Scenario 1",
"url": null,
"variables": [],
"headers": [],
"requests": [{
"randomId": 6271,
"name": "Request 1",
"url": "https://www.baidu.com",
"method": "GET",
"parameters": [{"key": "flag", "value": "test"}],
"headers": [{"key": "test_header", "value": "test_heade_value"}],
"body": {"type": null, "text": null, "kvs": []},
"assertions": {
"text": [],
"regex": [{"type": "REGEX", "subject": "HTTP_CODE", "expression": "^200$", "description": "equals: 200"}],
"responseTime": {"type": "RESPONSE_TIME", "responseInTime": null}
},
"extract": []
}]
}]