fix(接口测试): 修复接口用例转性能的时候关联文件找不到的问题

修复接口用例转性能的时候关联文件找不到的问题
This commit is contained in:
song-tianyang 2023-01-05 19:02:41 +08:00 committed by 建国
parent e9a8bc3527
commit e48580810a
2 changed files with 400 additions and 258 deletions

View File

@ -4,12 +4,14 @@ import io.metersphere.api.dto.JmxInfoDTO;
import io.metersphere.api.dto.definition.RunDefinitionRequest; import io.metersphere.api.dto.definition.RunDefinitionRequest;
import io.metersphere.api.dto.definition.request.ParameterConfig; import io.metersphere.api.dto.definition.request.ParameterConfig;
import io.metersphere.api.dto.scenario.environment.EnvironmentConfig; import io.metersphere.api.dto.scenario.environment.EnvironmentConfig;
import io.metersphere.api.exec.engine.EngineSourceParserFactory;
import io.metersphere.base.domain.ApiTestEnvironmentWithBLOBs; import io.metersphere.base.domain.ApiTestEnvironmentWithBLOBs;
import io.metersphere.base.domain.FileMetadata; import io.metersphere.base.domain.FileMetadata;
import io.metersphere.base.mapper.FileMetadataMapper;
import io.metersphere.commons.constants.ElementConstants; import io.metersphere.commons.constants.ElementConstants;
import io.metersphere.environment.service.BaseEnvironmentService; import io.metersphere.environment.service.BaseEnvironmentService;
import io.metersphere.metadata.service.FileMetadataService; import io.metersphere.metadata.service.FileMetadataService;
import io.metersphere.api.exec.engine.EngineSourceParserFactory; import io.metersphere.request.BodyFile;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.jorphan.collections.HashTree; import org.apache.jorphan.collections.HashTree;
@ -21,10 +23,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DataFormattingUtil { public class DataFormattingUtil {
@ -111,6 +110,7 @@ public class DataFormattingUtil {
} }
} }
} catch (Exception e) { } catch (Exception e) {
LogUtil.error("获取CSV文件异常!", e);
} }
} else if (StringUtils.equals(qname, ElementConstants.HTTP_SAMPLER)) { } else if (StringUtils.equals(qname, ElementConstants.HTTP_SAMPLER)) {
List<Element> elementPropElementList = parentElement.elements("elementProp"); List<Element> elementPropElementList = parentElement.elements("elementProp");
@ -188,9 +188,22 @@ public class DataFormattingUtil {
config.setConfig(envConfig); config.setConfig(envConfig);
} }
HashTree hashTree = runRequest.getTestElement().generateHashTree(config); HashTree hashTree = runRequest.getTestElement().generateHashTree(config);
List<BodyFile> files = new LinkedList<>();
ApiFileUtil.getFiles(hashTree, files);
String jmxString = runRequest.getTestElement().getJmx(hashTree); String jmxString = runRequest.getTestElement().getJmx(hashTree);
//将jmx处理封装为通用方法 //将jmx处理封装为通用方法
JmxInfoDTO dto = updateJmxString(jmxString, true); JmxInfoDTO dto = updateJmxString(jmxString, true);
FileMetadataMapper fileMetadataMapper = CommonBeanFactory.getBean(FileMetadataMapper.class);
if (fileMetadataMapper != null && CollectionUtils.isNotEmpty(files)) {
for (BodyFile file : files) {
if (StringUtils.isNotBlank(file.getFileId()) && file.isRef()) {
FileMetadata fileMetadata = fileMetadataMapper.selectByPrimaryKey(file.getFileId());
if (fileMetadata != null && !dto.getAttachFiles().containsKey(fileMetadata.getId())) {
dto.getAttachFiles().put(fileMetadata.getId(), fileMetadata.getName());
}
}
}
}
dto.setName(runRequest.getName() + ".jmx"); dto.setName(runRequest.getName() + ".jmx");
return dto; return dto;
} }

View File

