refactor(接口测试): 优化用例环境校验,提高执行速度

This commit is contained in:
fit2-zhao 2022-12-23 14:52:51 +08:00 committed by fit2-zhao
parent 7abc87b979
commit 9a27ac79d5
9 changed files with 81 additions and 299 deletions

View File

@ -65,6 +65,8 @@ public class ApiCaseExecuteService {
private TestPlanApiCaseMapper testPlanApiCaseMapper; private TestPlanApiCaseMapper testPlanApiCaseMapper;
@Resource @Resource
private JMeterService jMeterService; private JMeterService jMeterService;
@Resource
private BaseEnvironmentService baseEnvironmentService;
/** /**
* 测试计划case执行 * 测试计划case执行
@ -140,16 +142,13 @@ public class ApiCaseExecuteService {
// 开始选择执行模式 // 开始选择执行模式
if (deQueue != null && deQueue.getDetail() != null) { if (deQueue != null && deQueue.getDetail() != null) {
Thread thread = new Thread(new Runnable() { Thread thread = new Thread(() -> {
@Override
public void run() {
Thread.currentThread().setName("PLAN-CASE" + request.getPlanReportId()); Thread.currentThread().setName("PLAN-CASE" + request.getPlanReportId());
if (request.getConfig() != null && request.getConfig().getMode().equals(RunModeConstants.SERIAL.toString())) { if (request.getConfig() != null && request.getConfig().getMode().equals(RunModeConstants.SERIAL.toString())) {
apiCaseSerialService.serial(deQueue); apiCaseSerialService.serial(deQueue);
} else { } else {
apiCaseParallelExecuteService.parallel(executeQueue, request.getConfig(), deQueue, runMode); apiCaseParallelExecuteService.parallel(executeQueue, request.getConfig(), deQueue, runMode);
} }
}
}); });
thread.start(); thread.start();
} }
@ -166,100 +165,64 @@ public class ApiCaseExecuteService {
return testPlanApiCaseMapper.selectByExample(example); return testPlanApiCaseMapper.selectByExample(example);
} }
public Map<String, List<String>> checkEnv(List<ApiTestCaseWithBLOBs> caseList) { public Map<String, List<String>> getRequestEnv(List<ApiTestCaseWithBLOBs> caseList) {
Map<String, List<String>> projectEnvMap = new HashMap<>(); Map<String, List<String>> projectEnvMap = new HashMap<>();
if (CollectionUtils.isNotEmpty(caseList)) { if (CollectionUtils.isEmpty(caseList)) {
StringBuilder builderHttp = new StringBuilder(); return projectEnvMap;
StringBuilder builderTcp = new StringBuilder(); }
for (int i = caseList.size() - 1; i >= 0; i--) { StringBuilder message = new StringBuilder();
ApiTestCaseWithBLOBs apiCase = caseList.get(i); for (ApiTestCaseWithBLOBs apiCase : caseList) {
JSONObject apiCaseNew = new JSONObject(apiCase.getRequest()); JSONObject requestObj = new JSONObject(apiCase.getRequest());
if (apiCaseNew.has(PropertyConstant.TYPE) && ElementConstants.HTTP_SAMPLER.equals(apiCaseNew.optString(PropertyConstant.TYPE))) { if (StringUtils.equalsAny(requestObj.optString(PropertyConstant.TYPE), ElementConstants.HTTP_SAMPLER, ElementConstants.JDBC_SAMPLER)) {
if (!apiCaseNew.has("useEnvironment") || StringUtils.isEmpty(apiCaseNew.optString("useEnvironment"))) { Map<String, String> envMap = this.getEnvMap(requestObj, apiCase.getProjectId());
builderHttp.append(apiCase.getName()).append("; "); if (MapUtils.isEmpty(envMap)) {
message.append(apiCase.getName()).append("");
} else { } else {
//记录运行环境ID //记录运行环境ID
String envId = apiCaseNew.optString("useEnvironment"); this.setEnvId(projectEnvMap, apiCase.getProjectId(), envMap.get(apiCase.getProjectId()));
if (projectEnvMap.containsKey(apiCase.getProjectId())) {
if (!projectEnvMap.get(apiCase.getProjectId()).contains(envId)) {
projectEnvMap.get(apiCase.getProjectId()).add(envId);
}
} else {
projectEnvMap.put(apiCase.getProjectId(), new ArrayList<>() {{
this.add(envId);
}});
} }
} }
} }
if (apiCaseNew.has(PropertyConstant.TYPE) && ElementConstants.JDBC_SAMPLER.equals(apiCaseNew.optString(PropertyConstant.TYPE))) { if (StringUtils.isNotEmpty(message)) {
DatabaseConfig dataSource = null; MSException.throwException("用例:" + message + "运行环境为空!");
if (apiCaseNew.has("useEnvironment") && apiCaseNew.has("dataSourceId")) {
String environmentId = apiCaseNew.optString("useEnvironment");
String dataSourceId = apiCaseNew.optString("dataSourceId");
BaseEnvironmentService apiTestEnvironmentService = CommonBeanFactory.getBean(BaseEnvironmentService.class);
ApiTestEnvironmentWithBLOBs environment = apiTestEnvironmentService.get(environmentId);
EnvironmentConfig envConfig = null;
if (environment != null && environment.getConfig() != null) {
envConfig = JSON.parseObject(environment.getConfig(), EnvironmentConfig.class);
if (CollectionUtils.isNotEmpty(envConfig.getDatabaseConfigs())) {
for (DatabaseConfig item : envConfig.getDatabaseConfigs()) {
if (item.getId().equals(dataSourceId)) {
dataSource = item;
//记录运行环境ID
if (projectEnvMap.containsKey(apiCase.getProjectId())) {
if (!projectEnvMap.get(apiCase.getProjectId()).contains(environmentId)) {
projectEnvMap.get(apiCase.getProjectId()).add(environmentId);
}
} else {
projectEnvMap.put(apiCase.getProjectId(), new ArrayList<>() {{
this.add(environmentId);
}});
}
}
}
}
}
}
if (dataSource == null) {
builderTcp.append(apiCase.getName()).append("; ");
}
}
}
if (StringUtils.isNotEmpty(builderHttp)) {
MSException.throwException("用例:" + builderHttp + "运行环境为空!请检查");
}
if (StringUtils.isNotEmpty(builderTcp)) {
MSException.throwException("用例:" + builderTcp + "数据源为空!请检查");
}
} }
return projectEnvMap; return projectEnvMap;
} }
public Map<String, String> getEnvMap(ApiTestCaseWithBLOBs apiCase) { private void setEnvId(Map<String, List<String>> projectEnvMap, String projectId, String envId) {
Map<String, String> projectEnvMap = new HashMap<>();
JSONObject apiCaseNew = new JSONObject(apiCase.getRequest());
if (apiCaseNew.has(PropertyConstant.TYPE) && ElementConstants.HTTP_SAMPLER.equals(apiCaseNew.optString(PropertyConstant.TYPE))) {
if (apiCaseNew.has("useEnvironment") && StringUtils.isNotEmpty(apiCaseNew.optString("useEnvironment"))) {
//记录运行环境ID //记录运行环境ID
String envId = apiCaseNew.optString("useEnvironment"); if (projectEnvMap.containsKey(projectId)) {
projectEnvMap.put(apiCase.getProjectId(), envId); if (!projectEnvMap.get(projectId).contains(envId)) {
projectEnvMap.get(projectId).add(envId);
}
} else {
projectEnvMap.put(projectId, new ArrayList<>() {{
this.add(envId);
}});
} }
} }
if (apiCaseNew.has(PropertyConstant.TYPE) && ElementConstants.JDBC_SAMPLER.equals(apiCaseNew.optString(PropertyConstant.TYPE))) {
if (apiCaseNew.has("useEnvironment") && apiCaseNew.has("dataSourceId")) { public Map<String, String> getEnvMap(JSONObject request, String projectId) {
String environmentId = apiCaseNew.optString("useEnvironment"); Map<String, String> projectEnvMap = new HashMap<>();
String dataSourceId = apiCaseNew.optString("dataSourceId"); if (!request.has(PropertyConstant.TYPE)) {
BaseEnvironmentService apiTestEnvironmentService = CommonBeanFactory.getBean(BaseEnvironmentService.class); return projectEnvMap;
ApiTestEnvironmentWithBLOBs environment = apiTestEnvironmentService.get(environmentId); }
EnvironmentConfig envConfig = null; if (StringUtils.equals(ElementConstants.HTTP_SAMPLER, request.optString(PropertyConstant.TYPE))) {
if (StringUtils.isNotEmpty(request.optString(PropertyConstant.ENVIRONMENT))) {
//记录运行环境ID
projectEnvMap.put(projectId, request.optString(PropertyConstant.ENVIRONMENT));
}
}
if (StringUtils.equals(ElementConstants.JDBC_SAMPLER, request.optString(PropertyConstant.TYPE))) {
if (request.has(PropertyConstant.ENVIRONMENT) && request.has(PropertyConstant.DATASOURCE_ID)) {
ApiTestEnvironmentWithBLOBs environment = baseEnvironmentService.get(request.optString(PropertyConstant.ENVIRONMENT));
if (environment != null && environment.getConfig() != null) { if (environment != null && environment.getConfig() != null) {
envConfig = JSON.parseObject(environment.getConfig(), EnvironmentConfig.class); EnvironmentConfig envConfig = JSON.parseObject(environment.getConfig(), EnvironmentConfig.class);
if (CollectionUtils.isNotEmpty(envConfig.getDatabaseConfigs())) { if (CollectionUtils.isNotEmpty(envConfig.getDatabaseConfigs())) {
for (DatabaseConfig item : envConfig.getDatabaseConfigs()) { for (DatabaseConfig item : envConfig.getDatabaseConfigs()) {
if (item.getId().equals(dataSourceId)) { if (StringUtils.equals(item.getId(), request.optString(PropertyConstant.DATASOURCE_ID))) {
//记录运行环境ID //记录运行环境ID
projectEnvMap.put(apiCase.getProjectId(), environmentId); projectEnvMap.put(projectId, request.optString(PropertyConstant.ENVIRONMENT));
} }
} }
} }
@ -300,7 +263,7 @@ public class ApiCaseExecuteService {
Map<String, List<String>> testCaseEnvMap = new HashMap<>(); Map<String, List<String>> testCaseEnvMap = new HashMap<>();
// 环境检查 // 环境检查
if (MapUtils.isEmpty(request.getConfig().getEnvMap())) { if (MapUtils.isEmpty(request.getConfig().getEnvMap())) {
testCaseEnvMap = this.checkEnv(caseList); testCaseEnvMap = this.getRequestEnv(caseList);
} }
// 集合报告设置 // 集合报告设置
String serialReportId = request.isRerun() ? request.getReportId() : null; String serialReportId = request.isRerun() ? request.getReportId() : null;
@ -363,7 +326,8 @@ public class ApiCaseExecuteService {
BeanUtils.copyBean(config, request.getConfig()); BeanUtils.copyBean(config, request.getConfig());
if (StringUtils.equals(config.getEnvironmentType(), EnvironmentType.JSON.name()) && MapUtils.isEmpty(config.getEnvMap())) { if (StringUtils.equals(config.getEnvironmentType(), EnvironmentType.JSON.name()) && MapUtils.isEmpty(config.getEnvMap())) {
config.setEnvMap(this.getEnvMap(caseWithBLOBs)); JSONObject jsonObject = new JSONObject(caseWithBLOBs.getRequest());
config.setEnvMap(this.getEnvMap(jsonObject, caseWithBLOBs.getProjectId()));
} }
ApiDefinitionExecResultWithBLOBs report = ApiDefinitionExecResultUtil.initBase(caseWithBLOBs.getId(), ApiReportStatus.RUNNING.name(), null, config); ApiDefinitionExecResultWithBLOBs report = ApiDefinitionExecResultUtil.initBase(caseWithBLOBs.getId(), ApiReportStatus.RUNNING.name(), null, config);
report.setStatus(status); report.setStatus(status);
@ -387,16 +351,13 @@ public class ApiCaseExecuteService {
DBTestQueue queue = apiExecutionQueueService.add(executeQueue, poolId, ApiRunMode.DEFINITION.name(), serialReportId, reportType, ApiRunMode.DEFINITION.name(), request.getConfig()); DBTestQueue queue = apiExecutionQueueService.add(executeQueue, poolId, ApiRunMode.DEFINITION.name(), serialReportId, reportType, ApiRunMode.DEFINITION.name(), request.getConfig());
// 开始选择执行模式 // 开始选择执行模式
if (queue != null && queue.getDetail() != null) { if (queue != null && queue.getDetail() != null) {
Thread thread = new Thread(new Runnable() { Thread thread = new Thread(() -> {
@Override
public void run() {
Thread.currentThread().setName("API-CASE-RUN"); Thread.currentThread().setName("API-CASE-RUN");
if (request.getConfig().getMode().equals(RunModeConstants.SERIAL.toString())) { if (request.getConfig().getMode().equals(RunModeConstants.SERIAL.toString())) {
apiCaseSerialService.serial(queue); apiCaseSerialService.serial(queue);
} else { } else {
apiCaseParallelExecuteService.parallel(executeQueue, request.getConfig(), queue, ApiRunMode.DEFINITION.name()); apiCaseParallelExecuteService.parallel(executeQueue, request.getConfig(), queue, ApiRunMode.DEFINITION.name());
} }
}
}); });
thread.start(); thread.start();
} }

View File

@ -3,18 +3,15 @@ package io.metersphere.api.parse.api;
import io.metersphere.api.dto.ApiTestImportRequest; import io.metersphere.api.dto.ApiTestImportRequest;
import io.metersphere.api.dto.definition.request.sampler.MsHTTPSamplerProxy; import io.metersphere.api.dto.definition.request.sampler.MsHTTPSamplerProxy;
import io.metersphere.commons.constants.RequestTypeConstants;
import io.metersphere.api.parse.ApiImportAbstractParser; import io.metersphere.api.parse.ApiImportAbstractParser;
import io.metersphere.api.parse.MsAbstractParser; import io.metersphere.api.parse.MsAbstractParser;
import io.metersphere.base.domain.ApiDefinitionWithBLOBs; import io.metersphere.base.domain.ApiDefinitionWithBLOBs;
import io.metersphere.base.domain.ApiTestCaseWithBLOBs; import io.metersphere.base.domain.ApiTestCaseWithBLOBs;
import io.metersphere.commons.constants.ApiImportPlatform; import io.metersphere.commons.constants.ApiImportPlatform;
import io.metersphere.commons.constants.PropertyConstant;
import io.metersphere.commons.constants.RequestTypeConstants;
import io.metersphere.commons.exception.MSException; import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.CommonBeanFactory; import io.metersphere.commons.utils.*;
import io.metersphere.commons.utils.JSON;
import io.metersphere.commons.utils.LogUtil;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.commons.utils.JSONUtil;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -152,8 +149,8 @@ public class MsDefinitionParser extends MsAbstractParser<ApiDefinitionImport> {
return null; return null;
} }
JSONObject requestObj = JSONUtil.parseObject(request); JSONObject requestObj = JSONUtil.parseObject(request);
requestObj.put("useEnvironment", StringUtils.EMPTY); requestObj.put(PropertyConstant.ENVIRONMENT, StringUtils.EMPTY);
requestObj.put("environmentId", StringUtils.EMPTY); requestObj.put(PropertyConstant.ENVIRONMENT_ID, StringUtils.EMPTY);
requestObj.put("projectId", projectId); requestObj.put("projectId", projectId);
return requestObj; return requestObj;
} catch (Exception e) { } catch (Exception e) {

View File

@ -185,8 +185,8 @@ public class ApiScenarioImportUtil {
object.put("id", sameCase.getId()); object.put("id", sameCase.getId());
object.put("resourceId", sameCase.getId()); object.put("resourceId", sameCase.getId());
object.put("projectId", projectId); object.put("projectId", projectId);
object.put("useEnvironment", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT, StringUtils.EMPTY);
object.put("environmentId", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT_ID, StringUtils.EMPTY);
} }
} }
} else { } else {
@ -244,8 +244,8 @@ public class ApiScenarioImportUtil {
object.put("id", test.getId()); object.put("id", test.getId());
object.put("resourceId", test.getId()); object.put("resourceId", test.getId());
object.put("projectId", projectId); object.put("projectId", projectId);
object.put("useEnvironment", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT, StringUtils.EMPTY);
object.put("environmentId", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT_ID, StringUtils.EMPTY);
object.put("url", StringUtils.EMPTY); object.put("url", StringUtils.EMPTY);
JSONObject objectNew = JSONUtil.parseObject(object.toString()); JSONObject objectNew = JSONUtil.parseObject(object.toString());
objectNew.remove("refType"); objectNew.remove("refType");
@ -300,8 +300,8 @@ public class ApiScenarioImportUtil {
object.put("id", apiTestCase.getId()); object.put("id", apiTestCase.getId());
object.put("resourceId", apiTestCase.getId()); object.put("resourceId", apiTestCase.getId());
object.put("projectId", projectId); object.put("projectId", projectId);
object.put("useEnvironment", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT, StringUtils.EMPTY);
object.put("environmentId", StringUtils.EMPTY); object.put(PropertyConstant.ENVIRONMENT_ID, StringUtils.EMPTY);
JSONObject objectNew = JSONUtil.parseObject(object.toString()); JSONObject objectNew = JSONUtil.parseObject(object.toString());
objectNew.remove("refType"); objectNew.remove("refType");
objectNew.remove("referenced"); objectNew.remove("referenced");

View File

@ -24,4 +24,9 @@ public class PropertyConstant {
public final static String ASS_OPTION = "ASS_OPTION"; public final static String ASS_OPTION = "ASS_OPTION";
public final static String EXPECTED_VALUE = "EXPECTED_VALUE"; public final static String EXPECTED_VALUE = "EXPECTED_VALUE";
public final static String ELEMENT_CONDITION = "ElementCondition"; public final static String ELEMENT_CONDITION = "ElementCondition";
public final static String ENVIRONMENT = "useEnvironment";
public final static String ENVIRONMENT_ID = "environmentId";
public final static String DATASOURCE_ID = "dataSourceId";
} }

View File

@ -1,63 +0,0 @@
package io.metersphere.service;
import io.metersphere.service.definition.ApiDefinitionService;
import io.metersphere.service.scenario.ApiScenarioService;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ApiDefinitionMapper;
import io.metersphere.base.mapper.ApiModuleMapper;
import io.metersphere.base.mapper.ApiScenarioMapper;
import io.metersphere.base.mapper.ApiScenarioModuleMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
/**
* 接口测试所有级联删除资源
*/
public class ApiTestDelService {
@Resource
private ApiDefinitionService apiDefinitionService;
@Resource
private ApiScenarioService apiAutomationService;
@Resource
private ApiScenarioMapper apiScenarioMapper;
@Resource
private ApiDefinitionMapper apiDefinitionMapper;
@Resource
private ApiModuleMapper apiModuleMapper;
@Resource
private ApiScenarioModuleMapper apiScenarioModuleMapper;
public void delete(String projectId) {
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andProjectIdEqualTo(projectId);
// api and case
List<String> apiIds = apiDefinitionMapper.selectByExample(example).stream().map(ApiDefinition::getId).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(apiIds)) {
apiDefinitionService.deleteBatch(apiIds);
}
// scenario
ApiScenarioExample scenarioExample = new ApiScenarioExample();
scenarioExample.createCriteria().andProjectIdEqualTo(projectId);
List<String> scenarios = apiScenarioMapper.selectByExample(scenarioExample).stream().map(ApiScenario::getId).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(scenarios)) {
apiAutomationService.deleteBatch(scenarios);
}
// api module
ApiModuleExample moduleExample = new ApiModuleExample();
moduleExample.createCriteria().andProjectIdEqualTo(projectId);
apiModuleMapper.deleteByExample(moduleExample);
// scenario module
ApiScenarioModuleExample scenarioModuleExample = new ApiScenarioModuleExample();
scenarioModuleExample.createCriteria().andProjectIdEqualTo(projectId);
apiScenarioModuleMapper.deleteByExample(scenarioModuleExample);
}
}

