refactor: 优化接口测试导入

This commit is contained in:
chenjianxing 2020-07-17 18:25:09 +08:00
parent d830cc85db
commit 985385aba2
15 changed files with 272 additions and 75 deletions

View File

@ -2,10 +2,7 @@ package io.metersphere.api.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.api.dto.APITestResult;
import io.metersphere.api.dto.DeleteAPITestRequest;
import io.metersphere.api.dto.QueryAPITestRequest;
import io.metersphere.api.dto.SaveAPITestRequest;
import io.metersphere.api.dto.*;
import io.metersphere.api.service.APITestService;
import io.metersphere.base.domain.ApiTest;
import io.metersphere.base.domain.Schedule;
@ -50,7 +47,6 @@ public class APITestController {
return apiTestService.getApiTestByProjectId(projectId);
}
@GetMapping("/state/get/{testId}")
public ApiTest apiState(@PathVariable String testId) {
return apiTestService.getApiTestByTestId(testId);
@ -96,10 +92,10 @@ public class APITestController {
return apiTestService.run(request);
}
@PostMapping("/import/{platform}")
@PostMapping(value = "/import", consumes = {"multipart/form-data"})
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public ApiTest testCaseImport(MultipartFile file, @PathVariable String platform) {
return apiTestService.apiTestImport(file, platform);
public ApiTest testCaseImport(@RequestPart(value = "file") MultipartFile file, @RequestPart("request") ApiTestImportRequest request) {
return apiTestService.apiTestImport(file, request);
}
}

View File

@ -0,0 +1,15 @@
package io.metersphere.api.dto;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class ApiTestImportRequest {
private String name;
private String environmentId;
private String projectId;
private String platform;
private Boolean useEnvironment;
private String swaggerUrl;
}

View File

@ -1,7 +1,9 @@
package io.metersphere.api.parse;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.scenario.KeyValue;
import io.metersphere.api.dto.scenario.Request;
import io.metersphere.api.dto.scenario.Scenario;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.LogUtil;
import org.apache.commons.lang3.StringUtils;
@ -42,6 +44,12 @@ public abstract class ApiImportAbstractParser implements ApiImportParser {
return testStr.toString();
}
protected void setScenarioByRequest(Scenario scenario, ApiTestImportRequest request) {
if (request.getUseEnvironment()) {
scenario.setEnvironmentId(request.getEnvironmentId());
}
}
protected void addContentType(Request request, String contentType) {
addHeader(request, HttpHeader.CONTENT_TYPE.toString(), contentType);
}

View File

@ -1,9 +1,10 @@
package io.metersphere.api.parse;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.parse.ApiImport;
import java.io.InputStream;
public interface ApiImportParser {
ApiImport parse(InputStream source);
ApiImport parse(InputStream source, ApiTestImportRequest request);
}

View File

@ -3,6 +3,7 @@ package io.metersphere.api.parse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.parse.ApiImport;
import io.metersphere.commons.constants.MsRequestBodyType;
import org.apache.commons.lang3.StringUtils;
@ -13,9 +14,13 @@ import java.io.InputStream;
public class MsParser extends ApiImportAbstractParser {
@Override
public ApiImport parse(InputStream source) {
public ApiImport parse(InputStream source, ApiTestImportRequest request) {
String testStr = getApiTestStr(source);
return JSON.parseObject(parsePluginFormat(testStr), ApiImport.class);
ApiImport apiImport = JSON.parseObject(parsePluginFormat(testStr), ApiImport.class);
apiImport.getScenarios().forEach(scenario -> {
setScenarioByRequest(scenario, request);
});
return apiImport;
}
private String parsePluginFormat(String testStr) {

View File

@ -2,6 +2,7 @@ package io.metersphere.api.parse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.parse.ApiImport;
import io.metersphere.api.dto.parse.postman.*;
import io.metersphere.api.dto.scenario.Body;
@ -32,7 +33,7 @@ public class PostmanParser extends ApiImportAbstractParser {
}
@Override
public ApiImport parse(InputStream source) {
public ApiImport parse(InputStream source, ApiTestImportRequest request) {
String testStr = getApiTestStr(source);
PostmanCollection postmanCollection = JSON.parseObject(testStr, PostmanCollection.class);
PostmanCollectionInfo info = postmanCollection.getInfo();
@ -42,6 +43,7 @@ public class PostmanParser extends ApiImportAbstractParser {
Scenario scenario = new Scenario();
scenario.setRequests(requests);
scenario.setName(info.getName());
setScenarioByRequest(scenario, request);
scenarios.add(scenario);
apiImport.setScenarios(scenarios);
return apiImport;

View File

@ -2,6 +2,7 @@ package io.metersphere.api.parse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.parse.ApiImport;
import io.metersphere.api.dto.scenario.Body;
import io.metersphere.api.dto.scenario.KeyValue;
@ -16,6 +17,7 @@ import io.swagger.models.properties.ObjectProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.util.*;
@ -23,12 +25,18 @@ import java.util.*;
public class Swagger2Parser extends ApiImportAbstractParser {
@Override
public ApiImport parse(InputStream source) {
String testStr = getApiTestStr(source);
// Swagger swagger = new SwaggerParser().read("http://petstore.swagger.io/v2/swagger.json");
Swagger swagger = new SwaggerParser().readWithInfo(testStr).getSwagger();
public ApiImport parse(InputStream source, ApiTestImportRequest request) {
Swagger swagger = null;
if (StringUtils.isNotBlank(request.getSwaggerUrl())) {
swagger = new SwaggerParser().read(request.getSwaggerUrl());
} else {
swagger = new SwaggerParser().readWithInfo(getApiTestStr(source)).getSwagger();
}
ApiImport apiImport = new ApiImport();
apiImport.setScenarios(parseRequests(swagger));
apiImport.getScenarios().forEach(scenario -> {
scenario.setEnvironmentId(request.getEnvironmentId());
});
return apiImport;
}

View File

@ -2,6 +2,7 @@ package io.metersphere.api.service;
import com.alibaba.fastjson.JSONObject;
import io.metersphere.api.dto.APITestResult;
import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.QueryAPITestRequest;
import io.metersphere.api.dto.SaveAPITestRequest;
import io.metersphere.api.dto.parse.ApiImport;
@ -75,7 +76,6 @@ public class APITestService {
if (files == null || files.isEmpty()) {
throw new IllegalArgumentException(Translator.get("file_cannot_be_null"));
}
checkNameExist(request);
ApiTest test = createTest(request);
saveFile(test.getId(), files);
}
@ -187,6 +187,7 @@ public class APITestService {
}
private ApiTest createTest(SaveAPITestRequest request) {
checkNameExist(request);
final ApiTest test = new ApiTest();
test.setId(request.getId());
test.setName(request.getName());
@ -256,23 +257,23 @@ public class APITestService {
scheduleService.addOrUpdateCronJob(request, ApiTestJob.getJobKey(request.getResourceId()), ApiTestJob.getTriggerKey(request.getResourceId()), ApiTestJob.class);
}
public ApiTest apiTestImport(MultipartFile file, String platform) {
ApiImportParser apiImportParser = ApiImportParserFactory.getApiImportParser(platform);
public ApiTest apiTestImport(MultipartFile file, ApiTestImportRequest request) {
ApiImportParser apiImportParser = ApiImportParserFactory.getApiImportParser(request.getPlatform());
ApiImport apiImport = null;
try {
apiImport = apiImportParser.parse(file.getInputStream());
apiImport = apiImportParser.parse(file.getInputStream(), request);
} catch (Exception e) {
LogUtil.error(e.getMessage(), e);
MSException.throwException(Translator.get("parse_data_error"));
}
SaveAPITestRequest request = getImportApiTest(file, apiImport);
return createTest(request);
SaveAPITestRequest saveRequest = getImportApiTest(request, apiImport);
return createTest(saveRequest);
}
private SaveAPITestRequest getImportApiTest(MultipartFile file, ApiImport apiImport) {
private SaveAPITestRequest getImportApiTest(ApiTestImportRequest importRequest, ApiImport apiImport) {
SaveAPITestRequest request = new SaveAPITestRequest();
request.setName(file.getOriginalFilename());
request.setProjectId("");
request.setName(importRequest.getName());
request.setProjectId(importRequest.getProjectId());
request.setScenarioDefinition(apiImport.getScenarios());
request.setUserId(SessionUtils.getUserId());
request.setId(UUID.randomUUID().toString());

View File

@ -1,5 +1,5 @@
<template>
<el-dialog :title="$t('api_test.environment.environment_config')" :visible.sync="visible" class="environment-dialog" @close="close">
<el-dialog :title="$t('api_test.environment.environment_config')" :visible.sync="visible" class="environment-dialog" @close="close" :modal="false">
<el-container v-loading="result.loading">
<ms-aside-item :title="$t('api_test.environment.environment_list')" :data="environments" :item-operators="environmentOperators" :add-fuc="addEnvironment"
:delete-fuc="deleteEnvironment" @itemSelected="environmentSelected" ref="environmentItems"/>

View File

@ -1,28 +1,69 @@
<template>
<el-dialog :title="$t('api_test.api_import.title')" :visible.sync="visible" class="api-import" v-loading="result.loading">
<el-dialog :title="$t('api_test.api_import.title')" :visible.sync="visible" class="api-import" v-loading="result.loading" @close="close">
<div class="data-format">
<div class="header-bar">
<div>{{$t('api_test.api_import.data_format')}}</div>
<el-radio-group v-model="selectedPlatformValue">
<el-radio v-for="(item, index) in platforms" :key="index" :label="item.value">{{item.name}}</el-radio>
</el-radio-group>
<div class="operate-button">
<el-button class="save-button" type="primary" plain @click="save">
{{$t('commons.save')}}
</el-button>
<el-button class="cancel-button" type="warning" plain @click="visible = false">
{{$t('commons.cancel')}}
</el-button>
</div>
</div>
<div class="api-upload">
<el-upload
drag
action=""
:http-request="upload"
:limit="1"
:beforeUpload="uploadValidate"
:show-file-list="false"
:file-list="fileList"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text" v-html="$t('load_test.upload_tips')"></div>
<div class="el-upload__tip" slot="tip">{{$t('api_test.api_import.file_size_limit')}}</div>
</el-upload>
</div>
<el-form :model="formData" :rules="rules" label-width="100px" v-loading="result.loading" ref="form">
<el-row>
<el-col :span="11">
<el-form-item :label="$t('commons.name')" prop="name">
<el-input size="small" class="name-input" v-model="formData.name" clearable show-word-limit/>
</el-form-item>
<el-form-item :label="$t('commons.project')" prop="projectId">
<el-select size="small" v-model="formData.projectId" class="project-select" clearable>
<el-option v-for="(project, index) in projects" :key="index" :label="project.name" :value="project.id"/>
</el-select>
</el-form-item>
<el-form-item v-if="(selectedPlatformValue != 'Postman' && useEnvironment) || selectedPlatformValue == 'Swagger2'" :label="$t('api_test.environment.environment_config')" prop="environmentId">
<el-select size="small" v-model="formData.environmentId" class="environment-select" clearable>
<el-option v-for="(environment, index) in environments" :key="index" :label="environment.name + ': ' + environment.protocol + '://' + environment.socket" :value="environment.id"/>
<el-button class="environment-button" size="mini" type="primary" @click="openEnvironmentConfig">{{$t('api_test.environment.environment_config')}}</el-button>
<template v-slot:empty>
<div class="empty-environment">
<el-button :disabled="formData.projectId == ''" class="environment-button" size="mini" type="primary" @click="openEnvironmentConfig">{{$t('api_test.environment.environment_config')}}</el-button>
</div>
</template>
</el-select>
</el-form-item>
<el-form-item v-if="selectedPlatformValue == 'Metersphere'" prop="useEnvironment">
<el-checkbox v-model="useEnvironment">{{$t('api_test.environment.config_environment')}}</el-checkbox>
</el-form-item>
</el-col>
<el-col :span="1">
<el-divider direction="vertical"/>
</el-col>
<el-col :span="12">
<el-form-item prop="file" class="api-upload">
<el-upload
drag
action=""
:http-request="upload"
:limit="1"
:beforeUpload="uploadValidate"
:file-list="fileList"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text" v-html="$t('load_test.upload_tips')"></div>
<div class="el-upload__tip" slot="tip">{{$t('api_test.api_import.file_size_limit')}}</div>
</el-upload>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div class="format-tip">
<div>
@ -33,14 +74,17 @@
</div>
</div>
<api-environment-config ref="environmentConfig" @close="getEnvironments"/>
</el-dialog>
</template>
<script>
import MsDialogFooter from "../../../../common/components/MsDialogFooter";
import ApiEnvironmentConfig from "../ApiEnvironmentConfig";
export default {
name: "ApiImport",
components: {MsDialogFooter},
components: {ApiEnvironmentConfig, MsDialogFooter},
data() {
return {
visible: false,
@ -69,12 +113,37 @@
],
selectedPlatform: {},
selectedPlatformValue: 'Metersphere',
fileList: [],
result: {},
projects: [],
environments: [],
useEnvironment: false,
formData: {
name: '',
environmentId: '',
projectId: '',
file: undefined
},
rules: {
name: [
{required: true, message: this.$t('commons.input_name'), trigger: 'blur'},
{max: 60, message: this.$t('commons.input_limit', [1, 60]), trigger: 'blur'}
],
environmentId: [
{required: true, message: this.$t('api_test.environment.select_environment'), trigger: 'blur'},
],
projectId: [
{required: true, message: this.$t('api_test.select_project'), trigger: 'blur'},
],
file: [
{required: true, message: this.$t('commons.please_upload'), trigger: 'blur'},
],
},
fileList: []
}
},
created() {
this.selectedPlatform = this.platforms[0];
this.getProjects();
},
watch: {
selectedPlatformValue() {
@ -84,6 +153,9 @@
break;
}
}
},
'formData.projectId'() {
this.getEnvironments();
}
},
methods: {
@ -91,14 +163,8 @@
this.visible = true;
},
upload(file) {
this.formData.file = file.file;
this.fileList.push(file.file);
this.result = this.$fileUpload('/api/import/' + this.selectedPlatformValue, this.fileList, response => {
let res = response.data;
this.$success(this.$t('test_track.case.import.success'));
this.visible = false;
this.$router.push({path: '/api/test/edit', query: {id: res.id}});
});
this.fileList = [];
},
uploadValidate(file, fileList) {
let suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
@ -112,6 +178,55 @@
return false;
}
return true;
},
getEnvironments() {
if (this.formData.projectId) {
this.$get('/api/environment/list/' + this.formData.projectId, response => {
this.environments = response.data;
});
} else {
this.environments = [];
this.formData.environmentId = '';
}
},
getProjects() {
this.result = this.$get("/project/listAll", response => {
this.projects = response.data;
})
},
openEnvironmentConfig() {
if (!this.formData.projectId) {
this.$error(this.$t('api_test.select_project'));
return;
}
this.$refs.environmentConfig.open(this.formData.projectId);
},
save() {
this.$refs.form.validate(valid => {
if (valid) {
let param = {};
Object.assign(param, this.formData);
param.platform = this.selectedPlatformValue;
param.useEnvironment = this.useEnvironment;
this.result = this.$fileUpload('/api/import', param.file, param,response => {
let res = response.data;
this.$success(this.$t('test_track.case.import.success'));
this.visible = false;
this.$router.push({path: '/api/test/edit', query: {id: res.id}});
});
} else {
return false;
}
});
},
close() {
this.formData = {
name: '',
environmentId: '',
projectId: '',
file: undefined
};
this.fileList = [];
}
}
}
@ -125,21 +240,59 @@
.api-upload {
text-align: center;
display: inline-block;
}
.el-radio-group {
margin: 10px 0;
}
.data-format,.format-tip,.api-upload {
.header-bar,.format-tip,.el-form {
border: solid #E1E1E1 1px;
margin: 10px 0;
padding: 10px;
border-radius: 3px;
}
.header-bar {
padding: 10px 30px;
}
.api-import >>> .el-dialog__body {
padding: 15px 25px;
}
.operate-button {
float: right;
}
.save-button {
margin-left: 10px;
}
.environment-button {
margin-left: 20px;
padding: 7px;
}
.empty-environment {
padding: 10px 0px;
}
.el-form {
padding: 30px 10px;
}
.el-divider {
height: 200px;
}
.name-input {
width: 195px;
}
.dialog-footer {
float: right;
}
</style>

View File

@ -98,7 +98,7 @@
upload(file) {
this.isLoading = false;
this.fileList.push(file.file);
this.result = this.$fileUpload('/test/case/import/' + this.projectId, this.fileList,response => {
this.result = this.$fileUpload('/test/case/import/' + this.projectId, file.file, {}, response => {
let res = response.data;
if (res.success) {
this.$success(this.$t('test_track.case.import.success'));

View File

@ -95,7 +95,7 @@ export default {
}
};
Vue.prototype.$request = function (axiosRequestConfig, success) {
Vue.prototype.$request = function (axiosRequestConfig, success, failure) {
let result = {loading: true};
if (!success) {
return axios.request(axiosRequestConfig);
@ -104,6 +104,9 @@ export default {
then(success, response, result);
}).catch(error => {
exception(error, result);
if (failure) {
then(failure, error, result);
}
});
return result;
}
@ -125,24 +128,20 @@ export default {
});
};
Vue.prototype.$fileUpload = function(url, fileList, success, failure) {
let result = {loading: true};
Vue.prototype.$fileUpload = function(url, file, param, success, failure) {
let formData = new FormData();
if (fileList.length > 0) {
fileList.forEach(f => {
formData.append("file", f);
});
}
axios.post(url, formData, { headers: { "Content-Type": "multipart/form-data" }})
.then(response => {
then(success, response, result);
}).catch(error => {
exception(error, result);
if (failure) {
then(failure, error, result);
formData.append("file", file);
formData.append('request', new Blob([JSON.stringify(param)], {type: "application/json"}));
let axiosRequestConfig = {
method: 'POST',
url: url,
data: formData,
headers: {
'Content-Type': undefined
}
});
return result;
};
return Vue.prototype.$request(axiosRequestConfig, success, failure);
}
}
}

View File

@ -104,6 +104,7 @@ export default {
input_name: 'Please enter name',
formatErr: 'Format Error',
id: 'ID',
please_upload: 'Please upload file',
date: {
select_date: 'Select date',
start_date: 'Start date',
@ -327,20 +328,22 @@ export default {
running: "Running",
reset: "Rest",
input_name: "Please enter the test name",
select_project: "Select project",
select_project: "Please select project",
variable_name: "Variable name",
copied: "copied",
key: "Key",
value: "Value",
create_performance_test: "Create Performance Test",
export_config: "Export Configuration",
export_config: "Export",
environment: {
name: "Environment Name",
socket: "Socket",
globalVariable: "Global Variable",
environment_list: "Environment List",
environment_config: "Environment Config",
config_environment: "Config Environment",
environment: "Environment",
select_environment: "Please select environment",
please_save_test: "Please Save Test First",
},
scenario: {

View File

@ -102,6 +102,7 @@ export default {
login_username: 'ID 或 邮箱',
input_login_username: '请输入用户 ID 或 邮箱',
input_name: '请输入名称',
please_upload: '请上传文件',
formatErr: '格式错误',
id: 'ID',
date: {
@ -332,14 +333,16 @@ export default {
key: "键",
value: "值",
create_performance_test: "创建性能测试",
export_config: "导出配置",
export_config: "导出",
environment: {
name: "环境名称",
socket: "环境域名",
globalVariable: "全局变量",
environment_list: "环境列表",
environment_config: "环境配置",
config_environment: "配置环境",
environment: "环境",
select_environment: "请选择环境",
please_save_test: "请先保存测试",
},
scenario: {

View File

@ -102,6 +102,7 @@ export default {
input_name: '請輸入名稱',
formatErr: '格式錯誤',
id: 'ID',
please_upload: '請上傳文件',
date: {
select_date: '選擇日期',
start_date: '開始日期',
@ -331,14 +332,16 @@ export default {
key: "鍵",
value: "值",
create_performance_test: "創建性能測試",
export_config: "匯出配寘",
export_config: "匯出",
environment: {
name: "環境名稱",
socket: "環境域名",
globalVariable: "全局變量",
environment_list: "環境列表",
environment_config: "環境配置",
config_environment: "配置環境",
environment: "環境",
select_environment: "請選擇環境",
please_save_test: "請先保存測試",
},
scenario: {