Conflicts:
	backend/src/main/java/io/metersphere/api/jmeter/APIBackendListenerClient.java
This commit is contained in:
wenyann 2020-12-24 13:18:36 +08:00
commit 3e9ae4afcb
40 changed files with 1264 additions and 460 deletions

View File

@ -44,9 +44,9 @@ public class APIScenarioReportController {
@PostMapping("/add")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public String add(@RequestBody APIScenarioReportResult node) {
public void add(@RequestBody APIScenarioReportResult node) {
node.setExecuteType(ExecuteType.Saved.name());
return apiReportService.save(node, ApiRunMode.SCENARIO.name());
apiReportService.save(node, ApiRunMode.SCENARIO.name());
}
@PostMapping("/update")

View File

@ -268,7 +268,7 @@ public class APITestController {
if(allCount!=0){
float coverageRageNumber =(float)apiCountResult.getExecutionPassCount()*100/allCount;
DecimalFormat df = new DecimalFormat("0.0");
apiCountResult.setCoverageRage(df.format(coverageRageNumber)+"%");
apiCountResult.setPassRage(df.format(coverageRageNumber)+"%");
}
return apiCountResult;
@ -302,7 +302,7 @@ public class APITestController {
if(allCount!=0){
float coverageRageNumber =(float)apiCountResult.getSuccessCount()*100/allCount;
DecimalFormat df = new DecimalFormat("0.0");
apiCountResult.setCoverageRage(df.format(coverageRageNumber)+"%");
apiCountResult.setSuccessRage(df.format(coverageRageNumber)+"%");
}
return apiCountResult;
@ -354,6 +354,6 @@ public class APITestController {
public void updateScheduleEnableByPrimyKey(@RequestBody ScheduleInfoRequest request) {
Schedule schedule = scheduleService.getSchedule(request.getTaskID());
schedule.setEnable(request.isEnable());
apiTestService.updateSchedule(schedule);
apiAutomationService.updateSchedule(schedule);
}
}

View File

@ -44,21 +44,20 @@ public class ApiDefinitionController {
@PostMapping(value = "/create", consumes = {"multipart/form-data"})
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER}, logical = Logical.OR)
public void create(@RequestPart("request") SaveApiDefinitionRequest request, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
checkPermissionService.checkReadOnlyUser();
checkPermissionService.checkProjectOwner(request.getProjectId());
apiDefinitionService.create(request, bodyFiles);
}
@PostMapping(value = "/update", consumes = {"multipart/form-data"})
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER}, logical = Logical.OR)
public void update(@RequestPart("request") SaveApiDefinitionRequest request, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
checkPermissionService.checkReadOnlyUser();
checkPermissionService.checkProjectOwner(request.getProjectId());
apiDefinitionService.update(request, bodyFiles);
}
@GetMapping("/delete/{id}")
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER}, logical = Logical.OR)
public void delete(@PathVariable String id) {
checkPermissionService.checkReadOnlyUser();
apiDefinitionService.delete(id);
}

View File