View File

@ -678,7 +678,7 @@ public class ApiTestCaseService {
bloBs.forEach(apiTestCase -> { bloBs.forEach(apiTestCase -> {
JSONObject req = JSONUtil.parseObject(apiTestCase.getRequest()); JSONObject req = JSONUtil.parseObject(apiTestCase.getRequest());
req.put("useEnvironment", request.getEnvId()); req.put(PropertyConstant.ENVIRONMENT, request.getEnvId());
String requestStr = JSON.toJSONString(req); String requestStr = JSON.toJSONString(req);
apiTestCase.setRequest(requestStr); apiTestCase.setRequest(requestStr);
batchMapper.updateByPrimaryKeySelective(apiTestCase); batchMapper.updateByPrimaryKeySelective(apiTestCase);

View File

@ -2,32 +2,26 @@ package io.metersphere.service.ext;
import io.metersphere.api.dto.ScheduleRequest; import io.metersphere.api.dto.ScheduleRequest;
import io.metersphere.base.domain.*; import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.ApiScenarioMapper;
import io.metersphere.base.mapper.ScheduleMapper; import io.metersphere.base.mapper.ScheduleMapper;
import io.metersphere.base.mapper.SwaggerUrlProjectMapper; import io.metersphere.base.mapper.SwaggerUrlProjectMapper;
import io.metersphere.base.mapper.UserMapper; import io.metersphere.base.mapper.UserMapper;
import io.metersphere.base.mapper.ext.ExtScheduleMapper; import io.metersphere.base.mapper.ext.ExtScheduleMapper;
import io.metersphere.commons.constants.ScheduleGroup; import io.metersphere.commons.constants.ScheduleGroup;
import io.metersphere.commons.constants.ScheduleType;
import io.metersphere.commons.exception.MSException; import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.utils.DateUtils;
import io.metersphere.commons.utils.JSON; import io.metersphere.commons.utils.JSON;
import io.metersphere.commons.utils.LogUtil; import io.metersphere.commons.utils.LogUtil;
import io.metersphere.commons.utils.SessionUtils; import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.dto.ScheduleDao; import io.metersphere.dto.ScheduleDao;
import io.metersphere.dto.TaskInfoResult;
import io.metersphere.log.utils.ReflexObjectUtil; import io.metersphere.log.utils.ReflexObjectUtil;
import io.metersphere.log.vo.DetailColumn; import io.metersphere.log.vo.DetailColumn;
import io.metersphere.log.vo.OperatingLogDetails; import io.metersphere.log.vo.OperatingLogDetails;
import io.metersphere.log.vo.schedule.ScheduleReference; import io.metersphere.log.vo.schedule.ScheduleReference;
import io.metersphere.request.BaseQueryRequest;
import io.metersphere.request.OrderRequest; import io.metersphere.request.OrderRequest;
import io.metersphere.request.QueryScheduleRequest; import io.metersphere.request.QueryScheduleRequest;
import io.metersphere.sechedule.ApiScenarioTestJob; import io.metersphere.sechedule.ApiScenarioTestJob;
import io.metersphere.sechedule.ScheduleManager; import io.metersphere.sechedule.ScheduleManager;
import io.metersphere.sechedule.SwaggerUrlImportJob; import io.metersphere.sechedule.SwaggerUrlImportJob;
import io.metersphere.service.ServiceUtils; import io.metersphere.service.ServiceUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.quartz.JobKey; import org.quartz.JobKey;
import org.quartz.SchedulerException; import org.quartz.SchedulerException;
@ -36,14 +30,14 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public class ExtApiScheduleService { public class ExtApiScheduleService {
@Resource
private ApiScenarioMapper apiScenarioMapper;
@Resource @Resource
private ScheduleMapper scheduleMapper; private ScheduleMapper scheduleMapper;
@Resource @Resource
@ -70,10 +64,6 @@ public class ExtApiScheduleService {
swaggerUrlProjectMapper.updateByPrimaryKeyWithBLOBs(swaggerUrlProject); swaggerUrlProjectMapper.updateByPrimaryKeyWithBLOBs(swaggerUrlProject);
} }
public Schedule getSchedule(String ScheduleId) {
return scheduleMapper.selectByPrimaryKey(ScheduleId);
}
public int editSchedule(Schedule schedule) { public int editSchedule(Schedule schedule) {
schedule.setUpdateTime(System.currentTimeMillis()); schedule.setUpdateTime(System.currentTimeMillis());
return scheduleMapper.updateByPrimaryKeySelective(schedule); return scheduleMapper.updateByPrimaryKeySelective(schedule);
@ -89,19 +79,6 @@ public class ExtApiScheduleService {
return null; return null;
} }
public List<Schedule> getScheduleByResourceIds(List<String> resourceIds, String group) {
if (CollectionUtils.isEmpty(resourceIds)) {
return new ArrayList<>();
}
ScheduleExample example = new ScheduleExample();
example.createCriteria().andResourceIdIn(resourceIds).andGroupEqualTo(group);
List<Schedule> schedules = scheduleMapper.selectByExample(example);
if (schedules.size() > 0) {
return schedules;
}
return new ArrayList<>();
}
public int deleteByResourceId(String resourceId, String group) { public int deleteByResourceId(String resourceId, String group) {
ScheduleExample scheduleExample = new ScheduleExample(); ScheduleExample scheduleExample = new ScheduleExample();
scheduleExample.createCriteria().andResourceIdEqualTo(resourceId); scheduleExample.createCriteria().andResourceIdEqualTo(resourceId);
@ -120,16 +97,6 @@ public class ExtApiScheduleService {
return scheduleMapper.deleteByExample(scheduleExample); return scheduleMapper.deleteByExample(scheduleExample);
} }
public int deleteByWorkspaceId(String workspaceId) {
ScheduleExample scheduleExample = new ScheduleExample();
scheduleExample.createCriteria().andWorkspaceIdEqualTo(workspaceId);
List<Schedule> schedules = scheduleMapper.selectByExample(scheduleExample);
schedules.forEach(item -> {
removeJob(item.getResourceId(), item.getGroup());
});
return scheduleMapper.deleteByExample(scheduleExample);
}
private void removeJob(String resourceId, String group) { private void removeJob(String resourceId, String group) {
if (StringUtils.equals(ScheduleGroup.API_SCENARIO_TEST.name(), group)) { if (StringUtils.equals(ScheduleGroup.API_SCENARIO_TEST.name(), group)) {
scheduleManager.removeJob(ApiScenarioTestJob.getJobKey(resourceId), ApiScenarioTestJob.getTriggerKey(resourceId)); scheduleManager.removeJob(ApiScenarioTestJob.getJobKey(resourceId), ApiScenarioTestJob.getTriggerKey(resourceId));
@ -138,32 +105,6 @@ public class ExtApiScheduleService {
} }
} }
public List<Schedule> listSchedule() {
ScheduleExample example = new ScheduleExample();
return scheduleMapper.selectByExample(example);
}
public List<Schedule> getEnableSchedule() {
ScheduleExample example = new ScheduleExample();
example.createCriteria().andEnableEqualTo(true);
return scheduleMapper.selectByExample(example);
}
public void startEnableSchedules() {
List<Schedule> Schedules = getEnableSchedule();
Schedules.forEach(schedule -> {
try {
if (schedule.getEnable()) {
LogUtil.info("初始化任务:" + JSON.toJSONString(schedule));
scheduleManager.addOrUpdateCronJob(new JobKey(schedule.getKey(), schedule.getGroup()), new TriggerKey(schedule.getKey(), schedule.getGroup()), Class.forName(schedule.getJob()), schedule.getValue(), scheduleManager.getDefaultJobDataMap(schedule, schedule.getValue(), schedule.getUserId()));
}
} catch (Exception e) {
LogUtil.error("初始化任务失败", e);
}
});
}
public Schedule buildApiTestSchedule(ScheduleRequest request) { public Schedule buildApiTestSchedule(ScheduleRequest request) {
Schedule schedule = new Schedule(); Schedule schedule = new Schedule();
schedule.setResourceId(request.getResourceId()); schedule.setResourceId(request.getResourceId());
@ -231,52 +172,6 @@ public class ExtApiScheduleService {
}); });
} }
public long countTaskByProjectId(String projectId) {
return extScheduleMapper.countTaskByProjectId(projectId);
}
public long countTaskByProjectIdInThisWeek(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 {
return extScheduleMapper.countTaskByProjectIdAndCreateTimeRange(projectId, firstTime.getTime(), lastTime.getTime());
}
}
public List<TaskInfoResult> findRunningTaskInfoByProjectID(String projectID, BaseQueryRequest request) {
List<TaskInfoResult> runningTaskInfoList = extScheduleMapper.findRunningTaskInfoByProjectID(projectID, request);
return runningTaskInfoList;
}
public void createSchedule(ScheduleRequest request) {
Schedule schedule = this.buildApiTestSchedule(request);
JobKey jobKey = null;
TriggerKey triggerKey = null;
Class clazz = null;
if ("testPlan".equals(request.getScheduleFrom())) {
LogUtil.info("testPlan");
} else {
//默认为情景
ApiScenarioWithBLOBs apiScene = apiScenarioMapper.selectByPrimaryKey(request.getResourceId());
schedule.setName(apiScene.getName());
schedule.setProjectId(apiScene.getProjectId());
schedule.setGroup(ScheduleGroup.API_SCENARIO_TEST.name());
schedule.setType(ScheduleType.CRON.name());
jobKey = ApiScenarioTestJob.getJobKey(request.getResourceId());
triggerKey = ApiScenarioTestJob.getTriggerKey(request.getResourceId());
clazz = ApiScenarioTestJob.class;
schedule.setJob(ApiScenarioTestJob.class.getName());
}
this.addSchedule(schedule);
this.addOrUpdateCronJob(request, jobKey, triggerKey, clazz);
}
public void updateSchedule(Schedule request) { public void updateSchedule(Schedule request) {
JobKey jobKey = null; JobKey jobKey = null;
TriggerKey triggerKey = null; TriggerKey triggerKey = null;
@ -307,11 +202,6 @@ public class ExtApiScheduleService {
} }
} }
public Object getCurrentlyExecutingJobs() {
return scheduleManager.getCurrentlyExecutingJobs();
}
public String getLogDetails(String id) { public String getLogDetails(String id) {
Schedule bloB = scheduleMapper.selectByPrimaryKey(id); Schedule bloB = scheduleMapper.selectByPrimaryKey(id);
if (bloB != null) { if (bloB != null) {

View File

@ -6,7 +6,6 @@ import io.metersphere.base.domain.Project;
import io.metersphere.base.domain.ProjectApplication; import io.metersphere.base.domain.ProjectApplication;
import io.metersphere.base.domain.ProjectApplicationExample; import io.metersphere.base.domain.ProjectApplicationExample;
import io.metersphere.base.mapper.ProjectApplicationMapper; import io.metersphere.base.mapper.ProjectApplicationMapper;
import io.metersphere.base.mapper.ProjectMapper;
import io.metersphere.base.mapper.UserMapper; import io.metersphere.base.mapper.UserMapper;
import io.metersphere.base.mapper.ext.BaseProjectMapper; import io.metersphere.base.mapper.ext.BaseProjectMapper;
import io.metersphere.base.mapper.ext.ExtApiProjectMapper; import io.metersphere.base.mapper.ext.ExtApiProjectMapper;
@ -41,8 +40,6 @@ public class ExtProjectApplicationService {
@Resource @Resource
private BaseProjectService baseProjectService; private BaseProjectService baseProjectService;
@Resource @Resource
private ProjectMapper projectMapper;
@Resource
private BaseProjectMapper baseProjectMapper; private BaseProjectMapper baseProjectMapper;
@Resource @Resource
private UserMapper userMapper; private UserMapper userMapper;
@ -144,11 +141,6 @@ public class ExtProjectApplicationService {
} }
} }
public void closeMockTcp(String projectId) {
Project project = projectMapper.selectByPrimaryKey(projectId);
this.closeMockTcp(project);
}
public void closeMockTcp(Project project) { public void closeMockTcp(Project project) {
if (project == null) { if (project == null) {
MSException.throwException("Project not found!"); MSException.throwException("Project not found!");

View File

@ -1188,7 +1188,7 @@ public class ApiScenarioService {
List<ApiScenarioWithBLOBs> apiScenarios = selectByIdsWithBLOBs(request.getIds()); List<ApiScenarioWithBLOBs> apiScenarios = selectByIdsWithBLOBs(request.getIds());
apiScenarios.forEach(item -> { apiScenarios.forEach(item -> {
JSONObject object = JSONUtil.parseObject(item.getScenarioDefinition()); JSONObject object = JSONUtil.parseObject(item.getScenarioDefinition());
object.put("environmentId", request.getEnvironmentId()); object.put(PropertyConstant.ENVIRONMENT_ID, request.getEnvironmentId());
if (object != null) { if (object != null) {
item.setScenarioDefinition(object.toString()); item.setScenarioDefinition(object.toString());
} }