@ -6,77 +6,173 @@
<el-col :span="12"> <el-col :span="12">
<el-form :inline="true"> <el-form :inline="true">
<el-form-item :label="$t('load_test.name')"> <el-form-item :label="$t('load_test.name')">
<el-input :disabled="isReadOnly" :placeholder="$t('load_test.input_name')" v-model="test.name" <el-input
:disabled="isReadOnly"
:placeholder="$t('load_test.input_name')"
v-model="test.name"
class="input-with-select" class="input-with-select"
size="small" size="small"
maxlength="255" show-word-limit/> maxlength="255"
show-word-limit
/>
</el-form-item> </el-form-item>
</el-form> </el-form>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-tooltip :content="$t('commons.follow')" placement="bottom" effect="dark" v-if="!showFollow"> <el-tooltip
<i class="el-icon-star-off" :content="$t('commons.follow')"
style="color: #783987; font-size: 25px; margin-right: 15px;cursor: pointer;position: relative; top: 5px; " placement="bottom"
@click="saveFollow"/> effect="dark"
v-if="!showFollow"
>
<i
class="el-icon-star-off"
style="
color: #783987;
font-size: 25px;
margin-right: 15px;
cursor: pointer;
position: relative;
top: 5px;
"
@click="saveFollow"
/>
</el-tooltip> </el-tooltip>
<el-tooltip :content="$t('commons.cancel')" placement="bottom" effect="dark" v-if="showFollow"> <el-tooltip
<i class="el-icon-star-on" :content="$t('commons.cancel')"
style="color: #783987; font-size: 28px; margin-right: 15px;cursor: pointer;position: relative; top: 5px; " placement="bottom"
@click="saveFollow"/> effect="dark"
v-if="showFollow"
>
<i
class="el-icon-star-on"
style="
color: #783987;
font-size: 28px;
margin-right: 15px;
cursor: pointer;
position: relative;
top: 5px;
"
@click="saveFollow"
/>
</el-tooltip> </el-tooltip>
<el-link type="primary" size="small" style="margin-right: 5px" @click="openHis" v-if="test.id"> <el-link
{{ $t('operating_log.change_history') }} type="primary"
size="small"
style="margin-right: 5px"
@click="openHis"
v-if="test.id"
>
{{ $t("operating_log.change_history") }}
</el-link> </el-link>
<mx-version-history v-xpack <mx-version-history
v-xpack
ref="versionHistory" ref="versionHistory"
:version-data="versionData" :version-data="versionData"
:current-id="testId" :current-id="testId"
:is-read="isReadOnly" :is-read="isReadOnly"
:has-latest="hasLatest" :has-latest="hasLatest"
@setLatest="setLatest" @setLatest="setLatest"
@compare="compare" @checkout="checkout" @create="create" @del="del"/> @compare="compare"
<el-button :disabled="isReadOnly" type="primary" size="small" plain @click="save" @checkout="checkout"
@create="create"
@del="del"
/>
<el-button
:disabled="isReadOnly"
type="primary"
size="small"
plain
@click="save"
v-permission="['PROJECT_PERFORMANCE_TEST:READ+EDIT']" v-permission="['PROJECT_PERFORMANCE_TEST:READ+EDIT']"
>{{ $t('commons.save') }} >{{ $t("commons.save") }}
</el-button> </el-button>
<el-button :disabled="isReadOnly" size="small" type="primary" plain @click="saveAndRun" <el-button
v-permission="['PROJECT_PERFORMANCE_TEST:READ+RUN']"> :disabled="isReadOnly"
{{ $t('load_test.save_and_run') }} size="small"
type="primary"
plain
@click="saveAndRun"
v-permission="['PROJECT_PERFORMANCE_TEST:READ+RUN']"
>
{{ $t("load_test.save_and_run") }}
</el-button> </el-button>
<el-button :disabled="isReadOnly" size="small" type="warning" plain @click="cancel"> <el-button
{{ $t('commons.cancel') }} :disabled="isReadOnly"
size="small"
type="warning"
plain
@click="cancel"
>
{{ $t("commons.cancel") }}
</el-button> </el-button>
<schedule-config :schedule="test.schedule" :save="saveCronExpression" @scheduleChange="saveSchedule" <schedule-config
:schedule="test.schedule"
:save="saveCronExpression"
@scheduleChange="saveSchedule"
v-if="hasPermission('PROJECT_PERFORMANCE_TEST:READ+SCHEDULE')" v-if="hasPermission('PROJECT_PERFORMANCE_TEST:READ+SCHEDULE')"
:check-open="checkScheduleEdit" :test-id="testId" :custom-validate="durationValidate"/> :check-open="checkScheduleEdit"
:test-id="testId"
:custom-validate="durationValidate"
/>
<ms-tip-button v-if="test.isNeedUpdate && hasPermission('PROJECT_PERFORMANCE_TEST:READ+EDIT')" <ms-tip-button
class="sync-btn" type="primary" size="small" circle v-if="
test.isNeedUpdate &&
hasPermission('PROJECT_PERFORMANCE_TEST:READ+EDIT')
"
class="sync-btn"
type="primary"
size="small"
circle
icon="el-icon-connection" icon="el-icon-connection"
@click="syncScenario" @click="syncScenario"
:plain="!test.isNeedUpdate" :plain="!test.isNeedUpdate"
:disabled="!test.isNeedUpdate" :disabled="!test.isNeedUpdate"
:tip="'同步场景测试最新变更'"/> :tip="'同步场景测试最新变更'"
/>
</el-col> </el-col>
</el-row> </el-row>
<el-tabs v-model="active" @tab-click="clickTab"> <el-tabs v-model="active" @tab-click="clickTab">
<el-tab-pane :label="$t('load_test.basic_config')" class="advanced-config"> <el-tab-pane
<performance-basic-config :is-read-only="isReadOnly" :test="test" ref="basicConfig" :label="$t('load_test.basic_config')"
class="advanced-config"
>
<performance-basic-config
:is-read-only="isReadOnly"
:test="test"
ref="basicConfig"
@tgTypeChange="tgTypeChange" @tgTypeChange="tgTypeChange"
@fileChange="fileChange"/>
</el-tab-pane>
<el-tab-pane :label="$t('load_test.pressure_config')" class="advanced-config">
<performance-pressure-config :is-read-only="isReadOnly" :test="test" :test-id="testId"
@fileChange="fileChange" @fileChange="fileChange"
ref="pressureConfig" @changeActive="changeTabActive"/> />
</el-tab-pane> </el-tab-pane>
<el-tab-pane :label="$t('load_test.advanced_config')" class="advanced-config"> <el-tab-pane
<performance-advanced-config :read-only="isReadOnly" :test-id="testId" ref="advancedConfig"/> :label="$t('load_test.pressure_config')"
class="advanced-config"
>
<performance-pressure-config
:is-read-only="isReadOnly"
:test="test"
:test-id="testId"
@fileChange="fileChange"
ref="pressureConfig"
@changeActive="changeTabActive"
/>
</el-tab-pane>
<el-tab-pane
:label="$t('load_test.advanced_config')"
class="advanced-config"
>
<performance-advanced-config
:read-only="isReadOnly"
:test-id="testId"
ref="advancedConfig"
/>
</el-tab-pane> </el-tab-pane>
</el-tabs> </el-tabs>
</el-card> </el-card>
@ -89,10 +185,14 @@
:destroy-on-close="true" :destroy-on-close="true"
width="100%" width="100%"
> >
<diff-version v-if="dialogVisible" :old-data="oldData" :show-follow="showFollow" :new-data="newData" <diff-version
:new-show-follow="newShowFollow"></diff-version> v-if="dialogVisible"
:old-data="oldData"
:show-follow="showFollow"
:new-data="newData"
:new-show-follow="newShowFollow"
></diff-version>
</el-dialog> </el-dialog>
</ms-main-container> </ms-main-container>
</ms-container> </ms-container>
</template> </template>
@ -103,8 +203,15 @@ import PerformancePressureConfig from "./components/PerformancePressureConfig";
import PerformanceAdvancedConfig from "./components/PerformanceAdvancedConfig"; import PerformanceAdvancedConfig from "./components/PerformanceAdvancedConfig";
import MsContainer from "metersphere-frontend/src/components/MsContainer"; import MsContainer from "metersphere-frontend/src/components/MsContainer";
import MsMainContainer from "metersphere-frontend/src/components/MsMainContainer"; import MsMainContainer from "metersphere-frontend/src/components/MsMainContainer";
import {getCurrentProjectID, getCurrentUser, getCurrentWorkspaceId} from "metersphere-frontend/src/utils/token"; import {
import {hasLicense, hasPermission} from "metersphere-frontend/src/utils/permission"; getCurrentProjectID,
getCurrentUser,
getCurrentWorkspaceId,
} from "metersphere-frontend/src/utils/token";
import {
hasLicense,
hasPermission,
} from "metersphere-frontend/src/utils/permission";
import ScheduleConfig from "./components/ScheduleConfig"; import ScheduleConfig from "./components/ScheduleConfig";
import MsChangeHistory from "metersphere-frontend/src/components/history/ChangeHistory"; import MsChangeHistory from "metersphere-frontend/src/components/history/ChangeHistory";
import MsTableOperatorButton from "metersphere-frontend/src/components/MsTableOperatorButton"; import MsTableOperatorButton from "metersphere-frontend/src/components/MsTableOperatorButton";
@ -123,9 +230,12 @@ import {
saveFollows, saveFollows,
saveSchedule, saveSchedule,
saveTest, saveTest,
syncScenario syncScenario,
} from "@/api/performance"; } from "@/api/performance";
import {getDefaultVersion, setLatestVersionById} from 'metersphere-frontend/src/api/version'; import {
getDefaultVersion,
setLatestVersionById,
} from "metersphere-frontend/src/api/version";
export default { export default {
name: "EditPerformanceTest", name: "EditPerformanceTest",
@ -140,11 +250,9 @@ export default {
MsMainContainer, MsMainContainer,
MsChangeHistory, MsChangeHistory,
DiffVersion, DiffVersion,
MxVersionHistory MxVersionHistory,
}, },
inject: [ inject: ["reload"],
'reload'
],
data() { data() {
return { return {
dialogVisible: false, dialogVisible: false,
@ -156,60 +264,63 @@ export default {
savePath: "/performance/save", savePath: "/performance/save",
editPath: "/performance/edit", editPath: "/performance/edit",
projects: [], projects: [],
active: '0', active: "0",
testId: '', testId: "",
isReadOnly: false, isReadOnly: false,
showFollow: false, showFollow: false,
tabs: [{ tabs: [
title: this.$t('load_test.basic_config'), {
id: '0', title: this.$t("load_test.basic_config"),
component: 'PerformanceBasicConfig' id: "0",
}, { component: "PerformanceBasicConfig",
title: this.$t('load_test.pressure_config'), },
id: '1', {
component: 'PerformancePressureConfig' title: this.$t("load_test.pressure_config"),
}, { id: "1",
title: this.$t('load_test.advanced_config'), component: "PerformancePressureConfig",
id: '2', },
component: 'PerformanceAdvancedConfig' {
}], title: this.$t("load_test.advanced_config"),
id: "2",
component: "PerformanceAdvancedConfig",
},
],
maintainerOptions: [], maintainerOptions: [],
versionData: [], versionData: [],
projectEnvMap: {}, projectEnvMap: {},
latestVersionId: '', latestVersionId: "",
hasLatest: false hasLatest: false,
}; };
}, },
watch: { watch: {
'$route'(to) { $route(to) {
// //
if (to.path.startsWith('/performance/test/create')) { if (to.path.startsWith("/performance/test/create")) {
this.reload(); this.reload();
} }
if (!to.path.startsWith('/performance/test/edit')) { if (!to.path.startsWith("/performance/test/edit")) {
return; return;
} }
this.reload(); this.reload();
this.isReadOnly = false; this.isReadOnly = false;
this.getTest(to.params.testId); this.getTest(to.params.testId);
} },
}, },
created() { created() {
let projectId = this.$route.query.projectId; let projectId = this.$route.query.projectId;
if (projectId && projectId !== getCurrentProjectID()) { if (projectId && projectId !== getCurrentProjectID()) {
sessionStorage.setItem(PROJECT_ID, projectId); sessionStorage.setItem(PROJECT_ID, projectId);
} }
this.isReadOnly = !hasPermission('PROJECT_PERFORMANCE_TEST:READ+EDIT'); this.isReadOnly = !hasPermission("PROJECT_PERFORMANCE_TEST:READ+EDIT");
this.getTest(this.$route.params.testId); this.getTest(this.$route.params.testId);
if (hasLicense()) { if (hasLicense()) {
this.getDefaultVersion(); this.getDefaultVersion();
} }
this.$EventBus.$on('projectChange', this.handleProjectChange); this.$EventBus.$on("projectChange", this.handleProjectChange);
}, },
destroyed() { destroyed() {
this.$EventBus.$off('projectChange', this.handleProjectChange); this.$EventBus.$off("projectChange", this.handleProjectChange);
}, },
mounted() { mounted() {
// todo // todo
@ -222,17 +333,21 @@ export default {
return getCurrentUser(); return getCurrentUser();
}, },
getMaintainerOptions() { getMaintainerOptions() {
getProjectUsers() getProjectUsers().then((res) => {
.then(res => {
this.maintainerOptions = res.data; this.maintainerOptions = res.data;
}); });
}, },
openHis() { openHis() {
this.$refs.changeHistory.open(this.test.id, ["性能测试", "性能測試", "Performance test", "PERFORMANCE_TEST"]); this.$refs.changeHistory.open(this.test.id, [
"性能测试",
"性能測試",
"Performance test",
"PERFORMANCE_TEST",
]);
}, },
importAPITest() { importAPITest() {
// sessionStorage // sessionStorage
let apiTest = JSON.parse(sessionStorage.getItem('LOAD_TEST'))?.test; let apiTest = JSON.parse(sessionStorage.getItem("LOAD_TEST"))?.test;
if (apiTest && apiTest.name) { if (apiTest && apiTest.name) {
this.$set(this.test, "name", apiTest.name); this.$set(this.test, "name", apiTest.name);
if (apiTest.jmx.projectEnvMap) { if (apiTest.jmx.projectEnvMap) {
@ -245,7 +360,7 @@ export default {
relateApiList.push({ relateApiList.push({
apiId: apiTest.jmx.scenarioId, apiId: apiTest.jmx.scenarioId,
apiVersion: apiTest.jmx.version, apiVersion: apiTest.jmx.version,
type: 'SCENARIO' type: "SCENARIO",
}); });
this.$set(this.test, "apiList", relateApiList); this.$set(this.test, "apiList", relateApiList);
} }
@ -256,7 +371,7 @@ export default {
apiId: apiTest.jmx.caseId, apiId: apiTest.jmx.caseId,
apiVersion: apiTest.jmx.version, apiVersion: apiTest.jmx.version,
envId: apiTest.jmx.envId, envId: apiTest.jmx.envId,
type: 'API_CASE' type: "API_CASE",
}); });
this.$set(this.test, "apiList", relateApiList); this.$set(this.test, "apiList", relateApiList);
} }
@ -265,12 +380,17 @@ export default {
for (let fileID in apiTest.jmx.attachFiles) { for (let fileID in apiTest.jmx.attachFiles) {
attachFiles.push(fileID); attachFiles.push(fileID);
} }
if (attachFiles.length > 0) {
this.$refs.basicConfig.selectAttachFileById(attachFiles);
} }
this.active = '1'; }
sessionStorage.removeItem('LOAD_TEST'); this.active = "1";
sessionStorage.removeItem("LOAD_TEST");
} else { } else {
// sessionStorage // sessionStorage
let scenarioJmxs = JSON.parse(sessionStorage.getItem('LOAD_TEST'))?.scenarioJmxs; let scenarioJmxs = JSON.parse(
sessionStorage.getItem("LOAD_TEST")
)?.scenarioJmxs;
if (scenarioJmxs && scenarioJmxs.name) { if (scenarioJmxs && scenarioJmxs.name) {
this.$set(this.test, "name", scenarioJmxs.name); this.$set(this.test, "name", scenarioJmxs.name);
let relateApiList = []; let relateApiList = [];
@ -278,13 +398,13 @@ export default {
this.projectEnvMap = scenarioJmxs.projectEnvMap; this.projectEnvMap = scenarioJmxs.projectEnvMap;
} }
if (scenarioJmxs.jmxs) { if (scenarioJmxs.jmxs) {
scenarioJmxs.jmxs.forEach(item => { scenarioJmxs.jmxs.forEach((item) => {
if (item.scenarioId) { if (item.scenarioId) {
this.$refs.basicConfig.importScenario(item.scenarioId); this.$refs.basicConfig.importScenario(item.scenarioId);
relateApiList.push({ relateApiList.push({
apiId: item.scenarioId, apiId: item.scenarioId,
apiVersion: item.version, apiVersion: item.version,
type: 'SCENARIO' type: "SCENARIO",
}); });
} }
if (item.caseId) { if (item.caseId) {
@ -299,8 +419,8 @@ export default {
this.$set(this.test, "apiList", relateApiList); this.$set(this.test, "apiList", relateApiList);
}); });
this.$refs.basicConfig.handleUpload(); this.$refs.basicConfig.handleUpload();
this.active = '1'; this.active = "1";
sessionStorage.removeItem('LOAD_TEST'); sessionStorage.removeItem("LOAD_TEST");
} }
} }
} }
@ -310,8 +430,7 @@ export default {
this.test.follows = []; this.test.follows = [];
this.showFollow = false; this.showFollow = false;
this.testId = testId; this.testId = testId;
this.loading = getTest(testId) this.loading = getTest(testId).then((response) => {
.then(response => {
if (response.data) { if (response.data) {
this.test = response.data; this.test = response.data;
if (!this.test.schedule) { if (!this.test.schedule) {
@ -330,9 +449,8 @@ export default {
} }
}, },
getDefaultFollow(testId) { getDefaultFollow(testId) {
getFollows(testId) getFollows(testId).then((response) => {
.then(response => { this.$set(this.test, "follows", response.data);
this.$set(this.test, 'follows', response.data);
for (let i = 0; i < this.test.follows.length; i++) { for (let i = 0; i < this.test.follows.length; i++) {
if (this.test.follows[i] === this.currentUser().id) { if (this.test.follows[i] === this.currentUser().id) {
this.showFollow = true; this.showFollow = true;
@ -349,7 +467,10 @@ export default {
return; return;
} }
if (!this.test.versionId) { if (!this.test.versionId) {
if (this.$refs.versionHistory && this.$refs.versionHistory.currentVersion) { if (
this.$refs.versionHistory &&
this.$refs.versionHistory.currentVersion
) {
this.test.versionId = this.$refs.versionHistory.currentVersion.id; this.test.versionId = this.$refs.versionHistory.currentVersion.id;
} }
} }
@ -357,12 +478,12 @@ export default {
this.loading = saveTest(this.test, formData) this.loading = saveTest(this.test, formData)
.then(({ data }) => { .then(({ data }) => {
this.$success(this.$t('commons.save_success')); this.$success(this.$t("commons.save_success"));
this.test.id = data.data.id; this.test.id = data.data.id;
this.$refs.advancedConfig.cancelAllEdit(); this.$refs.advancedConfig.cancelAllEdit();
if (this.$route.path.indexOf('/performance/test/edit/') < 0) { if (this.$route.path.indexOf("/performance/test/edit/") < 0) {
this.$router.push({ this.$router.push({
path: '/performance/test/edit/' + data.data.id, path: "/performance/test/edit/" + data.data.id,
}); });
} else { } else {
this.$refs.basicConfig.uploadList = []; this.$refs.basicConfig.uploadList = [];
@ -370,7 +491,7 @@ export default {
} }
this.getVersionHistory(); this.getVersionHistory();
}) })
.catch(error => { .catch((error) => {
if (this.$refs.versionHistory) { if (this.$refs.versionHistory) {
this.$refs.versionHistory.loading = false; this.$refs.versionHistory.loading = false;
} }
@ -382,14 +503,12 @@ export default {
} }
let formData = this.getSaveOption(); let formData = this.getSaveOption();
this.loading = saveTest(this.test, formData) this.loading = saveTest(this.test, formData).then(({ data }) => {
.then(({data}) => {
this.test.id = data.data.id; this.test.id = data.data.id;
this.$success(this.$t('commons.save_success')); this.$success(this.$t("commons.save_success"));
runTest(this.test) runTest(this.test).then((response) => {
.then(response => {
let reportId = response.data; let reportId = response.data;
this.$router.push({path: '/performance/report/view/' + reportId}); this.$router.push({ path: "/performance/report/view/" + reportId });
}); });
}); });
}, },
@ -397,58 +516,67 @@ export default {
let formData = new FormData(); let formData = new FormData();
if (this.$refs.basicConfig.uploadList.length > 0) { if (this.$refs.basicConfig.uploadList.length > 0) {
this.$refs.basicConfig.uploadList.forEach(f => { this.$refs.basicConfig.uploadList.forEach((f) => {
formData.append("file", f); formData.append("file", f);
}); });
} }
// //
this.test.updatedFileList = this.$refs.basicConfig.updatedFileList(); this.test.updatedFileList = this.$refs.basicConfig.updatedFileList();
this.test.fileSorts = this.$refs.basicConfig.fileSorts(); this.test.fileSorts = this.$refs.basicConfig.fileSorts();
this.test.conversionFileIdList = this.$refs.basicConfig.conversionMetadataIdList(); this.test.conversionFileIdList =
this.$refs.basicConfig.conversionMetadataIdList();
// //
this.test.loadConfiguration = JSON.stringify(this.$refs.pressureConfig.convertProperty()); this.test.loadConfiguration = JSON.stringify(
this.$refs.pressureConfig.convertProperty()
);
this.test.testResourcePoolId = this.$refs.pressureConfig.resourcePool; this.test.testResourcePoolId = this.$refs.pressureConfig.resourcePool;
// //
this.test.advancedConfiguration = JSON.stringify(this.$refs.advancedConfig.configurations()); this.test.advancedConfiguration = JSON.stringify(
this.$refs.advancedConfig.configurations()
);
this.test.projectEnvMap = this.projectEnvMap; this.test.projectEnvMap = this.projectEnvMap;
// filejson // filejson
let requestJson = JSON.stringify(this.test, function (key, value) { let requestJson = JSON.stringify(this.test, function (key, value) {
return key === "file" ? undefined : value; return key === "file" ? undefined : value;
}); });
formData.append('request', new Blob([requestJson], { formData.append(
type: "application/json" "request",
})); new Blob([requestJson], {
type: "application/json",
})
);
return formData; return formData;
}, },
syncScenario() { syncScenario() {
if (!hasPermission('PROJECT_API_SCENARIO:READ+CREATE')) { if (!hasPermission("PROJECT_API_SCENARIO:READ+CREATE")) {
this.$warning(this.$t('performance_test.sync_scenario_no_permission_tips')); this.$warning(
this.$t("performance_test.sync_scenario_no_permission_tips")
);
return; return;
} }
let param = { let param = {
id: this.test.id, id: this.test.id,
scenarioId: this.test.scenarioId scenarioId: this.test.scenarioId,
}; };
syncScenario(param) syncScenario(param).then(() => {
.then(() => {
this.getTest(this.$route.params.testId); this.getTest(this.$route.params.testId);
this.$success('commons.save_success'); this.$success("commons.save_success");
}); });
}, },
cancel() { cancel() {
this.$router.push({path: '/performance/test/all'}); this.$router.push({ path: "/performance/test/all" });
}, },
validTest() { validTest() {
let currentProjectId = getCurrentProjectID(); let currentProjectId = getCurrentProjectID();
this.test.projectId = currentProjectId; this.test.projectId = currentProjectId;
if (!this.test.name) { if (!this.test.name) {
this.$error(this.$t('load_test.test_name_is_null')); this.$error(this.$t("load_test.test_name_is_null"));
return false; return false;
} }
if (!this.test.projectId) { if (!this.test.projectId) {
this.$error(this.$t('load_test.project_is_null')); this.$error(this.$t("load_test.project_is_null"));
return false; return false;
} }
@ -494,22 +622,21 @@ export default {
param.enable = true; param.enable = true;
} }
saveSchedule(param) saveSchedule(param).then((response) => {
.then(response => { this.$success(this.$t("commons.save_success"));
this.$success(this.$t('commons.save_success'));
this.getTest(this.test.id); this.getTest(this.test.id);
}); });
}, },
checkScheduleEdit() { checkScheduleEdit() {
if (!this.test.id) { if (!this.test.id) {
this.$message(this.$t('api_test.environment.please_save_test')); this.$message(this.$t("api_test.environment.please_save_test"));
return false; return false;
} }
return true; return true;
}, },
durationValidate(intervalTime) { durationValidate(intervalTime) {
let duration = 0; let duration = 0;
this.$refs.pressureConfig.threadGroups.forEach(tg => { this.$refs.pressureConfig.threadGroups.forEach((tg) => {
let d = this.$refs.pressureConfig.getDuration(tg); let d = this.$refs.pressureConfig.getDuration(tg);
if (duration < d) { if (duration < d) {
duration = d; duration = d;
@ -518,31 +645,31 @@ export default {
if (intervalTime < duration * 1000) { if (intervalTime < duration * 1000) {
return { return {
pass: false, pass: false,
info: this.$t('load_test.schedule_tip') info: this.$t("load_test.schedule_tip"),
}; };
} }
return { return {
pass: true pass: true,
}; };
}, },
fileChange(threadGroups) { fileChange(threadGroups) {
let handler = this.$refs.pressureConfig; let handler = this.$refs.pressureConfig;
let csvSet = new Set; let csvSet = new Set();
threadGroups.forEach(tg => { threadGroups.forEach((tg) => {
tg.threadNumber = tg.threadNumber || 10; tg.threadNumber = tg.threadNumber || 10;
tg.duration = tg.duration || 10; tg.duration = tg.duration || 10;
tg.durationHours = Math.floor(tg.duration / 3600); tg.durationHours = Math.floor(tg.duration / 3600);
tg.durationMinutes = Math.floor((tg.duration / 60 % 60)); tg.durationMinutes = Math.floor((tg.duration / 60) % 60);
tg.durationSeconds = Math.floor((tg.duration % 60)); tg.durationSeconds = Math.floor(tg.duration % 60);
tg.rampUpTime = tg.rampUpTime || 5; tg.rampUpTime = tg.rampUpTime || 5;
tg.step = tg.step || 5; tg.step = tg.step || 5;
tg.rpsLimit = tg.rpsLimit || 10; tg.rpsLimit = tg.rpsLimit || 10;
tg.threadType = tg.threadType || 'DURATION'; tg.threadType = tg.threadType || "DURATION";
tg.iterateNum = tg.iterateNum || 1; tg.iterateNum = tg.iterateNum || 1;
tg.iterateRampUp = tg.iterateRampUp || 10; tg.iterateRampUp = tg.iterateRampUp || 10;
if (tg.csvFiles) { if (tg.csvFiles) {
tg.csvFiles.map(item => csvSet.add(item)); tg.csvFiles.map((item) => csvSet.add(item));
} }
}); });
let csvFiles = []; let csvFiles = [];
@ -564,7 +691,7 @@ export default {
handler.calculateTotalChart(); handler.calculateTotalChart();
}, },
clickTab(tab) { clickTab(tab) {
if (tab.index === '1') { if (tab.index === "1") {
this.$refs.pressureConfig.calculateTotalChart(); this.$refs.pressureConfig.calculateTotalChart();
} }
}, },
@ -578,9 +705,8 @@ export default {
} }
} }
if (this.testId) { if (this.testId) {
saveFollows(this.testId, this.test.follows) saveFollows(this.testId, this.test.follows).then(() => {
.then(() => { this.$success(this.$t("commons.cancel_follow_success"));
this.$success(this.$t('commons.cancel_follow_success'));
}); });
} }
} else { } else {
@ -590,16 +716,14 @@ export default {
} }
this.test.follows.push(this.currentUser().id); this.test.follows.push(this.currentUser().id);
if (this.testId) { if (this.testId) {
saveFollows(this.testId, this.test.follows) saveFollows(this.testId, this.test.follows).then(() => {
.then(() => { this.$success(this.$t("commons.follow_success"));
this.$success(this.$t('commons.follow_success'));
}); });
} }
} }
}, },
getDefaultVersion() { getDefaultVersion() {
getDefaultVersion(getCurrentProjectID()) getDefaultVersion(getCurrentProjectID()).then((response) => {
.then(response => {
this.latestVersionId = response.data; this.latestVersionId = response.data;
this.getVersionHistory(); this.getVersionHistory();
}); });
@ -609,12 +733,13 @@ export default {
if (this.testId) { if (this.testId) {
testId = this.testId; testId = this.testId;
} }
getTestVersionHistory(testId) getTestVersionHistory(testId).then((response) => {
.then(response => {
this.versionData = response.data; this.versionData = response.data;
let latestVersionData = response.data.filter((v) => v.versionId === this.latestVersionId); let latestVersionData = response.data.filter(
(v) => v.versionId === this.latestVersionId
);
if (latestVersionData.length > 0) { if (latestVersionData.length > 0) {
this.hasLatest = false this.hasLatest = false;
} else { } else {
this.hasLatest = true; this.hasLatest = true;
} }
@ -622,16 +747,15 @@ export default {
}, },
compare(row) { compare(row) {
this.oldData = this.test; this.oldData = this.test;
this.oldData.createTime = this.$refs.versionHistory.versionOptions.filter(v => v.id === this.test.versionId)[0].createTime; this.oldData.createTime = this.$refs.versionHistory.versionOptions.filter(
getTestByVersion(row.id, this.test.refId) (v) => v.id === this.test.versionId
.then(response => { )[0].createTime;
getTest(response.data.id) getTestByVersion(row.id, this.test.refId).then((response) => {
.then(res => { getTest(response.data.id).then((res) => {
if (res.data) { if (res.data) {
this.newData = res.data; this.newData = res.data;
this.newData.createTime = row.createTime; this.newData.createTime = row.createTime;
getFollows(response.data.id) getFollows(response.data.id).then((resp) => {
.then(resp => {
if (resp.data && resp.data.follows) { if (resp.data && resp.data.follows) {
for (let i = 0; i < resp.data.follows.length; i++) { for (let i = 0; i < resp.data.follows.length; i++) {
if (resp.data.follows[i] === this.currentUser().id) { if (resp.data.follows[i] === this.currentUser().id) {
@ -651,11 +775,13 @@ export default {
checkout(row) { checkout(row) {
//let test = this.versionData.filter(v => v.versionId === row.id)[0]; //let test = this.versionData.filter(v => v.versionId === row.id)[0];
this.test.versionId = row.id; this.test.versionId = row.id;
this.loading = getTestByVersion(this.test.versionId, this.test.refId) this.loading = getTestByVersion(
.then(response => { this.test.versionId,
this.test.refId
).then((response) => {
this.testId = response.data.id; this.testId = response.data.id;
this.$router.push({ this.$router.push({
path: '/performance/test/edit/' + this.testId, path: "/performance/test/edit/" + this.testId,
}); });
this.getVersionHistory(); this.getVersionHistory();
}); });
@ -666,45 +792,49 @@ export default {
this.save(true); this.save(true);
}, },
del(row) { del(row) {
this.$alert(this.$t('load_test.delete_confirm') + ' ' + row.name + " ", '', { this.$alert(
confirmButtonText: this.$t('commons.confirm'), this.$t("load_test.delete_confirm") + " " + row.name + " ",
"",
{
confirmButtonText: this.$t("commons.confirm"),
callback: (action) => { callback: (action) => {
if (action === 'confirm') { if (action === "confirm") {
deleteCurrentVersionTest({versionId: row.id, refId: this.test.refId}) deleteCurrentVersionTest({
.then(response => { versionId: row.id,
this.$success(this.$t('load_test.delete_success')); refId: this.test.refId,
}).then((response) => {
this.$success(this.$t("load_test.delete_success"));
this.getVersionHistory(); this.getVersionHistory();
}); });
} }
},
} }
}); );
}, },
setLatest(row) { setLatest(row) {
let param = { let param = {
projectId: getCurrentProjectID(), projectId: getCurrentProjectID(),
type: 'PERFORMANCE', type: "PERFORMANCE",
versionId: row.id, versionId: row.id,
resourceId: this.test.id resourceId: this.test.id,
} };
setLatestVersionById(param).then(() => { setLatestVersionById(param).then(() => {
this.$success(this.$t('commons.modify_success')); this.$success(this.$t("commons.modify_success"));
this.checkout(row); this.checkout(row);
}); });
}, },
handleProjectChange() { handleProjectChange() {
if (this.$route.path.startsWith('/performance/test/edit')) { if (this.$route.path.startsWith("/performance/test/edit")) {
this.$nextTick(() => { this.$nextTick(() => {
this.$router.push('/performance/test/all'); this.$router.push("/performance/test/all");
}) });
} }
}, },
} },
}; };
</script> </script>
<style scoped> <style scoped>
.el-select { .el-select {
min-width: 130px; min-width: 130px;
} }
@ -723,5 +853,4 @@ export default {
margin-right: 25px; margin-right: 25px;
margin-top: 5px; margin-top: 5px;
} }
</style> </style>