@ -21,6 +21,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/api/testcase")
@ -43,6 +44,12 @@ public class ApiTestCaseController {
return PageUtils.setPageInfo(page, apiTestCaseService.listSimple(request));
}
@PostMapping("/get/request")
public Map<String, String> listSimple(@RequestBody ApiTestCaseRequest request) {
request.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());
return apiTestCaseService.getRequest(request);
}
@PostMapping(value = "/create", consumes = {"multipart/form-data"})
public void create(@RequestPart("request") SaveApiTestCaseRequest request, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
apiTestCaseService.create(request, bodyFiles);

View File

@ -206,35 +206,17 @@ public class MsHTTPSamplerProxy extends MsTestElement {
this.getRest().stream().filter(KeyValue::isEnable).filter(KeyValue::isValid).forEach(keyValue ->
keyValueMap.put(keyValue.getName(), keyValue.getValue())
);
// 这块是否使用jmeter自身机制
Map<String, String> pubKeyValueMap = new HashMap<>();
if (config != null && config.getVariables() != null) {
config.getVariables().stream().forEach(keyValue -> {
pubKeyValueMap.put(keyValue.getName(), keyValue.getValue());
});
}
for (String key : keyValueMap.keySet()) {
if (keyValueMap.get(key) != null && keyValueMap.get(key).startsWith("$")) {
String pubKey = keyValueMap.get(key).substring(2, keyValueMap.get(key).length() - 1);
keyValueMap.put(key, pubKeyValueMap.get(pubKey));
}
}
Pattern p = Pattern.compile("(\\{)([\\w]+)(\\})");
Matcher m = p.matcher(path);
StringBuffer sb = new StringBuffer();
try {
Pattern p = Pattern.compile("(\\{)([\\w]+)(\\})");
Matcher m = p.matcher(path);
while (m.find()) {
String group = m.group(2);
//替换并且把替换好的值放到sb中
m.appendReplacement(sb, keyValueMap.get(group));
path = path.replace("{" + group + "}", keyValueMap.get(group));
}
} catch (Exception ex) {
ex.printStackTrace();
}
//把符合的数据追加到sb尾
m.appendTail(sb);
return sb.toString();
return path;
}
private String getPostQueryParameters(String path) {

View File

@ -1,6 +1,7 @@
package io.metersphere.api.jmeter;
import io.metersphere.api.service.*;
import io.metersphere.base.domain.ApiScenarioReport;
import io.metersphere.base.domain.ApiTestReport;
import io.metersphere.commons.constants.APITestStatus;
import io.metersphere.commons.constants.ApiRunMode;
@ -20,6 +21,7 @@ import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.visualizers.backend.AbstractBackendListenerClient;
import org.apache.jmeter.visualizers.backend.BackendListenerContext;
import org.python.antlr.ast.Str;
import org.springframework.http.HttpMethod;
import java.io.ByteArrayOutputStream;
@ -50,6 +52,7 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
private ApiScenarioReportService apiScenarioReportService;
public String runMode = ApiRunMode.RUN.name();
// 测试ID
@ -155,6 +158,7 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
testResult.getScenarios().addAll(scenarios.values());
testResult.getScenarios().sort(Comparator.comparing(ScenarioResult::getId));
ApiTestReport report = null;
String reportUrl = null;
// 这部分后续优化只留 DELIMIT SCENARIO 两部分
if (StringUtils.equals(this.runMode, ApiRunMode.DEBUG.name())) {
report = apiReportService.get(debugReportId);
@ -173,7 +177,31 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
} else if (StringUtils.equalsAny(this.runMode, ApiRunMode.SCENARIO.name(), ApiRunMode.SCENARIO_PLAN.name())) {
// 执行报告不需要存储由用户确认后在存储
testResult.setTestId(testId);
apiScenarioReportService.complete(testResult, this.runMode);
ApiScenarioReport scenarioReport = apiScenarioReportService.complete(testResult, this.runMode);
report = new ApiTestReport();
report.setStatus(scenarioReport.getStatus());
report.setId(scenarioReport.getId());
report.setTriggerMode(scenarioReport.getTriggerMode());
report.setName(scenarioReport.getName());
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
assert systemParameterService != null;
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
reportUrl = baseSystemConfigDTO.getUrl() + "/#/api/automation/report";
String scenaName = scenarioReport.getName();
if(scenaName==null){
scenaName = "";
}else {
scenaName = scenaName.split("-")[0];
}
String scenarioID = apiScenarioReportService.getApiScenarioId(scenaName,scenarioReport.getProjectId());
testResult.setTestId(scenarioID);
} else {
apiTestService.changeStatus(testId, APITestStatus.Completed);
report = apiReportService.getRunningReport(testResult.getTestId());
@ -196,24 +224,24 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
}
}
try {
if (StringUtils.equals(NoticeConstants.Mode.API, report.getTriggerMode()) || StringUtils.equals(NoticeConstants.Mode.SCHEDULE, report.getTriggerMode())) {
sendTask(report, testResult);
}
sendTask(report,reportUrl, testResult);
} catch (Exception e) {
LogUtil.error("发送通知" + e.getMessage(), e);
LogUtil.error(e.getMessage(), e);
}
}
private static void sendTask(ApiTestReport report, TestResult testResult) {
private static void sendTask(ApiTestReport report,String reportUrl, TestResult testResult) {
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
NoticeSendService noticeSendService = CommonBeanFactory.getBean(NoticeSendService.class);
assert systemParameterService != null;
assert noticeSendService != null;
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String url = baseSystemConfigDTO.getUrl() + "/#/api/report/view/" + report.getId();
String url = reportUrl;
if(StringUtils.isEmpty(url)){
url = baseSystemConfigDTO.getUrl() + "/#/api/report/view/" + report.getId();
}
String successContext = "";
String failedContext = "";
String subject = "";
@ -239,7 +267,6 @@ public class APIBackendListenerClient extends AbstractBackendListenerClient impl
paramMap.put("id", report.getId());
paramMap.put("type", "performance");
paramMap.put("url", baseSystemConfigDTO.getUrl());
paramMap.put("state", report.getStatus());
NoticeModel noticeModel = NoticeModel.builder()
.successContext(successContext)
.successMailTemplate("ApiSuccessfulNotification")

View File

@ -20,7 +20,7 @@ public class TestResult {
private int passAssertions = 0;
private final List<ScenarioResult> scenarios = new ArrayList<>();
private List<ScenarioResult> scenarios = new ArrayList<>();
public void addError(int count) {
this.error += count;

View File

@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.metersphere.api.dto.DeleteAPIReportRequest;
import io.metersphere.api.dto.automation.*;
import io.metersphere.api.dto.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.RunDefinitionRequest;
@ -14,6 +15,7 @@ import io.metersphere.api.dto.scenario.environment.EnvironmentConfig;
import io.metersphere.api.jmeter.JMeterService;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ApiScenarioMapper;
import io.metersphere.base.mapper.ApiScenarioReportMapper;
import io.metersphere.base.mapper.TestPlanApiScenarioMapper;
import io.metersphere.base.mapper.ext.ExtApiScenarioMapper;
import io.metersphere.base.mapper.ext.ExtTestPlanApiCaseMapper;
@ -30,9 +32,6 @@ import io.metersphere.service.ScheduleService;
import io.metersphere.track.dto.TestPlanDTO;
import io.metersphere.track.request.testcase.ApiCaseRelevanceRequest;
import io.metersphere.track.request.testcase.QueryTestPlanRequest;
import io.metersphere.track.request.testcase.TestPlanApiCaseBatchRequest;
import io.metersphere.track.service.TestPlanApiCaseService;
import io.metersphere.track.service.TestPlanScenarioCaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
@ -47,7 +46,6 @@ import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
@Transactional(rollbackFor = Exception.class)
@ -72,6 +70,8 @@ public class ApiAutomationService {
private ExtTestPlanMapper extTestPlanMapper;
@Resource
SqlSessionFactory sqlSessionFactory;
@Resource
private ApiScenarioReportMapper apiScenarioReportMapper;
public List<ApiScenarioDTO> list(ApiScenarioRequest request) {
request.setOrders(ServiceUtils.getDefaultOrder(request.getOrders()));
@ -160,7 +160,11 @@ public class ApiAutomationService {
apiScenarioMapper.deleteByPrimaryKey(id);
}
public void preDelete(String scenarioID){
public void preDelete(String scenarioID) {
ApiScenarioReportExample scenarioReportExample = new ApiScenarioReportExample();
scenarioReportExample.createCriteria().andScenarioIdEqualTo(scenarioID);
List<ApiScenarioReport> list = apiScenarioReportMapper.selectByExample(scenarioReportExample);
deleteApiScenarioReport(list);
scheduleService.deleteByResourceId(scenarioID);
TestPlanApiScenarioExample example = new TestPlanApiScenarioExample();
@ -174,37 +178,51 @@ public class ApiAutomationService {
}
example = new TestPlanApiScenarioExample();
if(!idList.isEmpty()){
if (!idList.isEmpty()) {
example.createCriteria().andIdIn(idList);
testPlanApiScenarioMapper.deleteByExample(example);
}
}
public void preDelete(List<String> scenarioIDList){
private void deleteApiScenarioReport(List<ApiScenarioReport> list) {
if (CollectionUtils.isNotEmpty(list)) {
List<String> ids = list.stream().map(ApiScenarioReport::getId).collect(Collectors.toList());
DeleteAPIReportRequest reportRequest = new DeleteAPIReportRequest();
reportRequest.setIds(ids);
apiReportService.deleteAPIReportBatch(reportRequest);
}
}
public void preDeleteBatch(List<String> scenarioIDList) {
ApiScenarioReportExample scenarioReportExample = new ApiScenarioReportExample();
scenarioReportExample.createCriteria().andScenarioIdIn(scenarioIDList);
List<ApiScenarioReport> list = apiScenarioReportMapper.selectByExample(scenarioReportExample);
deleteApiScenarioReport(list);
List<String> testPlanApiScenarioIdList = new ArrayList<>();
List<String> scheduleIdList = new ArrayList<>();
for (String id :scenarioIDList) {
for (String id : scenarioIDList) {
TestPlanApiScenarioExample example = new TestPlanApiScenarioExample();
example.createCriteria().andApiScenarioIdEqualTo(id);
List<TestPlanApiScenario> testPlanApiScenarioList = testPlanApiScenarioMapper.selectByExample(example);
for (TestPlanApiScenario api :testPlanApiScenarioList) {
if(!testPlanApiScenarioIdList.contains(api.getId())){
for (TestPlanApiScenario api : testPlanApiScenarioList) {
if (!testPlanApiScenarioIdList.contains(api.getId())) {
testPlanApiScenarioIdList.add(api.getId());
}
}
scheduleService.deleteByResourceId(id);
}
if(!testPlanApiScenarioIdList.isEmpty()){
if (!testPlanApiScenarioIdList.isEmpty()) {
TestPlanApiScenarioExample example = new TestPlanApiScenarioExample();
example.createCriteria().andIdIn(testPlanApiScenarioIdList);
testPlanApiScenarioMapper.deleteByExample(example);
}
}
public void deleteBatch(List<String> ids) {
//及连删除外键表
preDelete(ids);;
// 删除外键表
preDeleteBatch(ids);
ApiScenarioExample example = new ApiScenarioExample();
example.createCriteria().andIdIn(ids);
apiScenarioMapper.deleteByExample(example);
@ -242,16 +260,16 @@ public class ApiAutomationService {
return new ArrayList<>();
}
private void createAPIScenarioReportResult(String id, String triggerMode, String execType, String projectId,String userID) {
private void createAPIScenarioReportResult(String id, String triggerMode, String execType, String projectId, String userID) {
APIScenarioReportResult report = new APIScenarioReportResult();
report.setId(id);
report.setName("测试执行结果");
report.setCreateTime(System.currentTimeMillis());
report.setUpdateTime(System.currentTimeMillis());
report.setStatus(APITestStatus.Running.name());
if(StringUtils.isNotEmpty(userID)){
if (StringUtils.isNotEmpty(userID)) {
report.setUserId(userID);
}else {
} else {
report.setUserId(SessionUtils.getUserId());
}
@ -316,7 +334,7 @@ public class ApiAutomationService {
jMeterService.runDefinition(request.getId(), jmeterTestPlanHashTree, request.getReportId(), runMode);
createAPIScenarioReportResult(request.getId(), request.getTriggerMode() == null ? ReportTriggerMode.MANUAL.name() : request.getTriggerMode(),
request.getExecuteType(), projectID,request.getReportUserID());
request.getExecuteType(), projectID, request.getReportUserID());
return request.getId();
}
@ -339,7 +357,6 @@ public class ApiAutomationService {
ParameterConfig config = new ParameterConfig();
config.setConfig(envConfig);
HashTree hashTree = request.getTestElement().generateHashTree(config);
request.getTestElement().getJmx(hashTree);
// 调用执行方法
jMeterService.runDefinition(request.getId(), hashTree, request.getReportId(), ApiRunMode.SCENARIO.name());
createAPIScenarioReportResult(request.getId(), ReportTriggerMode.MANUAL.name(), request.getExecuteType(), request.getProjectId(),
@ -367,8 +384,8 @@ public class ApiAutomationService {
ExtTestPlanScenarioCaseMapper scenarioBatchMapper = sqlSession.getMapper(ExtTestPlanScenarioCaseMapper.class);
ExtTestPlanApiCaseMapper apiCaseBatchMapper = sqlSession.getMapper(ExtTestPlanApiCaseMapper.class);
for (TestPlanDTO testPlan:list) {
if(request.getScenarioIds()!=null){
for (TestPlanDTO testPlan : list) {
if (request.getScenarioIds() != null) {
for (String scenarioId : request.getScenarioIds()) {
TestPlanApiScenario testPlanApiScenario = new TestPlanApiScenario();
testPlanApiScenario.setId(UUID.randomUUID().toString());
@ -379,7 +396,7 @@ public class ApiAutomationService {
scenarioBatchMapper.insertIfNotExists(testPlanApiScenario);
}
}
if(request.getApiIds()!=null){
if (request.getApiIds() != null) {
for (String caseId : request.getApiIds()) {
TestPlanApiCase testPlanApiCase = new TestPlanApiCase();
testPlanApiCase.setId(UUID.randomUUID().toString());
@ -390,40 +407,7 @@ public class ApiAutomationService {
apiCaseBatchMapper.insertIfNotExists(testPlanApiCase);
}
}
}
// testPlan的ID先不存储
// list.forEach(item -> {
// if (CollectionUtils.isNotEmpty(request.getApiIds())) {
// if (CollectionUtils.isNotEmpty(request.getApiIds())) {
// if (StringUtils.isEmpty(item.getApiIds())) {
// item.setApiIds(JSON.toJSONString(request.getApiIds()));
// } else {
// // 合并api
// List<String> dbApiIDs = JSON.parseArray(item.getApiIds(), String.class);
// List<String> result = Stream.of(request.getApiIds(), dbApiIDs)
// .flatMap(Collection::stream).distinct().collect(Collectors.toList());
// item.setApiIds(JSON.toJSONString(result));
// }
// item.setScenarioIds(null);
// }
// }
// if (CollectionUtils.isNotEmpty(request.getScenarioIds())) {
// if (CollectionUtils.isNotEmpty(request.getScenarioIds())) {
// if (StringUtils.isEmpty(item.getScenarioIds())) {
// item.setScenarioIds(JSON.toJSONString(request.getScenarioIds()));
// } else {
// // 合并场景ID
// List<String> dbScenarioIDs = JSON.parseArray(item.getScenarioIds(), String.class);
// List<String> result = Stream.of(request.getScenarioIds(), dbScenarioIDs)
// .flatMap(Collection::stream).distinct().collect(Collectors.toList());
// item.setScenarioIds(JSON.toJSONString(result));
// }
// item.setApiIds(null);
// }
// }
// mapper.updatePlan(item);
// });
sqlSession.flushStatements();
return "success";
}
@ -434,10 +418,8 @@ public class ApiAutomationService {
public long countScenarioByProjectIDAndCreatInThisWeek(String projectId) {
Map<String, Date> startAndEndDateInWeek = DateUtils.getWeedFirstTimeAndLastTime(new Date());
Date firstTime = startAndEndDateInWeek.get("firstTime");
Date lastTime = startAndEndDateInWeek.get("lastTime");
if (firstTime == null || lastTime == null) {
return 0;
} else {

View File

@ -50,7 +50,18 @@ public class ApiScenarioReportService {
@Resource
private TestPlanApiScenarioMapper testPlanApiScenarioMapper;
public void complete(TestResult result, String runMode) {
public String getApiScenarioId(String name, String projectID) {
ApiScenarioExample example = new ApiScenarioExample();
example.createCriteria().andNameEqualTo(name).andProjectIdEqualTo(projectID).andStatusNotEqualTo("Trash");
List<ApiScenario> list = apiScenarioMapper.selectByExample(example);
if (list.isEmpty()) {
return null;
} else {
return list.get(0).getId();
}
}
public ApiScenarioReport complete(TestResult result, String runMode) {
Object obj = cache.get(result.getTestId());
if (obj == null) {
MSException.throwException(Translator.get("api_report_is_null"));
@ -80,9 +91,11 @@ public class ApiScenarioReportService {
}
report.setContent(new String(detail.getContent(), StandardCharsets.UTF_8));
this.save(report, runMode);
// 此方法适用于前端发起
if (!report.getTriggerMode().equals(ReportTriggerMode.SCHEDULE.name())) {
cache.put(report.getId(), report);
}
return report;
}
/**
@ -129,19 +142,21 @@ public class ApiScenarioReportService {
}
}
public ApiScenarioReport createReport(APIScenarioReportResult test) {
public ApiScenarioReport createReport(APIScenarioReportResult test, String scenarioName, String scenarioId, String result) {
checkNameExist(test);
ApiScenarioReport report = new ApiScenarioReport();
report.setId(UUID.randomUUID().toString());
report.setProjectId(test.getProjectId());
report.setName(test.getName());
report.setName(scenarioName + "-" + DateUtils.getTimeStr(System.currentTimeMillis()));
report.setTriggerMode(test.getTriggerMode());
report.setDescription(test.getDescription());
report.setCreateTime(System.currentTimeMillis());
report.setUpdateTime(System.currentTimeMillis());
report.setStatus(test.getStatus());
report.setStatus(result);
report.setUserId(test.getUserId());
report.setExecuteType(test.getExecuteType());
report.setScenarioId(scenarioId);
report.setScenarioName(scenarioName);
apiScenarioReportMapper.insert(report);
return report;
}
@ -159,33 +174,37 @@ public class ApiScenarioReportService {
report.setStatus(test.getStatus());
report.setUserId(test.getUserId());
report.setExecuteType(test.getExecuteType());
report.setScenarioId(test.getScenarioId());
report.setScenarioName(test.getScenarioName());
apiScenarioReportMapper.updateByPrimaryKey(report);
return report;
}
private TestResult createTestResult(TestResult result) {
TestResult newrResult = new TestResult();
newrResult.setTestId(result.getTestId());
newrResult.setTotal(result.getTotal());
newrResult.setError(result.getError());
newrResult.setPassAssertions(result.getPassAssertions());
newrResult.setSuccess(result.getSuccess());
newrResult.setTotalAssertions(result.getTotalAssertions());
return newrResult;
}
public String save(APIScenarioReportResult test, String runModel) {
ApiScenarioReport report = createReport(test);
ApiScenarioReportDetail detail = new ApiScenarioReportDetail();
public void save(APIScenarioReportResult test, String runModel) {
TestResult result = JSON.parseObject(test.getContent(), TestResult.class);
// 更新场景
if (result != null) {
if (StringUtils.equals(runModel, ApiRunMode.SCENARIO_PLAN.name())) {
updatePlanCase(result, test, report);
updatePlanCase(result, test);
} else {
updateScenario(result.getScenarios(), test.getProjectId(), report.getId());
updateScenario(test, result);
}
}
detail.setContent(test.getContent().getBytes(StandardCharsets.UTF_8));
detail.setReportId(report.getId());
detail.setProjectId(test.getProjectId());
apiScenarioReportDetailMapper.insert(detail);
return report.getId();
}
public void updatePlanCase(TestResult result, APIScenarioReportResult test, ApiScenarioReport report) {
TestPlanApiScenario testPlanApiScenario = new TestPlanApiScenario();
testPlanApiScenario.setId(test.getId());
public void updatePlanCase(TestResult result, APIScenarioReportResult test) {
TestPlanApiScenario testPlanApiScenario = testPlanApiScenarioMapper.selectByPrimaryKey(test.getId());
ScenarioResult scenarioResult = result.getScenarios().get(0);
if (scenarioResult.getError() > 0) {
testPlanApiScenario.setLastResult("Fail");
@ -194,14 +213,27 @@ public class ApiScenarioReportService {
}
String passRate = new DecimalFormat("0%").format((float) scenarioResult.getSuccess() / (scenarioResult.getSuccess() + scenarioResult.getError()));
testPlanApiScenario.setPassRate(passRate);
// 存储场景报告
ApiScenarioReport report = createReport(test, scenarioResult.getName(), testPlanApiScenario.getApiScenarioId(), scenarioResult.getError() == 0 ? "Success" : "Error");
// 报告详情内容
ApiScenarioReportDetail detail = new ApiScenarioReportDetail();
TestResult newResult = createTestResult(result);
List<ScenarioResult> scenarioResults = new ArrayList();
scenarioResults.add(scenarioResult);
newResult.setScenarios(scenarioResults);
detail.setContent(JSON.toJSONString(newResult).getBytes(StandardCharsets.UTF_8));
detail.setReportId(report.getId());
detail.setProjectId(test.getProjectId());
apiScenarioReportDetailMapper.insert(detail);
testPlanApiScenario.setReportId(report.getId());
testPlanApiScenarioMapper.updateByPrimaryKeySelective(testPlanApiScenario);
}
public void updateScenario(List<ScenarioResult> Scenarios, String projectId, String reportId) {
Scenarios.forEach(item -> {
public void updateScenario(APIScenarioReportResult test, TestResult result) {
result.getScenarios().forEach(item -> {
ApiScenarioExample example = new ApiScenarioExample();
example.createCriteria().andNameEqualTo(item.getName()).andProjectIdEqualTo(projectId);
example.createCriteria().andNameEqualTo(item.getName()).andProjectIdEqualTo(test.getProjectId());
List<ApiScenario> list = apiScenarioMapper.selectByExample(example);
if (list.size() > 0) {
ApiScenario scenario = list.get(0);
@ -212,7 +244,21 @@ public class ApiScenarioReportService {
}
String passRate = new DecimalFormat("0%").format((float) item.getSuccess() / (item.getSuccess() + item.getError()));
scenario.setPassRate(passRate);
scenario.setReportId(reportId);
// 存储场景报告
ApiScenarioReport report = createReport(test, scenario.getName(), scenario.getId(), scenario.getLastResult());
// 报告详情内容
ApiScenarioReportDetail detail = new ApiScenarioReportDetail();
TestResult newResult = createTestResult(result);
List<ScenarioResult> scenarioResults = new ArrayList();
scenarioResults.add(item);
newResult.setScenarios(scenarioResults);
detail.setContent(JSON.toJSONString(newResult).getBytes(StandardCharsets.UTF_8));
detail.setReportId(report.getId());
detail.setProjectId(scenario.getProjectId());
apiScenarioReportDetailMapper.insert(detail);
// 更新场景状态
scenario.setReportId(report.getId());
apiScenarioMapper.updateByPrimaryKey(scenario);
}
});

View File

@ -105,7 +105,6 @@ public class ApiTestCaseService {
public void update(SaveApiTestCaseRequest request, List<MultipartFile> bodyFiles) {
deleteFileByTestId(request.getId());
List<String> bodyUploadIds = new ArrayList<>(request.getBodyUploadIds());
request.setBodyUploadIds(null);
ApiTestCase test = updateTest(request);
@ -134,12 +133,9 @@ public class ApiTestCaseService {
}
public void delete(String testId) {
extTestPlanTestCaseMapper.deleteByTestCaseID(testId);
deleteFileByTestId(testId);
extApiDefinitionExecResultMapper.deleteByResourceId(testId);
apiTestCaseMapper.deleteByPrimaryKey(testId);
deleteBodyFiles(testId);
}
@ -332,4 +328,9 @@ public class ApiTestCaseService {
example.createCriteria().andIdIn(caseIds);
return apiTestCaseMapper.selectByExample(example);
}
public Map<String, String> getRequest(ApiTestCaseRequest request) {
List<ApiTestCaseWithBLOBs> list = extApiTestCaseMapper.getRequest(request);
return list.stream().collect(Collectors.toMap(ApiTestCaseWithBLOBs::getId, ApiTestCaseWithBLOBs::getRequest));
}
}

View File

@ -24,6 +24,10 @@ public class ApiScenarioReport implements Serializable {
private String executeType;
private String scenarioName;
private String scenarioId;
private String description;
private static final long serialVersionUID = 1L;

View File

@ -713,6 +713,146 @@ public class ApiScenarioReportExample {
addCriterion("execute_type not between", value1, value2, "executeType");
return (Criteria) this;
}
public Criteria andScenarioNameIsNull() {
addCriterion("scenario_name is null");
return (Criteria) this;
}
public Criteria andScenarioNameIsNotNull() {
addCriterion("scenario_name is not null");
return (Criteria) this;
}
public Criteria andScenarioNameEqualTo(String value) {
addCriterion("scenario_name =", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameNotEqualTo(String value) {
addCriterion("scenario_name <>", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameGreaterThan(String value) {
addCriterion("scenario_name >", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameGreaterThanOrEqualTo(String value) {
addCriterion("scenario_name >=", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameLessThan(String value) {
addCriterion("scenario_name <", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameLessThanOrEqualTo(String value) {
addCriterion("scenario_name <=", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameLike(String value) {
addCriterion("scenario_name like", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameNotLike(String value) {
addCriterion("scenario_name not like", value, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameIn(List<String> values) {
addCriterion("scenario_name in", values, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameNotIn(List<String> values) {
addCriterion("scenario_name not in", values, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameBetween(String value1, String value2) {
addCriterion("scenario_name between", value1, value2, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioNameNotBetween(String value1, String value2) {
addCriterion("scenario_name not between", value1, value2, "scenarioName");
return (Criteria) this;
}
public Criteria andScenarioIdIsNull() {
addCriterion("scenario_id is null");
return (Criteria) this;
}
public Criteria andScenarioIdIsNotNull() {
addCriterion("scenario_id is not null");
return (Criteria) this;
}
public Criteria andScenarioIdEqualTo(String value) {
addCriterion("scenario_id =", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdNotEqualTo(String value) {
addCriterion("scenario_id <>", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdGreaterThan(String value) {
addCriterion("scenario_id >", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdGreaterThanOrEqualTo(String value) {
addCriterion("scenario_id >=", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdLessThan(String value) {
addCriterion("scenario_id <", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdLessThanOrEqualTo(String value) {
addCriterion("scenario_id <=", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdLike(String value) {
addCriterion("scenario_id like", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdNotLike(String value) {
addCriterion("scenario_id not like", value, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdIn(List<String> values) {
addCriterion("scenario_id in", values, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdNotIn(List<String> values) {
addCriterion("scenario_id not in", values, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdBetween(String value1, String value2) {
addCriterion("scenario_id between", value1, value2, "scenarioId");
return (Criteria) this;
}
public Criteria andScenarioIdNotBetween(String value1, String value2) {
addCriterion("scenario_id not between", value1, value2, "scenarioId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -1,8 +1,9 @@
package io.metersphere.base.domain;
import java.io.Serializable;
import lombok.Data;
import java.io.Serializable;
@Data
public class TestPlan implements Serializable {
private String id;
@ -39,10 +40,6 @@ public class TestPlan implements Serializable {
private String creator;
private String apiIds;
private String scenarioIds;
private String tags;
private static final long serialVersionUID = 1L;

View File

@ -1233,146 +1233,6 @@ public class TestPlanExample {
addCriterion("creator not between", value1, value2, "creator");
return (Criteria) this;
}
public Criteria andApiIdsIsNull() {
addCriterion("api_ids is null");
return (Criteria) this;
}
public Criteria andApiIdsIsNotNull() {
addCriterion("api_ids is not null");
return (Criteria) this;
}
public Criteria andApiIdsEqualTo(String value) {
addCriterion("api_ids =", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsNotEqualTo(String value) {
addCriterion("api_ids <>", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsGreaterThan(String value) {
addCriterion("api_ids >", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsGreaterThanOrEqualTo(String value) {
addCriterion("api_ids >=", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsLessThan(String value) {
addCriterion("api_ids <", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsLessThanOrEqualTo(String value) {
addCriterion("api_ids <=", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsLike(String value) {
addCriterion("api_ids like", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsNotLike(String value) {
addCriterion("api_ids not like", value, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsIn(List<String> values) {
addCriterion("api_ids in", values, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsNotIn(List<String> values) {
addCriterion("api_ids not in", values, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsBetween(String value1, String value2) {
addCriterion("api_ids between", value1, value2, "apiIds");
return (Criteria) this;
}
public Criteria andApiIdsNotBetween(String value1, String value2) {
addCriterion("api_ids not between", value1, value2, "apiIds");
return (Criteria) this;
}
public Criteria andScenarioIdsIsNull() {
addCriterion("scenario_ids is null");
return (Criteria) this;
}
public Criteria andScenarioIdsIsNotNull() {
addCriterion("scenario_ids is not null");
return (Criteria) this;
}
public Criteria andScenarioIdsEqualTo(String value) {
addCriterion("scenario_ids =", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsNotEqualTo(String value) {
addCriterion("scenario_ids <>", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsGreaterThan(String value) {
addCriterion("scenario_ids >", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsGreaterThanOrEqualTo(String value) {
addCriterion("scenario_ids >=", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsLessThan(String value) {
addCriterion("scenario_ids <", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsLessThanOrEqualTo(String value) {
addCriterion("scenario_ids <=", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsLike(String value) {
addCriterion("scenario_ids like", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsNotLike(String value) {
addCriterion("scenario_ids not like", value, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsIn(List<String> values) {
addCriterion("scenario_ids in", values, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsNotIn(List<String> values) {
addCriterion("scenario_ids not in", values, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsBetween(String value1, String value2) {
addCriterion("scenario_ids between", value1, value2, "scenarioIds");
return (Criteria) this;
}
public Criteria andScenarioIdsNotBetween(String value1, String value2) {
addCriterion("scenario_ids not between", value1, value2, "scenarioIds");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -2,9 +2,8 @@ package io.metersphere.base.mapper;
import io.metersphere.base.domain.ApiScenarioReport;
import io.metersphere.base.domain.ApiScenarioReportExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ApiScenarioReportMapper {
long countByExample(ApiScenarioReportExample example);

View File

@ -11,6 +11,8 @@
<result column="user_id" jdbcType="VARCHAR" property="userId" />
<result column="trigger_mode" jdbcType="VARCHAR" property="triggerMode" />
<result column="execute_type" jdbcType="VARCHAR" property="executeType" />
<result column="scenario_name" jdbcType="VARCHAR" property="scenarioName" />
<result column="scenario_id" jdbcType="VARCHAR" property="scenarioId" />
</resultMap>
<resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="io.metersphere.base.domain.ApiScenarioReport">
<result column="description" jdbcType="LONGVARCHAR" property="description" />
@ -75,7 +77,7 @@
</sql>
<sql id="Base_Column_List">
id, project_id, `name`, create_time, update_time, `status`, user_id, trigger_mode,
execute_type
execute_type, scenario_name, scenario_id
</sql>
<sql id="Blob_Column_List">
description
@ -132,11 +134,13 @@
insert into api_scenario_report (id, project_id, `name`,
create_time, update_time, `status`,
user_id, trigger_mode, execute_type,
description)
scenario_name, scenario_id, description
)
values (#{id,jdbcType=VARCHAR}, #{projectId,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR},
#{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT}, #{status,jdbcType=VARCHAR},
#{userId,jdbcType=VARCHAR}, #{triggerMode,jdbcType=VARCHAR}, #{executeType,jdbcType=VARCHAR},
#{description,jdbcType=LONGVARCHAR})
#{scenarioName,jdbcType=VARCHAR}, #{scenarioId,jdbcType=VARCHAR}, #{description,jdbcType=LONGVARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.ApiScenarioReport">
insert into api_scenario_report
@ -168,6 +172,12 @@
<if test="executeType != null">
execute_type,
</if>
<if test="scenarioName != null">
scenario_name,
</if>
<if test="scenarioId != null">
scenario_id,
</if>
<if test="description != null">
description,
</if>
@ -200,6 +210,12 @@
<if test="executeType != null">
#{executeType,jdbcType=VARCHAR},
</if>
<if test="scenarioName != null">
#{scenarioName,jdbcType=VARCHAR},
</if>
<if test="scenarioId != null">
#{scenarioId,jdbcType=VARCHAR},
</if>
<if test="description != null">
#{description,jdbcType=LONGVARCHAR},
</if>
@ -241,6 +257,12 @@
<if test="record.executeType != null">
execute_type = #{record.executeType,jdbcType=VARCHAR},
</if>
<if test="record.scenarioName != null">
scenario_name = #{record.scenarioName,jdbcType=VARCHAR},
</if>
<if test="record.scenarioId != null">
scenario_id = #{record.scenarioId,jdbcType=VARCHAR},
</if>
<if test="record.description != null">
description = #{record.description,jdbcType=LONGVARCHAR},
</if>
@ -260,6 +282,8 @@
user_id = #{record.userId,jdbcType=VARCHAR},
trigger_mode = #{record.triggerMode,jdbcType=VARCHAR},
execute_type = #{record.executeType,jdbcType=VARCHAR},
scenario_name = #{record.scenarioName,jdbcType=VARCHAR},
scenario_id = #{record.scenarioId,jdbcType=VARCHAR},
description = #{record.description,jdbcType=LONGVARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@ -275,7 +299,9 @@
`status` = #{record.status,jdbcType=VARCHAR},
user_id = #{record.userId,jdbcType=VARCHAR},
trigger_mode = #{record.triggerMode,jdbcType=VARCHAR},
execute_type = #{record.executeType,jdbcType=VARCHAR}
execute_type = #{record.executeType,jdbcType=VARCHAR},
scenario_name = #{record.scenarioName,jdbcType=VARCHAR},
scenario_id = #{record.scenarioId,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -307,6 +333,12 @@
<if test="executeType != null">
execute_type = #{executeType,jdbcType=VARCHAR},
</if>
<if test="scenarioName != null">
scenario_name = #{scenarioName,jdbcType=VARCHAR},
</if>
<if test="scenarioId != null">
scenario_id = #{scenarioId,jdbcType=VARCHAR},
</if>
<if test="description != null">
description = #{description,jdbcType=LONGVARCHAR},
</if>
@ -323,6 +355,8 @@
user_id = #{userId,jdbcType=VARCHAR},
trigger_mode = #{triggerMode,jdbcType=VARCHAR},
execute_type = #{executeType,jdbcType=VARCHAR},
scenario_name = #{scenarioName,jdbcType=VARCHAR},
scenario_id = #{scenarioId,jdbcType=VARCHAR},
description = #{description,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
@ -335,7 +369,9 @@
`status` = #{status,jdbcType=VARCHAR},
user_id = #{userId,jdbcType=VARCHAR},
trigger_mode = #{triggerMode,jdbcType=VARCHAR},
execute_type = #{executeType,jdbcType=VARCHAR}
execute_type = #{executeType,jdbcType=VARCHAR},
scenario_name = #{scenarioName,jdbcType=VARCHAR},
scenario_id = #{scenarioId,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -19,8 +19,6 @@
<result column="planned_end_time" jdbcType="BIGINT" property="plannedEndTime" />
<result column="actual_start_time" jdbcType="BIGINT" property="actualStartTime" />
<result column="creator" jdbcType="VARCHAR" property="creator" />
<result column="api_ids" jdbcType="VARCHAR" property="apiIds" />
<result column="scenario_ids" jdbcType="VARCHAR" property="scenarioIds" />
</resultMap>
<resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="io.metersphere.base.domain.TestPlan">
<result column="tags" jdbcType="LONGVARCHAR" property="tags" />
@ -86,7 +84,7 @@
<sql id="Base_Column_List">
id, workspace_id, report_id, `name`, description, `status`, stage, principal, test_case_match_rule,
executor_match_rule, create_time, update_time, actual_end_time, planned_start_time,
planned_end_time, actual_start_time, creator, api_ids, scenario_ids
planned_end_time, actual_start_time, creator
</sql>
<sql id="Blob_Column_List">
tags
@ -145,15 +143,15 @@
stage, principal, test_case_match_rule,
executor_match_rule, create_time, update_time,
actual_end_time, planned_start_time, planned_end_time,
actual_start_time, creator, api_ids,
scenario_ids, tags)
actual_start_time, creator, tags
)
values (#{id,jdbcType=VARCHAR}, #{workspaceId,jdbcType=VARCHAR}, #{reportId,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}, #{status,jdbcType=VARCHAR},
#{stage,jdbcType=VARCHAR}, #{principal,jdbcType=VARCHAR}, #{testCaseMatchRule,jdbcType=VARCHAR},
#{executorMatchRule,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT},
#{actualEndTime,jdbcType=BIGINT}, #{plannedStartTime,jdbcType=BIGINT}, #{plannedEndTime,jdbcType=BIGINT},
#{actualStartTime,jdbcType=BIGINT}, #{creator,jdbcType=VARCHAR}, #{apiIds,jdbcType=VARCHAR},
#{scenarioIds,jdbcType=VARCHAR}, #{tags,jdbcType=LONGVARCHAR})
#{actualStartTime,jdbcType=BIGINT}, #{creator,jdbcType=VARCHAR}, #{tags,jdbcType=LONGVARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.TestPlan">
insert into test_plan
@ -209,12 +207,6 @@
<if test="creator != null">
creator,
</if>
<if test="apiIds != null">
api_ids,
</if>
<if test="scenarioIds != null">
scenario_ids,
</if>
<if test="tags != null">
tags,
</if>
@ -271,12 +263,6 @@
<if test="creator != null">
#{creator,jdbcType=VARCHAR},
</if>
<if test="apiIds != null">
#{apiIds,jdbcType=VARCHAR},
</if>
<if test="scenarioIds != null">
#{scenarioIds,jdbcType=VARCHAR},
</if>
<if test="tags != null">
#{tags,jdbcType=LONGVARCHAR},
</if>
@ -342,12 +328,6 @@
<if test="record.creator != null">
creator = #{record.creator,jdbcType=VARCHAR},
</if>
<if test="record.apiIds != null">
api_ids = #{record.apiIds,jdbcType=VARCHAR},
</if>
<if test="record.scenarioIds != null">
scenario_ids = #{record.scenarioIds,jdbcType=VARCHAR},
</if>
<if test="record.tags != null">
tags = #{record.tags,jdbcType=LONGVARCHAR},
</if>
@ -375,8 +355,6 @@
planned_end_time = #{record.plannedEndTime,jdbcType=BIGINT},
actual_start_time = #{record.actualStartTime,jdbcType=BIGINT},
creator = #{record.creator,jdbcType=VARCHAR},
api_ids = #{record.apiIds,jdbcType=VARCHAR},
scenario_ids = #{record.scenarioIds,jdbcType=VARCHAR},
tags = #{record.tags,jdbcType=LONGVARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@ -400,9 +378,7 @@
planned_start_time = #{record.plannedStartTime,jdbcType=BIGINT},
planned_end_time = #{record.plannedEndTime,jdbcType=BIGINT},
actual_start_time = #{record.actualStartTime,jdbcType=BIGINT},
creator = #{record.creator,jdbcType=VARCHAR},
api_ids = #{record.apiIds,jdbcType=VARCHAR},
scenario_ids = #{record.scenarioIds,jdbcType=VARCHAR}
creator = #{record.creator,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -458,12 +434,6 @@
<if test="creator != null">
creator = #{creator,jdbcType=VARCHAR},
</if>
<if test="apiIds != null">
api_ids = #{apiIds,jdbcType=VARCHAR},
</if>
<if test="scenarioIds != null">
scenario_ids = #{scenarioIds,jdbcType=VARCHAR},
</if>
<if test="tags != null">
tags = #{tags,jdbcType=LONGVARCHAR},
</if>
@ -488,8 +458,6 @@
planned_end_time = #{plannedEndTime,jdbcType=BIGINT},
actual_start_time = #{actualStartTime,jdbcType=BIGINT},
creator = #{creator,jdbcType=VARCHAR},
api_ids = #{apiIds,jdbcType=VARCHAR},
scenario_ids = #{scenarioIds,jdbcType=VARCHAR},
tags = #{tags,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
@ -510,9 +478,7 @@
planned_start_time = #{plannedStartTime,jdbcType=BIGINT},
planned_end_time = #{plannedEndTime,jdbcType=BIGINT},
actual_start_time = #{actualStartTime,jdbcType=BIGINT},
creator = #{creator,jdbcType=VARCHAR},
api_ids = #{apiIds,jdbcType=VARCHAR},
scenario_ids = #{scenarioIds,jdbcType=VARCHAR}
creator = #{creator,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -50,12 +50,20 @@
) caseErrorCountData ON caseErrorCountData.testCaseID =testCase.testCaseID
WHERE caseErrorCountData.executeTime >= #{startTimestamp}
UNION
SELECT scene.`name` AS caseName,testPlan.`name` AS testPlan,count(report.id) AS failureTimes,'scenario' AS caseType
SELECT scene.`name` AS caseName,apiScene.testPlanName AS testPlan,count(report.id) AS failureTimes,'scenario' AS caseType
FROM api_scenario_report report
INNER JOIN api_scenario_report_detail reportDetail ON report.id = reportDetail.report_id
INNER JOIN api_scenario scene ON reportDetail.content like concat('%"',scene.`name`,'"%')
LEFT JOIN test_plan_api_scenario apiScene ON apiScene.api_scenario_id = scene.id
LEFT JOIN test_plan testPlan ON testPlan.id = apiScene.test_plan_id
INNER JOIN api_scenario scene ON reportDetail.content like concat('%"', scene.`name`,'"%')
LEFT JOIN
(
SELECT
apiScene.api_scenario_id,
group_concat(testPlan.`name`) AS testPlanName
FROM
test_plan_api_scenario apiScene
INNER JOIN test_plan testPlan ON testPlan.id = apiScene.test_plan_id
GROUP BY apiScene.api_scenario_id
)apiScene ON apiScene.api_scenario_id = scene.id
WHERE report.project_id = #{projectId}
AND report.status = 'Error' AND report.create_time >= #{startTimestamp}
GROUP BY scene.id

View File

@ -100,7 +100,7 @@
<select id="list" resultMap="BaseResultMap">
SELECT r.name AS test_name,
r.name, r.description, r.id, r.project_id, r.create_time, r.update_time, r.status, r.trigger_mode,
r.name, r.description, r.id, r.project_id, r.create_time, r.update_time, r.status, r.trigger_mode,r.scenario_name,
project.name AS project_name, user.name AS user_name
FROM api_scenario_report r
LEFT JOIN project ON project.id = r.project_id
@ -179,8 +179,8 @@
SELECT count(acr.report_id) AS countNumber FROM api_scenario_report_detail acr
INNER JOIN api_scenario_report ar ON ar.id = acr.report_id
INNER JOIN (
SELECT acitem.id FROM api_scenario acitem INNER JOIN `schedule` sc ON acitem.id = sc.resource_id
) ac on acr.content like CONCAT('%', ac.id,'%')
SELECT acitem.`name` FROM api_scenario acitem INNER JOIN `schedule` sc ON acitem.id = sc.resource_id
) ac on acr.content like CONCAT('%"', ac.`name`,'"%')
WHERE acr.project_id = #{projectId} AND ar.create_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp}
</select>
@ -189,8 +189,8 @@
FROM api_scenario_report_detail acr
INNER JOIN api_scenario_report ar ON ar.id = acr.report_id
INNER JOIN (
SELECT acitem.id FROM api_scenario acitem INNER JOIN `schedule` sc ON acitem.id = sc.resource_id
) ac on acr.content like CONCAT('%', ac.id,'%')
SELECT acitem.`name` FROM api_scenario acitem INNER JOIN `schedule` sc ON acitem.id = sc.resource_id
) ac on acr.content like CONCAT('%"', ac.`name`,'"%')
WHERE acr.project_id = #{projectId}
</select>
</mapper>

View File

@ -4,10 +4,13 @@ import io.metersphere.api.dto.datacount.ApiDataCountResult;
import io.metersphere.api.dto.definition.ApiTestCaseDTO;
import io.metersphere.api.dto.definition.ApiTestCaseRequest;
import io.metersphere.api.dto.definition.ApiTestCaseResult;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface ExtApiTestCaseMapper {
@ -20,4 +23,6 @@ public interface ExtApiTestCaseMapper {
List<ApiDataCountResult> countProtocolByProjectID(String projectId);
long countByProjectIDAndCreateInThisWeek(@Param("projectId") String projectId, @Param("firstDayTimestamp") long firstDayTimestamp, @Param("lastDayTimestamp") long lastDayTimestamp);
List<ApiTestCaseWithBLOBs> getRequest(@Param("request") ApiTestCaseRequest request);
}

View File

@ -290,5 +290,20 @@
AND testCase.create_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp}
</select>
<select id="getRequest" resultType="io.metersphere.base.domain.ApiTestCaseWithBLOBs">
select id, request
from api_test_case
where 1
<if test="request.id != null and request.id!=''">
and id = #{request.id}
</if>
<if test="request.ids != null and request.ids.size() > 0">
and id in
<foreach collection="request.ids" item="caseId" separator="," open="(" close=")">
#{caseId}
</foreach>
</if>
</select>
</mapper>

View File

@ -160,7 +160,6 @@
WHERE sch.resource_id IN (
SELECT id FROM api_test WHERE project_id = #{projectId,jdbcType=VARCHAR}
)
AND `group` = #{group}
</select>
<select id="countByProjectIDAndCreateInThisWeek" resultType="java.lang.Long">

View File

@ -17,12 +17,9 @@ public interface ExtTestPlanMapper {
List<TestPlanDTO> selectByIds(@Param("list") List<String> ids);
int updatePlan(@Param("plan") TestPlanDTO plan);
List<TestPlanDTO> selectReference(@Param("request") QueryTestPlanRequest params);
/**
* 通过关联表(test_plan_api_case/test_plan_api_scenario)查询testPlan
*
* @param params
* @return
*/

View File

@ -182,21 +182,6 @@
order by test_plan.update_time desc
</select>
<update id="updatePlan" parameterType="io.metersphere.track.dto.TestPlanDTO">
update test_plan
<set>
<if test="plan.apiIds != null">
api_ids = #{plan.apiIds,jdbcType=VARCHAR}
</if>
<if test="plan.scenarioIds != null">
scenario_ids = #{plan.scenarioIds,jdbcType=VARCHAR}
</if>
</set>
<where>
id = #{plan.id}
</where>
</update>
<select id="selectByIds" resultMap="BaseResultMap" parameterType="java.util.List">
SELECT * FROM TEST_PLAN p where p.id in
<foreach collection="list" item="planId" open="(" close=")" separator=",">
@ -204,18 +189,6 @@
</foreach>
</select>
<select id="selectReference" resultMap="BaseResultMap" parameterType="io.metersphere.track.request.testcase.QueryTestPlanRequest">
SELECT * FROM TEST_PLAN p LEFT JOIN test_plan_project t ON t.test_plan_id=p.id
<where>
<if test="request.scenarioId != null">
AND p.scenario_ids like CONCAT('%', #{request.scenarioId},'%')
</if>
<if test="request.apiId != null">
AND p.api_ids like CONCAT('%', #{request.apiId},'%')
</if>
</where>
</select>
<select id="checkIsHave" resultType="int">
SELECT COUNT(1)
FROM test_plan_project, project
@ -231,6 +204,7 @@
<select id="selectTestPlanByRelevancy" resultMap="BaseResultMap" parameterType="io.metersphere.track.request.testcase.QueryTestPlanRequest">
SELECT * FROM TEST_PLAN p LEFT JOIN test_plan_project t ON t.test_plan_id=p.id
<where>
AND t.project_id = #{request.projectId}
<if test="request.scenarioId != null">
AND p.id IN (SELECT test_plan_id FROM test_plan_api_scenario WHERE api_scenario_id = #{request.scenarioId} )
</if>

View File

@ -41,6 +41,10 @@ public class DateUtils {
return dateFormat.format(timeStamp);
}
public static String getTimeStr(long timeStamp) {
SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_PATTERN);
return dateFormat.format(timeStamp);
}
public static Date dateSum (Date date,int countDays){

View File

@ -55,7 +55,7 @@ public class ApiScenarioTestJob extends MsScheduleJob {
request.setReportId(id);
request.setProjectId(projectID);
request.setTriggerMode(ReportTriggerMode.SCHEDULE.name());
request.setExecuteType(ExecuteType.Completed.name());
request.setExecuteType(ExecuteType.Saved.name());
request.setScenarioIds(this.scenarioIds);
request.setReportUserID(this.userId);

View File

@ -75,7 +75,7 @@ public class PerformanceTestController {
@RequestPart("request") SaveTestPlanRequest request,
@RequestPart(value = "file") List<MultipartFile> files
) {
checkPermissionService.checkReadOnlyUser();
checkPermissionService.checkProjectOwner(request.getProjectId());
return performanceTestService.save(request, files);
}
@ -84,7 +84,6 @@ public class PerformanceTestController {
@RequestPart("request") EditTestPlanRequest request,
@RequestPart(value = "file", required = false) List<MultipartFile> files
) {
checkPermissionService.checkReadOnlyUser();
checkPermissionService.checkPerformanceTestOwner(request.getId());
return performanceTestService.edit(request, files);
}
@ -115,7 +114,6 @@ public class PerformanceTestController {
@PostMapping("/delete")
public void delete(@RequestBody DeleteTestPlanRequest request) {
checkPermissionService.checkReadOnlyUser();
checkPermissionService.checkPerformanceTestOwner(request.getId());
performanceTestService.delete(request);
}

View File

@ -212,6 +212,8 @@ public class SystemParameterService {
public void saveBaseInfo(List<SystemParameter> parameters) {
SystemParameterExample example = new SystemParameterExample();
parameters.forEach(param -> {
// 去掉路径最后的 /
param.setParamValue(StringUtils.removeEnd(param.getParamValue(), "/"));
example.createCriteria().andParamKeyEqualTo(param.getParamKey());
if (systemParameterMapper.countByExample(example) > 0) {
systemParameterMapper.updateByPrimaryKey(param);

@ -1 +1 @@
Subproject commit 79343a2763b014355f91fc21b2356a95ae437973
Subproject commit 9f4a9bbf46fc1333dbcccea21f83e27e3ec10b1f

View File

@ -0,0 +1,4 @@
ALTER TABLE api_scenario_report ADD scenario_name varchar(255) NULL;
ALTER TABLE api_scenario_report ADD scenario_id varchar(100) NULL;
ALTER TABLE test_plan DROP COLUMN api_ids;
ALTER TABLE test_plan DROP COLUMN scenario_ids;

View File

@ -20,10 +20,8 @@
</el-table-column>
<el-table-column :label="$t('commons.name')" width="200" show-overflow-tooltip prop="name">
</el-table-column>
<!--
<el-table-column prop="testName" :label="$t('api_report.test_name')" width="200" show-overflow-tooltip/>
-->
<el-table-column prop="projectName" :label="$t('load_test.project_name')" width="150" show-overflow-tooltip/>
<el-table-column prop="scenarioName" :label="$t('api_test.automation.scenario_name')" width="150" show-overflow-tooltip/>
<el-table-column prop="userName" :label="$t('api_test.creator')" width="150" show-overflow-tooltip/>
<el-table-column prop="createTime" width="250" :label="$t('commons.create_time')" sortable>
<template v-slot:default="scope">
@ -69,7 +67,7 @@
import MsContainer from "../../../common/components/MsContainer";
import MsMainContainer from "../../../common/components/MsMainContainer";
import MsApiReportStatus from "./ApiReportStatus";
import {_filter, _sort,getCurrentProjectID} from "@/common/js/utils";
import {_filter, _sort, getCurrentProjectID} from "@/common/js/utils";
import MsTableOperatorButton from "../../../common/components/MsTableOperatorButton";
import ReportTriggerModeItem from "../../../common/tableItem/ReportTriggerModeItem";
import {REPORT_CONFIGS} from "../../../common/components/search/search-components";

View File

@ -1,6 +1,6 @@
<template>
<el-card class="card-content">
<div>
<el-card>
<div class="card-content">
<div class="ms-main-div" @click="showAll">
<el-row>
<el-col>
@ -14,28 +14,28 @@
<el-form :model="currentScenario" label-position="right" label-width="80px" size="small" :rules="rules" ref="currentScenario" style="margin-right: 20px">
<!-- 基础信息 -->
<el-row>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('commons.name')" prop="name">
<el-input class="ms-scenario-input" size="small" v-model="currentScenario.name"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('test_track.module.module')" prop="apiScenarioModuleId">
<el-select class="ms-scenario-input" size="small" v-model="currentScenario.apiScenarioModuleId">
<el-option v-for="item in moduleOptions" :key="item.id" :label="item.path" :value="item.id"/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('commons.status')" prop="status">
<el-select class="ms-scenario-input" size="small" v-model="currentScenario.status">
<el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.id"/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
</el-row>
<el-row>
<el-col :span="7">
<el-form-item :label="$t('api_test.definition.request.responsible')" prop="principal">
<el-select v-model="currentScenario.principal"
:placeholder="$t('api_test.definition.request.responsible')" filterable size="small"
@ -47,20 +47,16 @@
:value="item.id">
</el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('test_track.case.priority')" prop="level">
<el-select class="ms-scenario-input" size="small" v-model="currentScenario.level">
<el-option v-for="item in levels" :key="item.id" :label="item.label" :value="item.id"/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('api_test.automation.follow_people')" prop="followPeople">
<el-select v-model="currentScenario.followPeople"
:placeholder="$t('api_test.automation.follow_people')" filterable size="small"
@ -76,14 +72,13 @@
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-col :span="7">
<el-form-item label="Tag" prop="tags">
<ms-input-tag :currentScenario="currentScenario" ref="tag"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-col :span="7">
<el-form-item :label="$t('commons.description')" prop="description">
<el-input class="ms-http-textarea"
v-model="currentScenario.description"
@ -181,40 +176,33 @@
</div>
</el-col>
<!-- 按钮列表 -->
<div>
<el-col :span="3">
<vue-fab id="fab" mainBtnColor="#783887" :click-auto-close="false">
<fab-item
v-for="(item, index) in buttons"
:key="index"
:idx="getIdx(index)"
:title="item.title"
:title-bg-color="item.titleBgColor"
:title-color="item.titleColor"
:color="item.titleColor"
:icon="item.icon"
@clickItem="item.click"/>
</vue-fab>
</el-col>
</div>
<el-col :span="3">
<vue-fab id="fab" mainBtnColor="#783887" size="small" :global-options="globalOptions"
:click-auto-close="false" v-outside-click="outsideClick">
<fab-item
v-for="(item, index) in buttons"
:key="index"
:idx="getIdx(index)"
:title="item.title"
:title-bg-color="item.titleBgColor"
:title-color="item.titleColor"
:color="item.titleColor"
:icon="item.icon"
@clickItem="item.click"/>
</vue-fab>
</el-col>
</el-row>
</div>
<!--接口列表-->
<el-drawer :visible.sync="apiListVisible" :destroy-on-close="true" direction="ltr" :withHeader="false" :modal="false" size="90%">
<ms-api-definition :visible="visibleRef" :currentRow="currentRow"/>
<el-button style="float: right;margin: 0px 20px 0px" type="primary" @click="pushApiOrCase('REF')">{{$t('api_test.scenario.reference')}}</el-button>
<el-button style="float: right;" type="primary" @click="pushApiOrCase('Copy')">{{ $t('commons.copy') }}</el-button>
</el-drawer>
<scenario-api-relevance @save="pushApiOrCase" ref="scenarioApiRelevance"/>
<!--自定义接口-->
<el-drawer :visible.sync="customizeVisible" :destroy-on-close="true" direction="ltr" :withHeader="false" :title="$t('api_test.automation.customize_req')" style="overflow: auto" :modal="false" size="90%">
<ms-api-customize :request="customizeRequest" @addCustomizeApi="addCustomizeApi"/>
</el-drawer>
<!--场景导入 -->
<el-drawer :visible.sync="scenarioVisible" :destroy-on-close="true" direction="ltr" :withHeader="false" :title="$t('api_test.automation.scenario_import')" style="overflow: auto" :modal="false" size="90%">
<ms-import-api-scenario @addScenario="addScenario"/>
</el-drawer>
<scenario-relevance @save="addScenario" ref="scenarioRelevance"/>
<!-- 环境 -->
<api-environment-config ref="environmentConfig" @close="environmentConfigClose"/>
@ -245,7 +233,6 @@
import MsIfController from "./IfController";
import MsApiAssertions from "../../definition/components/assertion/ApiAssertions";
import MsApiExtract from "../../definition/components/extract/ApiExtract";
import MsApiDefinition from "./api/ApiDefinition";
import MsApiComponent from "./ApiComponent";
import {ELEMENTS, ELEMENT_TYPE} from "./Setting";
import MsApiCustomize from "./ApiCustomize";
@ -260,6 +247,9 @@
import ApiImport from "../../definition/components/import/ApiImport";
import InputTag from 'vue-input-tag'
import "@/common/css/material-icons.css"
import OutsideClick from "@/common/js/outside-click";
import ScenarioApiRelevance from "./api/ScenarioApiRelevance";
import ScenarioRelevance from "./api/ScenarioRelevance";
export default {
name: "EditApiScenario",
@ -268,18 +258,18 @@
currentScenario: {},
},
components: {
ScenarioRelevance,
ScenarioApiRelevance,
ApiEnvironmentConfig,
MsScenarioParameters,
MsApiReportDetail,
MsInputTag, MsRun,
MsApiScenarioComponent,
MsImportApiScenario,
MsJsr233Processor,
MsConstantTimer,
MsIfController,
MsApiAssertions,
MsApiExtract,
MsApiDefinition,
MsApiComponent,
MsApiCustomize,
ApiImport,
@ -323,8 +313,10 @@
debugData: {},
reportId: "",
projectId: "",
visibleRef: "",
enableCookieShare: false,
globalOptions: {
spacing: 30
}
}
}
,
@ -340,6 +332,7 @@
,
watch: {}
,
directives: {OutsideClick},
computed: {
buttons() {
let buttons = [
@ -447,7 +440,7 @@
},
methods: {
getIdx(index) {
return -1 * index - 2.25; //
return index - 0.33
},
showButton(...names) {
for (const name of names) {
@ -457,6 +450,9 @@
}
return false;
},
outsideClick() {
this.operatingElements = ELEMENTS.get("ALL");
},
addComponent(type) {
switch (type) {
case ELEMENT_TYPE.IfController:
@ -492,7 +488,8 @@
this.customizeVisible = true;
break;
case ELEMENT_TYPE.scenario:
this.scenarioVisible = true;
// this.scenarioVisible = true;
this.$refs.scenarioRelevance.open();
break;
default:
this.$refs.apiImport.open();
@ -518,8 +515,7 @@
}
,
apiListImport() {
this.visibleRef = getUUID();
this.apiListVisible = true;
this.$refs.scenarioApiRelevance.open();
}
,
recursiveSorting(arr) {
@ -551,8 +547,7 @@
this.customizeRequest = {};
this.sort();
this.reload();
}
,
},
addScenario(arr) {
if (arr && arr.length > 0) {
arr.forEach(item => {
@ -567,8 +562,7 @@
this.sort();
this.reload();
this.scenarioVisible = false;
}
,
},
setApiParameter(item, refType, referenced) {
let request = {};
if (Object.prototype.toString.call(item.request).indexOf("String") > 0) {
@ -599,20 +593,10 @@
}
}
,
pushApiOrCase(referenced) {
if (this.currentRow.cases.length === 0 && this.currentRow.apis.length === 0) {
this.$warning(this.$t('api_test.automation.reference_info'));
return;
}
this.currentRow.cases.forEach(item => {
this.setApiParameter(item, "CASE", referenced);
})
this.currentRow.apis.forEach(item => {
this.setApiParameter(item, "API", referenced);
})
this.apiListVisible = false;
this.currentRow.cases = [];
this.currentRow.apis = [];
pushApiOrCase(data, refType, referenced) {
data.forEach(item => {
this.setApiParameter(item, refType, referenced);
});
this.sort();
this.reload();
}
@ -896,6 +880,10 @@
</script>
<style scoped>
.card-content {
height: calc(100vh - 196px);
overflow-y: auto;
}
.ms-scenario-input {
width: 100%;
}
@ -910,10 +898,9 @@
}
.ms-debug-div {
margin-left: 20px;
border: 1px #DCDFE6 solid;
border-radius: 4px;
margin-right: 10px;
margin-right: 20px;
}
.ms-scenario-button {
@ -946,7 +933,6 @@
}
#fab {
bottom: unset;
right: 90px;
z-index: 5;
}

View File

@ -0,0 +1,132 @@
<template>
<el-dialog class="api-relevance" :title="$t('test_track.plan_view.relevance_test_case')"
:visible.sync="dialogVisible"
width="60%"
:close-on-click-modal="false"
top="50px">
<ms-container>
<ms-aside-container :enable-aside-hidden="false">
<ms-api-module
@nodeSelectEvent="nodeChange"
@protocolChange="handleProtocolChange"
@refreshTable="refresh"
@setModuleOptions="setModuleOptions"
:is-read-only="true"
ref="nodeTree"/>
</ms-aside-container>
<ms-main-container>
<scenario-relevance-api-list
v-if="isApiListEnable"
:current-protocol="currentProtocol"
:select-node-ids="selectNodeIds"
:is-api-list-enable="isApiListEnable"
@isApiListEnableChange="isApiListEnableChange"
ref="apiList"
/>
<scenario-relevance-case-list
v-if="!isApiListEnable"
:current-protocol="currentProtocol"
:select-node-ids="selectNodeIds"
:is-api-list-enable="isApiListEnable"
@isApiListEnableChange="isApiListEnableChange"
ref="apiCaseList"/>
</ms-main-container>
</ms-container>
<template v-slot:footer>
<el-button type="primary" @click="copy" @keydown.enter.native.prevent>复制</el-button>
<el-button v-if="!isApiListEnable" type="primary" @click="reference" @keydown.enter.native.prevent>引用</el-button>
</template>
</el-dialog>
</template>
<script>
import ScenarioRelevanceCaseList from "./ScenarioRelevanceCaseList";
import MsApiModule from "../../../definition/components/module/ApiModule";
import MsContainer from "../../../../common/components/MsContainer";
import MsAsideContainer from "../../../../common/components/MsAsideContainer";
import MsMainContainer from "../../../../common/components/MsMainContainer";
import ScenarioRelevanceApiList from "./ScenarioRelevanceApiList";
export default {
name: "ScenarioApiRelevance",
components: {
ScenarioRelevanceApiList,
MsMainContainer, MsAsideContainer, MsContainer, MsApiModule, ScenarioRelevanceCaseList},
data() {
return {
dialogVisible: false,
result: {},
currentProtocol: null,
selectNodeIds: [],
moduleOptions: {},
isApiListEnable: true,
}
},
methods: {
reference() {
this.save('REF');
},
copy() {
this.save('Copy');
},
save(reference) {
if (this.isApiListEnable) {
this.$emit('save', this.$refs.apiList.selectRows, 'API', reference);
this.close();
} else {
let apiCases = this.$refs.apiCaseList.selectRows;
let ids = Array.from(apiCases).map(row => row.id);
this.result = this.$post("/api/testcase/get/request", {ids: ids}, (response) => {
apiCases.forEach((item) => {
item.request = response.data[item.id];
});
this.$emit('save', apiCases, 'CASE', reference);
this.close();
});
}
},
close() {
this.refresh();
this.dialogVisible = false;
},
open() {
this.dialogVisible = true;
},
isApiListEnableChange(data) {
this.isApiListEnable = data;
},
nodeChange(node, nodeIds, pNodes) {
this.selectNodeIds = nodeIds;
},
handleProtocolChange(protocol) {
this.currentProtocol = protocol;
},
setModuleOptions(data) {
this.moduleOptions = data;
},
refresh() {
if (this.isApiListEnable) {
this.$refs.apiList.initTable();
} else {
this.$refs.apiCaseList.initTable();
}
},
}
}
</script>
<style scoped>
.ms-aside-container {
border: 0px;
}
.api-relevance >>> .el-dialog__body {
padding: 10px 20px;
}
</style>

View File

@ -0,0 +1,138 @@
<template>
<el-dialog class="api-relevance" :title="$t('test_track.plan_view.relevance_test_case')"
:visible.sync="dialogVisible"
width="60%"
:close-on-click-modal="false"
top="50px">
<ms-container>
<ms-aside-container :enable-aside-hidden="false">
<ms-api-scenario-module
@nodeSelectEvent="nodeChange"
@refreshTable="refresh"
@setModuleOptions="setModuleOptions"
@enableTrash="false"
:is-read-only="true"
ref="nodeTree"/>
</ms-aside-container>
<ms-main-container>
<ms-api-scenario-list
:select-node-ids="selectNodeIds"
:referenced="true"
:trash-enable="false"
@selection="setData"
ref="apiScenarioList"/>
</ms-main-container>
</ms-container>
<template v-slot:footer>
<el-button type="primary" @click="copy" @keydown.enter.native.prevent>复制</el-button>
<el-button type="primary" @click="reference" @keydown.enter.native.prevent>引用</el-button>
</template>
</el-dialog>
</template>
<script>
import ScenarioRelevanceCaseList from "./ScenarioRelevanceCaseList";
import MsApiModule from "../../../definition/components/module/ApiModule";
import MsContainer from "../../../../common/components/MsContainer";
import MsAsideContainer from "../../../../common/components/MsAsideContainer";
import MsMainContainer from "../../../../common/components/MsMainContainer";
import ScenarioRelevanceApiList from "./ScenarioRelevanceApiList";
import MsApiScenarioModule from "../ApiScenarioModule";
import MsApiScenarioList from "../ApiScenarioList";
import {getUUID} from "../../../../../../common/js/utils";
export default {
name: "ScenarioRelevance",
components: {
MsApiScenarioList,
MsApiScenarioModule,
MsMainContainer, MsAsideContainer, MsContainer},
data() {
return {
dialogVisible: false,
result: {},
currentProtocol: null,
selectNodeIds: [],
moduleOptions: {},
isApiListEnable: true,
currentScenario: [],
currentScenarioIds: [],
}
},
methods: {
reference() {
let scenarios = [];
if (!this.currentScenario || this.currentScenario.length < 1) {
this.$emit('请选择场景');
return;
}
this.currentScenario.forEach(item => {
let obj = {id: item.id, name: item.name, type: "scenario", referenced: 'REF', resourceId: getUUID()};
scenarios.push(obj);
});
this.$emit('save', scenarios);
this.close();
},
copy() {
let scenarios = [];
if (!this.currentScenarioIds || this.currentScenarioIds.length < 1) {
this.$emit('请选择场景');
return;
}
this.result = this.$post("/api/automation/getApiScenarios/", this.currentScenarioIds, response => {
if (response.data) {
response.data.forEach(item => {
let scenarioDefinition = JSON.parse(item.scenarioDefinition);
let obj = {id: item.id, name: item.name, type: "scenario", referenced: 'Copy', resourceId: getUUID(), hashTree: scenarioDefinition.hashTree};
scenarios.push(obj);
});
this.$emit('save', scenarios);
this.close();
}
})
},
close() {
this.refresh();
this.dialogVisible = false;
},
open() {
this.dialogVisible = true;
if (this.$refs.apiScenarioList) {
this.$refs.apiScenarioList.search();
}
},
nodeChange(node, nodeIds, pNodes) {
this.selectNodeIds = nodeIds;
},
handleProtocolChange(protocol) {
this.currentProtocol = protocol;
},
setModuleOptions(data) {
this.moduleOptions = data;
},
refresh() {
this.$refs.apiScenarioList.search();
},
setData(data) {
this.currentScenario = Array.from(data).map(row => row);
this.currentScenarioIds = Array.from(data).map(row => row.id);
},
}
}
</script>
<style scoped>
.ms-aside-container {
border: 0px;
}
.api-relevance >>> .el-dialog__body {
padding: 10px 20px;
}
</style>

View File

@ -0,0 +1,248 @@
<template>
<api-list-container
:is-api-list-enable="isApiListEnable"
@isApiListEnableChange="isApiListEnableChange">
<el-input placeholder="搜索" @blur="initTable" class="search-input" size="small" @keyup.enter.native="initTable" v-model="condition.name"/>
<el-table v-loading="result.loading"
border
:data="tableData" row-key="id" class="test-content adjust-table"
@select-all="handleSelectAll"
@select="handleSelect">
<el-table-column type="selection"/>
<el-table-column prop="name" :label="$t('api_test.definition.api_name')" show-overflow-tooltip/>
<el-table-column
prop="status"
column-key="api_status"
:label="$t('api_test.definition.api_status')"
show-overflow-tooltip>
<template v-slot:default="scope">
<ms-tag v-if="scope.row.status == 'Prepare'" type="info" effect="plain" :content="$t('test_track.plan.plan_status_prepare')"/>
<ms-tag v-if="scope.row.status == 'Underway'" type="warning" effect="plain" :content="$t('test_track.plan.plan_status_running')"/>
<ms-tag v-if="scope.row.status == 'Completed'" type="success" effect="plain" :content="$t('test_track.plan.plan_status_completed')"/>
<ms-tag v-if="scope.row.status == 'Trash'" type="danger" effect="plain" content="废弃"/>
</template>
</el-table-column>
<el-table-column
prop="method"
:label="$t('api_test.definition.api_type')"
show-overflow-tooltip>
<template v-slot:default="scope" class="request-method">
<el-tag size="mini" :style="{'background-color': getColor(scope.row.method), border: getColor(true, scope.row.method)}" class="api-el-tag">
{{ scope.row.method}}
</el-tag>
</template>
</el-table-column>
<el-table-column
prop="path"
:label="$t('api_test.definition.api_path')"
show-overflow-tooltip/>
<el-table-column
prop="userName"
:label="$t('api_test.definition.api_principal')"
show-overflow-tooltip/>
<el-table-column width="160" :label="$t('api_test.definition.api_last_time')" prop="updateTime">
<template v-slot:default="scope">
<span>{{ scope.row.updateTime | timestampFormatDate }}</span>
</template>
</el-table-column>
<el-table-column
prop="caseTotal"
:label="$t('api_test.definition.api_case_number')"
show-overflow-tooltip/>
<el-table-column
prop="caseStatus"
:label="$t('api_test.definition.api_case_status')"
show-overflow-tooltip/>
<el-table-column
prop="casePassingRate"
:label="$t('api_test.definition.api_case_passing_rate')"
show-overflow-tooltip/>
</el-table>
<ms-table-pagination :change="initTable" :current-page.sync="currentPage" :page-size.sync="pageSize"
:total="total"/>
</api-list-container>
</template>
<script>
import MsTableOperator from "../../../../common/components/MsTableOperator";
import MsTableOperatorButton from "../../../../common/components/MsTableOperatorButton";
import {LIST_CHANGE, TrackEvent} from "@/business/components/common/head/ListEvent";
import MsTablePagination from "../../../../common/pagination/TablePagination";
import MsTag from "../../../../common/components/MsTag";
import MsBottomContainer from "../../../definition/components/BottomContainer";
import ShowMoreBtn from "../../../../track/case/components/ShowMoreBtn";
import MsBatchEdit from "../../../definition/components/basis/BatchEdit";
import {API_METHOD_COLOUR, CASE_PRIORITY} from "../../../definition/model/JsonData";
import {getCurrentProjectID} from "@/common/js/utils";
import ApiListContainer from "../../../definition/components/list/ApiListContainer";
import PriorityTableItem from "../../../../track/common/tableItems/planview/PriorityTableItem";
import {_filter, _sort} from "../../../../../../common/js/utils";
import {_handleSelect, _handleSelectAll} from "../../../../../../common/js/tableUtils";
export default {
name: "ScenarioRelevanceApiList",
components: {
PriorityTableItem,
ApiListContainer,
MsTableOperatorButton,
MsTableOperator,
MsTablePagination,
MsTag,
MsBottomContainer,
ShowMoreBtn,
MsBatchEdit
},
data() {
return {
condition: {},
selectCase: {},
result: {},
moduleId: "",
deletePath: "/test/case/delete",
selectRows: new Set(),
typeArr: [
{id: 'priority', name: this.$t('test_track.case.priority')},
],
priorityFilters: [
{text: 'P0', value: 'P0'},
{text: 'P1', value: 'P1'},
{text: 'P2', value: 'P2'},
{text: 'P3', value: 'P3'}
],
valueArr: {
priority: CASE_PRIORITY,
},
methodColorMap: new Map(API_METHOD_COLOUR),
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0,
}
},
props: {
currentProtocol: String,
selectNodeIds: Array,
visible: {
type: Boolean,
default: false,
},
isApiListEnable: {
type: Boolean,
default: false,
},
isReadOnly: {
type: Boolean,
default: false
},
isCaseRelevance: {
type: Boolean,
default: false,
},
relevanceProjectId: String,
planId: String
},
created: function () {
this.initTable();
},
watch: {
selectNodeIds() {
this.initTable();
},
currentProtocol() {
this.initTable();
},
},
computed: {
},
methods: {
isApiListEnableChange(data) {
this.$emit('isApiListEnableChange', data);
},
initTable() {
this.selectRows = new Set();
this.condition.filters = ["Prepare", "Underway", "Completed"];
this.condition.moduleIds = this.selectNodeIds;
if (this.trashEnable) {
this.condition.filters = ["Trash"];
this.condition.moduleIds = [];
}
if (this.projectId != null) {
this.condition.projectId = this.projectId;
}
if (this.currentProtocol != null) {
this.condition.protocol = this.currentProtocol;
}
this.result = this.$post("/api/definition/list/" + this.currentPage + "/" + this.pageSize, this.condition, response => {
this.total = response.data.itemCount;
this.tableData = response.data.listObject;
});
},
handleSelect(selection, row) {
_handleSelect(this, selection, row, this.selectRows);
},
showExecResult(row) {
this.visible = false;
this.$emit('showExecResult', row);
},
filter(filters) {
_filter(filters, this.condition);
this.initTable();
},
sort(column) {
//
if (this.condition.orders) {
this.condition.orders = [];
}
_sort(column, this.condition);
this.initTable();
},
handleSelectAll(selection) {
_handleSelectAll(this, selection, this.tableData, this.selectRows);
},
buildPagePath(path) {
return path + "/" + this.currentPage + "/" + this.pageSize;
},
getColor(method) {
return this.methodColorMap.get(method);
},
},
}
</script>
<style scoped>
.operate-button > div {
display: inline-block;
margin-left: 10px;
}
.request-method {
padding: 0 5px;
color: #1E90FF;
}
.api-el-tag {
color: white;
}
.search-input {
float: right;
width: 300px;
/*margin-bottom: 20px;*/
margin-right: 20px;
}
</style>

View File

@ -0,0 +1,239 @@
<template>
<div>
<api-list-container
:is-api-list-enable="isApiListEnable"
@isApiListEnableChange="isApiListEnableChange">
<el-input placeholder="搜索" @blur="initTable" @keyup.enter.native="initTable" class="search-input" size="small" v-model="condition.name"/>
<el-table v-loading="result.loading"
border
:data="tableData" row-key="id" class="test-content adjust-table"
@select-all="handleSelectAll"
@filter-change="filter"
@sort-change="sort"
@select="handleSelect">
<el-table-column type="selection"/>
<el-table-column prop="name" :label="$t('api_test.definition.api_name')" show-overflow-tooltip/>
<el-table-column
prop="priority"
:filters="priorityFilters"
column-key="priority"
:label="$t('test_track.case.priority')"
show-overflow-tooltip>
<template v-slot:default="scope">
<priority-table-item :value="scope.row.priority"/>
</template>
</el-table-column>
<el-table-column
prop="path"
:label="$t('api_test.definition.api_path')"
show-overflow-tooltip/>
<el-table-column
prop="createUser"
:label="'创建人'"
show-overflow-tooltip/>
<el-table-column
sortable="custom"
width="160"
:label="$t('api_test.definition.api_last_time')"
prop="updateTime">
<template v-slot:default="scope">
<span>{{ scope.row.updateTime | timestampFormatDate }}</span>
</template>
</el-table-column>
</el-table>
<ms-table-pagination :change="initTable" :current-page.sync="currentPage" :page-size.sync="pageSize"
:total="total"/>
</api-list-container>
</div>
</template>
<script>
import MsTableOperator from "../../../../common/components/MsTableOperator";
import MsTableOperatorButton from "../../../../common/components/MsTableOperatorButton";
import {LIST_CHANGE, TrackEvent} from "@/business/components/common/head/ListEvent";
import MsTablePagination from "../../../../common/pagination/TablePagination";
import MsTag from "../../../../common/components/MsTag";
import MsBottomContainer from "../../../definition/components/BottomContainer";
import ShowMoreBtn from "../../../../track/case/components/ShowMoreBtn";
import MsBatchEdit from "../../../definition/components/basis/BatchEdit";
import {API_METHOD_COLOUR, CASE_PRIORITY} from "../../../definition/model/JsonData";
import {getCurrentProjectID} from "@/common/js/utils";
import ApiListContainer from "../../../definition/components/list/ApiListContainer";
import PriorityTableItem from "../../../../track/common/tableItems/planview/PriorityTableItem";
import {_filter, _sort} from "../../../../../../common/js/utils";
import {_handleSelect, _handleSelectAll} from "../../../../../../common/js/tableUtils";
export default {
name: "ScenarioRelevanceCaseList",
components: {
PriorityTableItem,
ApiListContainer,
MsTableOperatorButton,
MsTableOperator,
MsTablePagination,
MsTag,
MsBottomContainer,
ShowMoreBtn,
MsBatchEdit
},
data() {
return {
condition: {},
selectCase: {},
result: {},
moduleId: "",
selectRows: new Set(),
typeArr: [
{id: 'priority', name: this.$t('test_track.case.priority')},
],
priorityFilters: [
{text: 'P0', value: 'P0'},
{text: 'P1', value: 'P1'},
{text: 'P2', value: 'P2'},
{text: 'P3', value: 'P3'}
],
valueArr: {
priority: CASE_PRIORITY,
},
methodColorMap: new Map(API_METHOD_COLOUR),
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0,
}
},
props: {
currentProtocol: String,
selectNodeIds: Array,
visible: {
type: Boolean,
default: false,
},
isApiListEnable: {
type: Boolean,
default: false,
},
isReadOnly: {
type: Boolean,
default: false
},
isCaseRelevance: {
type: Boolean,
default: false,
},
relevanceProjectId: String,
planId: String
},
created: function () {
this.initTable();
},
watch: {
selectNodeIds() {
this.initTable();
},
currentProtocol() {
this.initTable();
},
},
computed: {
},
methods: {
isApiListEnableChange(data) {
this.$emit('isApiListEnableChange', data);
},
initTable() {
this.selectRows = new Set();
this.condition.status = "";
this.condition.moduleIds = this.selectNodeIds;
if (this.currentProtocol != null) {
this.condition.protocol = this.currentProtocol;
}
this.condition.projectId = getCurrentProjectID();
this.result = this.$post("/api/testcase/list/" + this.currentPage + "/" + this.pageSize, this.condition, response => {
this.total = response.data.itemCount;
this.tableData = response.data.listObject;
});
},
handleSelect(selection, row) {
_handleSelect(this, selection, row, this.selectRows);
},
showExecResult(row) {
this.visible = false;
this.$emit('showExecResult', row);
},
filter(filters) {
_filter(filters, this.condition);
this.initTable();
},
sort(column) {
//
if (this.condition.orders) {
this.condition.orders = [];
}
_sort(column, this.condition);
this.initTable();
},
handleSelectAll(selection) {
_handleSelectAll(this, selection, this.tableData, this.selectRows);
},
buildPagePath(path) {
return path + "/" + this.currentPage + "/" + this.pageSize;
},
handleTestCase(testCase) {
this.$get('/api/definition/get/' + testCase.apiDefinitionId, (response) => {
let api = response.data;
let selectApi = api;
let request = {};
if (Object.prototype.toString.call(api.request).match(/\[object (\w+)\]/)[1].toLowerCase() === 'object') {
request = api.request;
} else {
request = JSON.parse(api.request);
}
if (!request.hashTree) {
request.hashTree = [];
}
selectApi.url = request.path;
this.$refs.caseList.open(selectApi, testCase.id);
});
},
},
}
</script>
<style scoped>
.operate-button > div {
display: inline-block;
margin-left: 10px;
}
.request-method {
padding: 0 5px;
color: #1E90FF;
}
.api-el-tag {
color: white;
}
.search-input {
float: right;
width: 300px;
/*margin-bottom: 20px;*/
margin-right: 20px;
}
</style>

View File

@ -273,7 +273,7 @@
} else if (this.isRelevanceModel) {
return '/api/testcase/delete/' + apiCase.id;
} else {
return '/api/testcase/delete/' + +apiCase.id;
return '/api/testcase/delete/' + apiCase.id;
}
},
// getMaintainerOptions() {

View File

@ -112,8 +112,8 @@ export default {
threadGroups: [],
}
},
mounted() {
// this.getJmxContent();
activated() {
this.getJmxContent();
},
methods: {
calculateLoadConfiguration: function (data) {

View File

@ -15,10 +15,6 @@
<ms-table-button :is-tester-permission="true" icon="el-icon-connection"
:content="$t('test_track.plan_view.relevance_test_case')"
@click="$emit('openTestCaseRelevanceDialog')"/>
<ms-table-button :is-tester-permission="true" v-if="!testPlan.reportId" icon="el-icon-document"
:content="$t('test_track.plan_view.create_report')" @click="openTestReport"/>
<ms-table-button :is-tester-permission="true" v-if="testPlan.reportId" icon="el-icon-document"
:content="$t('test_track.plan_view.view_report')" @click="openReport"/>
<ms-table-button :is-tester-permission="true" icon="el-icon-document-remove"
:content="$t('test_track.plan_view.cancel_all_relevance')" @click="handleDeleteBatch"/>
</template>
@ -204,8 +200,6 @@
:is-read-only="isReadOnly"
@refreshTable="search"/>
<test-report-template-list @openReport="openReport" ref="testReportTemplateList"/>
<test-case-report-view @refresh="initTableData" ref="testCaseReportView"/>
</el-card>
<batch-edit ref="batchEdit" @batchEdit="batchEdit"
:type-arr="typeArr" :value-arr="valueArr" :dialog-title="$t('test_track.case.batch_edit_case')"/>
@ -242,8 +236,6 @@ export default {
name: "FunctionalTestCaseList",
components: {
FunctionalTestCaseEdit,
TestCaseReportView,
TestReportTemplateList,
MsTableOperatorButton,
MsTableOperator,
MethodTableItem,
@ -522,9 +514,6 @@ export default {
}
this.initTableData();
},
openTestReport() {
this.$refs.testReportTemplateList.open(this.planId);
},
statusChange(param) {
this.$post('/test/plan/case/edit', param, () => {
for (let i = 0; i < this.tableData.length; i++) {
@ -543,16 +532,7 @@ export default {
});
}
},
openReport(planId, id) {
this.getTestPlanById();
if (!id) {
id = this.testPlan.reportId;
}
if (!planId) {
planId = this.planId;
}
this.$refs.testCaseReportView.open(planId, id);
},
filter(filters) {
_filter(filters, this.condition);
this.initTableData();

View File

@ -0,0 +1,31 @@
const OutsideClick = {
// 初始化指令
bind(el, binding, vnode) {
function documentHandler(e) {
// 这里判断点击的元素是否是本身,是本身,则返回
if (el.contains(e.target)) {
return false;
}
// 判断指令中是否绑定了函数
if (binding.expression) {
// 如果绑定了函数 则调用那个函数此处binding.value就是handleClose方法
binding.value(e);
}
}
// 给当前元素绑定个私有变量方便在unbind中可以解除事件监听
el.__vueClickOutside__ = documentHandler;
document.addEventListener('click', documentHandler);
},
update() {
},
unbind(el, binding) {
// 解除事件监听
document.removeEventListener('click', el.__vueClickOutside__);
delete el.__vueClickOutside__;
},
};
export default OutsideClick;