This commit is contained in:
chenjianxing 2020-10-12 10:09:44 +08:00
commit 47344ab909
62 changed files with 1042 additions and 602 deletions

View File

@ -11,6 +11,7 @@ import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.dto.DashboardTestDTO;
import io.metersphere.service.CheckOwnerService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
@ -25,6 +26,8 @@ public class APIReportController {
@Resource
private APIReportService apiReportService;
@Resource
private CheckOwnerService checkOwnerService;
@GetMapping("recent/{count}")
public List<APIReportResult> recentTest(@PathVariable int count) {
@ -37,6 +40,7 @@ public class APIReportController {
@GetMapping("/list/{testId}")
public List<APIReportResult> listByTestId(@PathVariable String testId) {
checkOwnerService.checkApiTestOwner(testId);
return apiReportService.listByTestId(testId);
}

View File

@ -13,6 +13,7 @@ import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.controller.request.QueryScheduleRequest;
import io.metersphere.dto.ScheduleDao;
import io.metersphere.service.CheckOwnerService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
@ -27,6 +28,8 @@ import java.util.List;
public class APITestController {
@Resource
private APITestService apiTestService;
@Resource
private CheckOwnerService checkownerService;
@GetMapping("recent/{count}")
public List<APITestResult> recentTest(@PathVariable int count) {
@ -51,6 +54,7 @@ public class APITestController {
@GetMapping("/list/{projectId}")
public List<ApiTest> list(@PathVariable String projectId) {
checkownerService.checkProjectOwner(projectId);
return apiTestService.getApiTestByProjectId(projectId);
}
@ -71,6 +75,7 @@ public class APITestController {
@PostMapping(value = "/update", consumes = {"multipart/form-data"})
public void update(@RequestPart("request") SaveAPITestRequest request, @RequestPart(value = "file") MultipartFile file, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
checkownerService.checkApiTestOwner(request.getId());
apiTestService.update(request, file, bodyFiles);
}
@ -81,13 +86,16 @@ public class APITestController {
@GetMapping("/get/{testId}")
public APITestResult get(@PathVariable String testId) {
checkownerService.checkApiTestOwner(testId);
return apiTestService.get(testId);
}
@PostMapping("/delete")
public void delete(@RequestBody DeleteAPITestRequest request) {
apiTestService.delete(request.getId());
String testId = request.getId();
checkownerService.checkApiTestOwner(testId);
apiTestService.delete(testId);
}
@PostMapping(value = "/run")

View File

@ -3,6 +3,7 @@ package io.metersphere.api.controller;
import io.metersphere.api.service.ApiTestEnvironmentService;
import io.metersphere.base.domain.ApiTestEnvironmentWithBLOBs;
import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.service.CheckOwnerService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
@ -17,9 +18,12 @@ public class ApiTestEnvironmentController {
@Resource
ApiTestEnvironmentService apiTestEnvironmentService;
@Resource
private CheckOwnerService checkOwnerService;
@GetMapping("/list/{projectId}")
public List<ApiTestEnvironmentWithBLOBs> list(@PathVariable String projectId) {
checkOwnerService.checkProjectOwner(projectId);
return apiTestEnvironmentService.list(projectId);
}

View File

@ -37,5 +37,7 @@ public class TestCase implements Serializable {
private String otherTestName;
private String reviewStatus;
private static final long serialVersionUID = 1L;
}

View File

@ -1183,6 +1183,76 @@ public class TestCaseExample {
addCriterion("other_test_name not between", value1, value2, "otherTestName");
return (Criteria) this;
}
public Criteria andReviewStatusIsNull() {
addCriterion("review_status is null");
return (Criteria) this;
}
public Criteria andReviewStatusIsNotNull() {
addCriterion("review_status is not null");
return (Criteria) this;
}
public Criteria andReviewStatusEqualTo(String value) {
addCriterion("review_status =", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusNotEqualTo(String value) {
addCriterion("review_status <>", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusGreaterThan(String value) {
addCriterion("review_status >", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusGreaterThanOrEqualTo(String value) {
addCriterion("review_status >=", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusLessThan(String value) {
addCriterion("review_status <", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusLessThanOrEqualTo(String value) {
addCriterion("review_status <=", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusLike(String value) {
addCriterion("review_status like", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusNotLike(String value) {
addCriterion("review_status not like", value, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusIn(List<String> values) {
addCriterion("review_status in", values, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusNotIn(List<String> values) {
addCriterion("review_status not in", values, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusBetween(String value1, String value2) {
addCriterion("review_status between", value1, value2, "reviewStatus");
return (Criteria) this;
}
public Criteria andReviewStatusNotBetween(String value1, String value2) {
addCriterion("review_status not between", value1, value2, "reviewStatus");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -18,6 +18,7 @@
<result column="sort" jdbcType="INTEGER" property="sort" />
<result column="num" jdbcType="INTEGER" property="num" />
<result column="other_test_name" jdbcType="VARCHAR" property="otherTestName" />
<result column="review_status" jdbcType="VARCHAR" property="reviewStatus" />
</resultMap>
<resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="io.metersphere.base.domain.TestCaseWithBLOBs">
<result column="remark" jdbcType="LONGVARCHAR" property="remark" />
@ -83,7 +84,7 @@
</sql>
<sql id="Base_Column_List">
id, node_id, node_path, project_id, `name`, `type`, maintainer, priority, `method`,
prerequisite, create_time, update_time, test_id, sort, num, other_test_name
prerequisite, create_time, update_time, test_id, sort, num, other_test_name, review_status
</sql>
<sql id="Blob_Column_List">
remark, steps
@ -142,15 +143,15 @@
maintainer, priority, `method`,
prerequisite, create_time, update_time,
test_id, sort, num,
other_test_name, remark, steps
)
other_test_name, review_status, remark,
steps)
values (#{id,jdbcType=VARCHAR}, #{nodeId,jdbcType=VARCHAR}, #{nodePath,jdbcType=VARCHAR},
#{projectId,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR},
#{maintainer,jdbcType=VARCHAR}, #{priority,jdbcType=VARCHAR}, #{method,jdbcType=VARCHAR},
#{prerequisite,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT},
#{testId,jdbcType=VARCHAR}, #{sort,jdbcType=INTEGER}, #{num,jdbcType=INTEGER},
#{otherTestName,jdbcType=VARCHAR}, #{remark,jdbcType=LONGVARCHAR}, #{steps,jdbcType=LONGVARCHAR}
)
#{otherTestName,jdbcType=VARCHAR}, #{reviewStatus,jdbcType=VARCHAR}, #{remark,jdbcType=LONGVARCHAR},
#{steps,jdbcType=LONGVARCHAR})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.base.domain.TestCaseWithBLOBs">
insert into test_case
@ -203,6 +204,9 @@
<if test="otherTestName != null">
other_test_name,
</if>
<if test="reviewStatus != null">
review_status,
</if>
<if test="remark != null">
remark,
</if>
@ -259,6 +263,9 @@
<if test="otherTestName != null">
#{otherTestName,jdbcType=VARCHAR},
</if>
<if test="reviewStatus != null">
#{reviewStatus,jdbcType=VARCHAR},
</if>
<if test="remark != null">
#{remark,jdbcType=LONGVARCHAR},
</if>
@ -324,6 +331,9 @@
<if test="record.otherTestName != null">
other_test_name = #{record.otherTestName,jdbcType=VARCHAR},
</if>
<if test="record.reviewStatus != null">
review_status = #{record.reviewStatus,jdbcType=VARCHAR},
</if>
<if test="record.remark != null">
remark = #{record.remark,jdbcType=LONGVARCHAR},
</if>
@ -353,6 +363,7 @@
sort = #{record.sort,jdbcType=INTEGER},
num = #{record.num,jdbcType=INTEGER},
other_test_name = #{record.otherTestName,jdbcType=VARCHAR},
review_status = #{record.reviewStatus,jdbcType=VARCHAR},
remark = #{record.remark,jdbcType=LONGVARCHAR},
steps = #{record.steps,jdbcType=LONGVARCHAR}
<if test="_parameter != null">
@ -376,7 +387,8 @@
test_id = #{record.testId,jdbcType=VARCHAR},
sort = #{record.sort,jdbcType=INTEGER},
num = #{record.num,jdbcType=INTEGER},
other_test_name = #{record.otherTestName,jdbcType=VARCHAR}
other_test_name = #{record.otherTestName,jdbcType=VARCHAR},
review_status = #{record.reviewStatus,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -429,6 +441,9 @@
<if test="otherTestName != null">
other_test_name = #{otherTestName,jdbcType=VARCHAR},
</if>
<if test="reviewStatus != null">
review_status = #{reviewStatus,jdbcType=VARCHAR},
</if>
<if test="remark != null">
remark = #{remark,jdbcType=LONGVARCHAR},
</if>
@ -455,6 +470,7 @@
sort = #{sort,jdbcType=INTEGER},
num = #{num,jdbcType=INTEGER},
other_test_name = #{otherTestName,jdbcType=VARCHAR},
review_status = #{reviewStatus,jdbcType=VARCHAR},
remark = #{remark,jdbcType=LONGVARCHAR},
steps = #{steps,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=VARCHAR}
@ -475,7 +491,8 @@
test_id = #{testId,jdbcType=VARCHAR},
sort = #{sort,jdbcType=INTEGER},
num = #{num,jdbcType=INTEGER},
other_test_name = #{otherTestName,jdbcType=VARCHAR}
other_test_name = #{otherTestName,jdbcType=VARCHAR},
review_status = #{reviewStatus,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -20,4 +20,12 @@ public interface ExtTestCaseMapper {
TestCase getMaxNumByProjectId(@Param("projectId") String projectId);
/**
* 检查某工作空间下是否有某用例
* @param caseId
* @param workspaceId
* @return TestCase ID
*/
List<String> checkIsHave(@Param("caseId") String caseId, @Param("workspaceId") String workspaceId);
}

View File

@ -99,7 +99,7 @@
<select id="getTestCaseNames" resultType="io.metersphere.base.domain.TestCase">
select test_case.id, test_case.name, test_case.priority, test_case.type
select test_case.id, test_case.name, test_case.priority, test_case.type, test_case.review_status
from test_case
<where>
<if test="request.combine != null">
@ -130,6 +130,12 @@
#{value}
</foreach>
</when>
<when test="key=='status'">
and test_case.review_status in
<foreach collection="values" item="value" separator="," open="(" close=")">
#{value}
</foreach>
</when>
<otherwise>
and test_case.type in
<foreach collection="values" item="value" separator="," open="(" close=")">
@ -181,6 +187,12 @@
#{value}
</foreach>
</when>
<when test="key=='status'">
and test_case.review_status in
<foreach collection="values" item="value" separator="," open="(" close=")">
#{value}
</foreach>
</when>
<otherwise>
and test_case.method in
<foreach collection="values" item="value" separator="," open="(" close=")">
@ -239,4 +251,11 @@
<select id="getMaxNumByProjectId" resultType="io.metersphere.base.domain.TestCase">
select * from test_case where test_case.project_id = #{projectId} order by num desc limit 1;
</select>
<select id="checkIsHave" resultType="java.lang.String">
select distinct test_case.id
from test_case, project
where test_case.project_id = project.id
and project.workspace_id = #{workspaceId}
and test_case.id = #{caseId};
</select>
</mapper>

View File

@ -15,4 +15,12 @@ public interface ExtTestCaseReviewMapper {
List<TestCaseReviewDTO> listByWorkspaceId(@Param("workspaceId") String workspaceId);
List<TestReviewDTOWithMetric> listRelate(@Param("request") QueryTestReviewRequest request);
/**
* 检查某工作空间下是否有某测试评审
* @param reviewId
* @param workspaceId
* @return Review ID
*/
List<String> checkIsHave(@Param("reviewId") String reviewId, @Param("workspaceId") String workspaceId);
}

View File

@ -58,4 +58,11 @@
order by test_case_review.update_time desc
</select>
<select id="checkIsHave" resultType="java.lang.String">
select distinct review_id
from project, test_case_review_project
where project.id = test_case_review_project.project_id
and project.workspace_id = #{workspaceId}
and test_case_review_project.review_id = #{reviewId};
</select>
</mapper>

View File

@ -10,6 +10,6 @@ import java.util.List;
public interface ExtTestReviewCaseMapper {
List<TestReviewCaseDTO> list(@Param("request") QueryCaseReviewRequest request);
List<String> getStatusByReviewId(String planId);
List<String> getStatusByReviewId(String reviewId);
List<String> findRelateTestReviewId(String userId, String workspaceId);
}

View File

@ -182,9 +182,9 @@
</select>
<select id="getStatusByReviewId" resultType="java.lang.String">
select status
from test_case_review_test_case
where review_id = #{reviewId}
select review_status
from test_case
where id in (select case_id from test_case_review_test_case where review_id = #{reviewId});
</select>
<select id="findRelateTestReviewId" resultType="java.lang.String">

View File

@ -9,6 +9,7 @@ import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.controller.request.ProjectRequest;
import io.metersphere.dto.ProjectDTO;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.service.ProjectService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
@ -22,6 +23,8 @@ import java.util.List;
public class ProjectController {
@Resource
private ProjectService projectService;
@Resource
private CheckOwnerService checkOwnerService;
@GetMapping("/listAll")
public List<ProjectDTO> listAll() {
@ -71,6 +74,7 @@ public class ProjectController {
@GetMapping("/delete/{projectId}")
@RequiresRoles(value = {RoleConstants.TEST_MANAGER, RoleConstants.TEST_USER,}, logical = Logical.OR)
public void deleteProject(@PathVariable(value = "projectId") String projectId) {
checkOwnerService.checkProjectOwner(projectId);
projectService.deleteProject(projectId);
}

View File

@ -4,6 +4,7 @@ package io.metersphere.controller.handler;
import io.metersphere.commons.exception.MSException;
import io.metersphere.controller.ResultHolder;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@ -21,6 +22,13 @@ public class RestControllerExceptionHandler {
return ResultHolder.error(exception.getMessage());
}
/*=========== Shiro 异常拦截==============*/
@ExceptionHandler(UnauthorizedException.class)
public ResultHolder unauthorizedExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
response.setStatus(HttpStatus.FORBIDDEN.value());
return ResultHolder.error(exception.getMessage());
}
@ExceptionHandler(MSException.class)
public ResultHolder msExceptionHandler(HttpServletRequest request, HttpServletResponse response, MSException e) {

View File

@ -14,6 +14,7 @@ import io.metersphere.dto.DashboardTestDTO;
import io.metersphere.dto.LoadTestDTO;
import io.metersphere.dto.ScheduleDao;
import io.metersphere.performance.service.PerformanceTestService;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.service.FileService;
import io.metersphere.track.request.testplan.*;
import org.apache.shiro.authz.annotation.Logical;
@ -35,6 +36,8 @@ public class PerformanceTestController {
private PerformanceTestService performanceTestService;
@Resource
private FileService fileService;
@Resource
private CheckOwnerService checkOwnerService;
@GetMapping("recent/{count}")
public List<LoadTestDTO> recentTestPlans(@PathVariable int count) {
@ -54,12 +57,14 @@ public class PerformanceTestController {
@GetMapping("/list/{projectId}")
public List<LoadTest> list(@PathVariable String projectId) {
checkOwnerService.checkProjectOwner(projectId);
return performanceTestService.getLoadTestByProjectId(projectId);
}
@GetMapping("/state/get/{testId}")
public LoadTest listByTestId(@PathVariable String testId) {
checkOwnerService.checkPerformanceTestOwner(testId);
return performanceTestService.getLoadTestBytestId(testId);
}
@ -76,26 +81,31 @@ public class PerformanceTestController {
@RequestPart("request") EditTestPlanRequest request,
@RequestPart(value = "file", required = false) List<MultipartFile> files
) {
checkOwnerService.checkPerformanceTestOwner(request.getId());
return performanceTestService.edit(request, files);
}
@GetMapping("/get/{testId}")
public LoadTestDTO get(@PathVariable String testId) {
checkOwnerService.checkPerformanceTestOwner(testId);
return performanceTestService.get(testId);
}
@GetMapping("/get-advanced-config/{testId}")
public String getAdvancedConfiguration(@PathVariable String testId) {
checkOwnerService.checkPerformanceTestOwner(testId);
return performanceTestService.getAdvancedConfiguration(testId);
}
@GetMapping("/get-load-config/{testId}")
public String getLoadConfiguration(@PathVariable String testId) {
checkOwnerService.checkPerformanceTestOwner(testId);
return performanceTestService.getLoadConfiguration(testId);
}
@PostMapping("/delete")
public void delete(@RequestBody DeleteTestPlanRequest request) {
checkOwnerService.checkPerformanceTestOwner(request.getId());
performanceTestService.delete(request);
}
@ -111,6 +121,7 @@ public class PerformanceTestController {
@GetMapping("/file/metadata/{testId}")
public List<FileMetadata> getFileMetadata(@PathVariable String testId) {
checkOwnerService.checkPerformanceTestOwner(testId);
return fileService.getFileMetadataByTestId(testId);
}

View File

@ -0,0 +1,97 @@
package io.metersphere.service;
import io.metersphere.api.dto.APITestResult;
import io.metersphere.api.dto.QueryAPITestRequest;
import io.metersphere.base.domain.Project;
import io.metersphere.base.mapper.ProjectMapper;
import io.metersphere.base.mapper.ext.*;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.dto.LoadTestDTO;
import io.metersphere.i18n.Translator;
import io.metersphere.track.dto.TestPlanDTO;
import io.metersphere.track.request.testplan.QueryTestPlanRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CheckOwnerService {
@Resource
private ProjectMapper projectMapper;
@Resource
private ExtApiTestMapper extApiTestMapper;
@Resource
private ExtLoadTestMapper extLoadTestMapper;
@Resource
private ExtTestCaseMapper extTestCaseMapper;
@Resource
private ExtTestPlanMapper extTestPlanMapper;
@Resource
private ExtTestCaseReviewMapper extTestCaseReviewMapper;
public void checkProjectOwner(String projectId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
Project project = projectMapper.selectByPrimaryKey(projectId);
if (project == null) {
return;
}
if (!StringUtils.equals(workspaceId, project.getWorkspaceId())) {
throw new UnauthorizedException(Translator.get("check_owner_project"));
}
}
public void checkApiTestOwner(String testId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
QueryAPITestRequest request = new QueryAPITestRequest();
request.setWorkspaceId(workspaceId);
request.setId(testId);
List<APITestResult> apiTestResults = extApiTestMapper.list(request);
if (CollectionUtils.size(apiTestResults) != 1) {
throw new UnauthorizedException(Translator.get("check_owner_test"));
}
}
public void checkPerformanceTestOwner(String testId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
QueryTestPlanRequest request = new QueryTestPlanRequest();
request.setWorkspaceId(workspaceId);
request.setId(testId);
List<LoadTestDTO> loadTestDTOS = extLoadTestMapper.list(request);
if (CollectionUtils.size(loadTestDTOS) != 1) {
throw new UnauthorizedException(Translator.get("check_owner_test"));
}
}
public void checkTestCaseOwner(String caseId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
List<String> list = extTestCaseMapper.checkIsHave(caseId, workspaceId);
if (CollectionUtils.size(list) != 1) {
throw new UnauthorizedException(Translator.get("check_owner_case"));
}
}
public void checkTestPlanOwner(String planId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
io.metersphere.track.request.testcase.QueryTestPlanRequest request = new io.metersphere.track.request.testcase.QueryTestPlanRequest();
request.setWorkspaceId(workspaceId);
request.setId(planId);
List<TestPlanDTO> list = extTestPlanMapper.list(request);
if (CollectionUtils.size(list) != 1) {
throw new UnauthorizedException(Translator.get("check_owner_plan"));
}
}
public void checkTestReviewOwner(String reviewId) {
String workspaceId = SessionUtils.getCurrentWorkspaceId();
List<String> list = extTestCaseReviewMapper.checkIsHave(reviewId, workspaceId);
if (CollectionUtils.size(list) != 1) {
throw new UnauthorizedException(Translator.get("check_owner_review"));
}
}
}

View File

@ -487,20 +487,18 @@ public class UserService {
/*修改当前用户用户密码*/
private User updateCurrentUserPwd(EditPassWordRequest request) {
if (SessionUtils.getUser() != null) {
User user = userMapper.selectByPrimaryKey(SessionUtils.getUser().getId());
String pwd = user.getPassword();
String prepwd = CodingUtil.md5(request.getPassword(), "utf-8");
String newped = request.getNewpassword();
if (StringUtils.isNotBlank(prepwd)) {
if (prepwd.trim().equals(pwd.trim())) {
user.setPassword(CodingUtil.md5(newped));
user.setUpdateTime(System.currentTimeMillis());
return user;
}
}
MSException.throwException(Translator.get("password_modification_failed"));
String oldPassword = CodingUtil.md5(request.getPassword(), "utf-8");
String newPassword = request.getNewpassword();
UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(SessionUtils.getUser().getId()).andPasswordEqualTo(oldPassword);
List<User> users = userMapper.selectByExample(userExample);
if (!CollectionUtils.isEmpty(users)) {
User user = users.get(0);
user.setPassword(CodingUtil.md5(newPassword));
user.setUpdateTime(System.currentTimeMillis());
return user;
}
MSException.throwException(Translator.get("password_modification_failed"));
return null;
}
@ -512,8 +510,8 @@ public class UserService {
/*管理员修改用户密码*/
private User updateUserPwd(EditPassWordRequest request) {
User user = userMapper.selectByPrimaryKey(request.getId());
String newped = request.getNewpassword();
user.setPassword(CodingUtil.md5(newped));
String newPassword = request.getNewpassword();
user.setPassword(CodingUtil.md5(newPassword));
user.setUpdateTime(System.currentTimeMillis());
return user;
}

View File

@ -10,6 +10,7 @@ import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.excel.domain.ExcelResponse;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.track.dto.TestCaseDTO;
import io.metersphere.track.request.testcase.QueryTestCaseRequest;
import io.metersphere.track.request.testcase.TestCaseBatchRequest;
@ -30,6 +31,8 @@ public class TestCaseController {
@Resource
TestCaseService testCaseService;
@Resource
private CheckOwnerService checkOwnerService;
@PostMapping("/list/{goPage}/{pageSize}")
public Pager<List<TestCaseDTO>> list(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody QueryTestCaseRequest request) {
@ -39,6 +42,7 @@ public class TestCaseController {
@GetMapping("/list/{projectId}")
public List<TestCaseDTO> list(@PathVariable String projectId) {
checkOwnerService.checkProjectOwner(projectId);
QueryTestCaseRequest request = new QueryTestCaseRequest();
request.setProjectId(projectId);
return testCaseService.listTestCase(request);
@ -47,6 +51,7 @@ public class TestCaseController {
@GetMapping("/list/method/{projectId}")
public List<TestCaseDTO> listByMethod(@PathVariable String projectId) {
checkOwnerService.checkProjectOwner(projectId);
QueryTestCaseRequest request = new QueryTestCaseRequest();
request.setProjectId(projectId);
return testCaseService.listTestCaseMthod(request);
@ -78,11 +83,13 @@ public class TestCaseController {
@GetMapping("/get/{testCaseId}")
public TestCaseWithBLOBs getTestCase(@PathVariable String testCaseId) {
checkOwnerService.checkTestCaseOwner(testCaseId);
return testCaseService.getTestCase(testCaseId);
}
@GetMapping("/project/{testCaseId}")
public Project getProjectByTestCaseId(@PathVariable String testCaseId) {
checkOwnerService.checkTestCaseOwner(testCaseId);
return testCaseService.getProjectByTestCaseId(testCaseId);
}
@ -101,13 +108,15 @@ public class TestCaseController {
@PostMapping("/delete/{testCaseId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public int deleteTestCase(@PathVariable String testCaseId) {
checkOwnerService.checkTestCaseOwner(testCaseId);
return testCaseService.deleteTestCase(testCaseId);
}
@PostMapping("/import/{projectId}/{userId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public ExcelResponse testCaseImport(MultipartFile file, @PathVariable String projectId,@PathVariable String userId) throws NoSuchFieldException {
return testCaseService.testCaseImport(file, projectId,userId);
public ExcelResponse testCaseImport(MultipartFile file, @PathVariable String projectId, @PathVariable String userId) {
checkOwnerService.checkProjectOwner(projectId);
return testCaseService.testCaseImport(file, projectId, userId);
}
@GetMapping("/export/template")
@ -115,6 +124,7 @@ public class TestCaseController {
public void testCaseTemplateExport(HttpServletResponse response) {
testCaseService.testCaseTemplateExport(response);
}
@GetMapping("/export/xmindTemplate")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public void xmindTemplate(HttpServletResponse response) {

View File

@ -2,6 +2,7 @@ package io.metersphere.track.controller;
import io.metersphere.base.domain.TestCaseNode;
import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.track.dto.TestCaseNodeDTO;
import io.metersphere.track.request.testcase.DragNodeRequest;
import io.metersphere.track.request.testcase.QueryNodeRequest;
@ -20,9 +21,12 @@ public class TestCaseNodeController {
@Resource
TestCaseNodeService testCaseNodeService;
@Resource
private CheckOwnerService checkOwnerService;
@GetMapping("/list/{projectId}")
public List<TestCaseNodeDTO> getNodeByProjectId(@PathVariable String projectId) {
checkOwnerService.checkProjectOwner(projectId);
return testCaseNodeService.getNodeTreeByProjectId(projectId);
}
@ -39,11 +43,13 @@ public class TestCaseNodeController {
@GetMapping("/list/plan/{planId}")
public List<TestCaseNodeDTO> getNodeByPlanId(@PathVariable String planId) {
checkOwnerService.checkTestPlanOwner(planId);
return testCaseNodeService.getNodeByPlanId(planId);
}
@GetMapping("/list/review/{reviewId}")
public List<TestCaseNodeDTO> getNodeByReviewId(@PathVariable String reviewId) {
checkOwnerService.checkTestReviewOwner(reviewId);
return testCaseNodeService.getNodeByReviewId(reviewId);
}

View File

@ -9,6 +9,7 @@ import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.track.dto.TestCaseReviewDTO;
import io.metersphere.track.dto.TestReviewDTOWithMetric;
import io.metersphere.track.request.testreview.ReviewRelevanceRequest;
@ -32,6 +33,8 @@ public class TestCaseReviewController {
TestCaseReviewService testCaseReviewService;
@Resource
TestReviewProjectService testReviewProjectService;
@Resource
CheckOwnerService checkOwnerService;
@PostMapping("/list/{goPage}/{pageSize}")
public Pager<List<TestCaseReviewDTO>> list(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody QueryCaseReviewRequest request) {
@ -71,6 +74,7 @@ public class TestCaseReviewController {
@GetMapping("/delete/{reviewId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public void deleteCaseReview(@PathVariable String reviewId) {
checkOwnerService.checkTestReviewOwner(reviewId);
testCaseReviewService.deleteCaseReview(reviewId);
}
@ -103,12 +107,14 @@ public class TestCaseReviewController {
@PostMapping("/get/{reviewId}")
public TestCaseReview getTestReview(@PathVariable String reviewId) {
checkOwnerService.checkTestReviewOwner(reviewId);
return testCaseReviewService.getTestReview(reviewId);
}
@PostMapping("/edit/status/{reviewId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public void editTestPlanStatus(@PathVariable String reviewId) {
checkOwnerService.checkTestReviewOwner(reviewId);
testCaseReviewService.editTestReviewStatus(reviewId);
}

View File

@ -8,6 +8,7 @@ import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.utils.PageUtils;
import io.metersphere.commons.utils.Pager;
import io.metersphere.commons.utils.SessionUtils;
import io.metersphere.service.CheckOwnerService;
import io.metersphere.track.dto.TestCaseReportMetricDTO;
import io.metersphere.track.dto.TestPlanDTO;
import io.metersphere.track.dto.TestPlanDTOWithMetric;
@ -32,6 +33,8 @@ public class TestPlanController {
TestPlanService testPlanService;
@Resource
TestPlanProjectService testPlanProjectService;
@Resource
CheckOwnerService checkOwnerService;
@PostMapping("/list/{goPage}/{pageSize}")
public Pager<List<TestPlanDTO>> list(@PathVariable int goPage, @PathVariable int pageSize, @RequestBody QueryTestPlanRequest request) {
@ -70,6 +73,7 @@ public class TestPlanController {
@PostMapping("/get/{testPlanId}")
public TestPlan getTestPlan(@PathVariable String testPlanId) {
checkOwnerService.checkTestPlanOwner(testPlanId);
return testPlanService.getTestPlan(testPlanId);
}
@ -88,12 +92,14 @@ public class TestPlanController {
@PostMapping("/edit/status/{planId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public void editTestPlanStatus(@PathVariable String planId) {
checkOwnerService.checkTestPlanOwner(planId);
testPlanService.editTestPlanStatus(planId);
}
@PostMapping("/delete/{testPlanId}")
@RequiresRoles(value = {RoleConstants.TEST_USER, RoleConstants.TEST_MANAGER}, logical = Logical.OR)
public int deleteTestPlan(@PathVariable String testPlanId) {
checkOwnerService.checkTestPlanOwner(testPlanId);
return testPlanService.deleteTestPlan(testPlanId);
}
@ -109,6 +115,7 @@ public class TestPlanController {
@GetMapping("/project/name/{planId}")
public String getProjectNameByPlanId(@PathVariable String planId) {
checkOwnerService.checkTestPlanOwner(planId);
return testPlanService.getProjectNameByPlanId(planId);
}

View File

@ -9,7 +9,7 @@ import lombok.Setter;
public class TestReviewCaseDTO extends TestCaseWithBLOBs {
private String reviewer;
private String reviewerName;
private String status;
private String reviewStatus;
private String results;
private String reviewId;
private String caseId;

View File

@ -9,4 +9,5 @@ public class TestReviewDTOWithMetric extends TestCaseReviewDTO {
private Double testRate;
private Integer reviewed;
private Integer total;
private Integer pass;
}

View File

@ -6,8 +6,8 @@ import io.metersphere.base.mapper.ext.ExtProjectMapper;
import io.metersphere.base.mapper.ext.ExtTestCaseReviewMapper;
import io.metersphere.base.mapper.ext.ExtTestReviewCaseMapper;
import io.metersphere.commons.constants.TestCaseReviewStatus;
import io.metersphere.commons.constants.TestPlanStatus;
import io.metersphere.commons.constants.TestPlanTestCaseStatus;
import io.metersphere.commons.constants.TestReviewCaseStatus;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.user.SessionUser;
import io.metersphere.commons.utils.LogUtil;
@ -32,7 +32,6 @@ import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@ -272,14 +271,20 @@ public class TestCaseReviewService {
List<Project> projects = projectMapper.selectByExample(projectExample);
List<String> projectIds = projects.stream().map(Project::getId).collect(Collectors.toList());
TestCaseReviewProjectExample testCaseReviewProjectExample = new TestCaseReviewProjectExample();
testCaseReviewProjectExample.createCriteria().andProjectIdIn(projectIds);
List<TestCaseReviewProject> testCaseReviewProjects = testCaseReviewProjectMapper.selectByExample(testCaseReviewProjectExample);
List<String> reviewIds = testCaseReviewProjects.stream().map(TestCaseReviewProject::getReviewId).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(projectIds)) {
TestCaseReviewProjectExample testCaseReviewProjectExample = new TestCaseReviewProjectExample();
testCaseReviewProjectExample.createCriteria().andProjectIdIn(projectIds);
List<TestCaseReviewProject> testCaseReviewProjects = testCaseReviewProjectMapper.selectByExample(testCaseReviewProjectExample);
List<String> reviewIds = testCaseReviewProjects.stream().map(TestCaseReviewProject::getReviewId).collect(Collectors.toList());
TestCaseReviewExample testCaseReviewExample = new TestCaseReviewExample();
testCaseReviewExample.createCriteria().andIdIn(reviewIds);
return testCaseReviewMapper.selectByExample(testCaseReviewExample);
if (!CollectionUtils.isEmpty(reviewIds)) {
TestCaseReviewExample testCaseReviewExample = new TestCaseReviewExample();
testCaseReviewExample.createCriteria().andIdIn(reviewIds);
return testCaseReviewMapper.selectByExample(testCaseReviewExample);
}
}
return new ArrayList<>();
}
public void testReviewRelevance(ReviewRelevanceRequest request) {
@ -340,13 +345,13 @@ public class TestCaseReviewService {
testCaseReview.setId(reviewId);
for (String status : statusList) {
if (StringUtils.equals(status, TestPlanTestCaseStatus.Prepare.name())) {
testCaseReview.setStatus(TestPlanStatus.Underway.name());
if (StringUtils.equals(status, TestReviewCaseStatus.Prepare.name())) {
testCaseReview.setStatus(TestCaseReviewStatus.Underway.name());
testCaseReviewMapper.updateByPrimaryKeySelective(testCaseReview);
return;
}
}
testCaseReview.setStatus(TestPlanStatus.Completed.name());
testCaseReview.setStatus(TestCaseReviewStatus.Completed.name());
SaveTestCaseReviewRequest testCaseReviewRequest = new SaveTestCaseReviewRequest();
TestCaseReview _testCaseReview = testCaseReviewMapper.selectByPrimaryKey(reviewId);
List<String> userIds = new ArrayList<>();
@ -405,16 +410,19 @@ public class TestCaseReviewService {
testReview.setReviewed(0);
testReview.setTotal(0);
testReview.setPass(0);
if (testCases != null) {
testReview.setTotal(testCases.size());
testCases.forEach(testCase -> {
if (!StringUtils.equals(testCase.getStatus(), TestPlanTestCaseStatus.Prepare.name())
&& !StringUtils.equals(testCase.getStatus(), TestPlanTestCaseStatus.Underway.name())) {
if (!StringUtils.equals(testCase.getReviewStatus(), TestReviewCaseStatus.Prepare.name())) {
testReview.setReviewed(testReview.getReviewed() + 1);
}
if (StringUtils.equals(testCase.getReviewStatus(), TestReviewCaseStatus.Pass.name())) {
testReview.setPass(testReview.getPass() + 1);
}
});
}
testReview.setTestRate(MathUtils.getPercentWithDecimal(testReview.getTotal() == 0 ? 0 : testReview.getReviewed() * 1.0 / testReview.getTotal()));
});
}
return testReviews;

View File

@ -10,6 +10,7 @@ import io.metersphere.base.mapper.*;
import io.metersphere.base.mapper.ext.ExtTestCaseMapper;
import io.metersphere.commons.constants.RoleConstants;
import io.metersphere.commons.constants.TestCaseConstants;
import io.metersphere.commons.constants.TestCaseReviewStatus;
import io.metersphere.commons.exception.MSException;
import io.metersphere.commons.user.SessionUser;
import io.metersphere.commons.utils.BeanUtils;
@ -88,6 +89,7 @@ public class TestCaseService {
testCase.setCreateTime(System.currentTimeMillis());
testCase.setUpdateTime(System.currentTimeMillis());
testCase.setNum(getNextNum(testCase.getProjectId()));
testCase.setReviewStatus(TestCaseReviewStatus.Prepare.name());
testCaseMapper.insert(testCase);
}
@ -273,6 +275,8 @@ public class TestCaseService {
.map(TestCase::getName)
.collect(Collectors.toSet());
List<ExcelErrData<TestCaseExcelData>> errList = null;
if (multipartFile == null)
MSException.throwException(Translator.get("upload_fail"));
if (multipartFile.getOriginalFilename().endsWith(".xmind")) {
try {
@ -284,6 +288,11 @@ public class TestCaseService {
ExcelErrData excelErrData = new ExcelErrData(null, 1, Translator.get("upload_fail") + "" + processLog);
errList.add(excelErrData);
excelResponse.setErrList(errList);
} else if (xmindParser.getNodePaths().isEmpty() && xmindParser.getTestCase().isEmpty()) {
excelResponse.setSuccess(false);
ExcelErrData excelErrData = new ExcelErrData(null, 1, Translator.get("upload_fail") + "" + Translator.get("upload_content_is_null"));
errList.add(excelErrData);
excelResponse.setErrList(errList);
} else {
if (!xmindParser.getNodePaths().isEmpty()) {
testCaseNodeService.createNodes(xmindParser.getNodePaths(), projectId);
@ -295,7 +304,8 @@ public class TestCaseService {
excelResponse.setSuccess(true);
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.error(e.getMessage(), e);
MSException.throwException(e.getMessage());
}
} else {
@ -339,6 +349,7 @@ public class TestCaseService {
testcase.setNodeId(nodePathMap.get(testcase.getNodePath()));
testcase.setSort(sort.getAndIncrement());
testcase.setNum(num.decrementAndGet());
testcase.setReviewStatus(TestCaseReviewStatus.Prepare.name());
mapper.insert(testcase);
});
}

View File

@ -1,6 +1,7 @@
package io.metersphere.track.service;
import io.metersphere.base.domain.*;
import io.metersphere.base.mapper.TestCaseMapper;
import io.metersphere.base.mapper.TestCaseReviewMapper;
import io.metersphere.base.mapper.TestCaseReviewTestCaseMapper;
import io.metersphere.base.mapper.TestCaseReviewUsersMapper;
@ -38,6 +39,8 @@ public class TestReviewTestCaseService {
TestCaseReviewMapper testCaseReviewMapper;
@Resource
TestCaseReviewService testCaseReviewService;
@Resource
TestCaseMapper testCaseMapper;
public List<TestReviewCaseDTO> list(QueryCaseReviewRequest request) {
request.setOrders(ServiceUtils.getDefaultOrder(request.getOrders()));
@ -111,9 +114,17 @@ public class TestReviewTestCaseService {
MSException.throwException("此用例评审已到截止时间!");
}
// 记录测试用例评审状态变更
testCaseReviewTestCase.setStatus(testCaseReviewTestCase.getStatus());
testCaseReviewTestCase.setReviewer(SessionUtils.getUser().getId());
testCaseReviewTestCase.setUpdateTime(System.currentTimeMillis());
testCaseReviewTestCaseMapper.updateByPrimaryKeySelective(testCaseReviewTestCase);
// 修改用例评审状态
String caseId = testCaseReviewTestCase.getCaseId();
TestCaseWithBLOBs testCase = new TestCaseWithBLOBs();
testCase.setId(caseId);
testCase.setReviewStatus(testCaseReviewTestCase.getStatus());
testCaseMapper.updateByPrimaryKeySelective(testCase);
}
}

View File

@ -33,13 +33,10 @@ public class XmindCaseParser {
private StringBuffer process; // 过程校验记录
// 已存在用例名称
private Set<String> testCaseNames;
// 转换后的案例信息
private List<TestCaseWithBLOBs> testCases;
// 案例详情重写了hashCode方法去重用
private List<TestCaseExcelData> compartDatas;
// 记录没有用例的目录
private List<String> nodePaths;
@ -54,7 +51,10 @@ public class XmindCaseParser {
nodePaths = new ArrayList<>();
}
// 这里清理是为了 加快jvm 回收
private static final String TC_REGEX = "(?:tc:|tc|tc)";
private static final String PC_REGEX = "(?:pc:|pc|pc)";
private static final String RC_REGEX = "(?:rc:|rc|rc)";
public void clear() {
compartDatas.clear();
testCases.clear();
@ -90,9 +90,9 @@ public class XmindCaseParser {
}
// 递归处理案例数据
private void recursion(StringBuffer processBuffer, Attached parent, int level, List<Attached> attacheds) {
private void recursion(Attached parent, int level, List<Attached> attacheds) {
for (Attached item : attacheds) {
if (isAvailable(item.getTitle(), "(?:tc|tc:|tc)")) { // 用例
if (isAvailable(item.getTitle(), TC_REGEX)) { // 用例
item.setParent(parent);
this.newTestCase(item.getTitle(), parent.getPath(), item.getChildren() != null ? item.getChildren().getAttached() : null);
} else {
@ -100,7 +100,7 @@ public class XmindCaseParser {
item.setPath(nodePath);
item.setParent(parent);
if (item.getChildren() != null && !item.getChildren().getAttached().isEmpty()) {
recursion(processBuffer, item, level + 1, item.getChildren().getAttached());
recursion(item, level + 1, item.getChildren().getAttached());
} else {
if (!nodePath.startsWith("/")) {
nodePath = "/" + nodePath;
@ -163,7 +163,7 @@ public class XmindCaseParser {
return;
}
// 用例名称
testCase.setName(this.replace(tcArr[1], "tc:|tc|tc"));
testCase.setName(this.replace(tcArr[1], TC_REGEX));
if (!nodePath.startsWith("/")) {
nodePath = "/" + nodePath;
@ -188,10 +188,10 @@ public class XmindCaseParser {
List<Attached> steps = new LinkedList<>();
if (attacheds != null && !attacheds.isEmpty()) {
attacheds.forEach(item -> {
if (isAvailable(item.getTitle(), "(?:pc:|pc)")) {
testCase.setPrerequisite(replace(item.getTitle(), "(?:pc:|pc)"));
} else if (isAvailable(item.getTitle(), "(?:rc:|rc)")) {
testCase.setRemark(replace(item.getTitle(), "(?:rc:|rc)"));
if (isAvailable(item.getTitle(), PC_REGEX)) {
testCase.setPrerequisite(replace(item.getTitle(), PC_REGEX));
} else if (isAvailable(item.getTitle(), RC_REGEX)) {
testCase.setRemark(replace(item.getTitle(), RC_REGEX));
} else {
steps.add(item);
}
@ -267,28 +267,37 @@ public class XmindCaseParser {
// 导入思维导图处理
public String parse(MultipartFile multipartFile) {
StringBuffer processBuffer = new StringBuffer();
try {
// 获取思维导图内容
JsonRootBean root = XmindParser.parseObject(multipartFile);
if (root != null && root.getRootTopic() != null && root.getRootTopic().getChildren() != null) {
// 判断是模块还是用例
for (Attached item : root.getRootTopic().getChildren().getAttached()) {
if (isAvailable(item.getTitle(), "(?:tc:|tc|tc)")) { // 用例
return replace(item.getTitle(), "(?:tc:|tc|tc)") + "" + Translator.get("test_case_create_module_fail");
} else {
item.setPath(item.getTitle());
if (item.getChildren() != null && !item.getChildren().getAttached().isEmpty()) {
recursion(processBuffer, item, 1, item.getChildren().getAttached());
List<JsonRootBean> roots = XmindParser.parseObject(multipartFile);
for (JsonRootBean root : roots) {
if (root != null && root.getRootTopic() != null && root.getRootTopic().getChildren() != null) {
// 判断是模块还是用例
for (Attached item : root.getRootTopic().getChildren().getAttached()) {
if (isAvailable(item.getTitle(), TC_REGEX)) { // 用例
return replace(item.getTitle(), TC_REGEX) + "" + Translator.get("test_case_create_module_fail");
} else {
String nodePath = item.getTitle();
item.setPath(nodePath);
if (item.getChildren() != null && !item.getChildren().getAttached().isEmpty()) {
recursion(item, 1, item.getChildren().getAttached());
} else {
if (!nodePath.startsWith("/")) {
nodePath = "/" + nodePath;
}
if (nodePath.endsWith("/")) {
nodePath = nodePath.substring(0, nodePath.length() - 1);
}
nodePaths.add(nodePath); // 没有用例的路径
}
}
}
}
}
this.validate();
this.validate(); //检查目录合规性
} catch (Exception ex) {
processBuffer.append(Translator.get("incorrect_format"));
LogUtil.error(ex.getMessage());
return "xmind "+Translator.get("incorrect_format");
return ex.getMessage();
}
return process.toString();
}

View File

@ -5,75 +5,83 @@ import org.json.JSONObject;
import org.json.XML;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class XmindLegacy {
/**
* 返回content.xml和comments.xml合并后的json
*
* @param xmlContent
* @param xmlComments
* @return
* @throws IOException
* @throws DocumentException
*/
public static String getContent(String xmlContent, String xmlComments) throws IOException, DocumentException {
// 删除content.xml里面不能识别的字符串
xmlContent = xmlContent.replace("xmlns=\"urn:xmind:xmap:xmlns:content:2.0\"", "");
xmlContent = xmlContent.replace("xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"", "");
// 删除<topic>节点
xmlContent = xmlContent.replace("<topics type=\"attached\">", "");
xmlContent = xmlContent.replace("</topics>", "");
/**
* 返回content.xml和comments.xml合并后的json
*
* @param xmlContent
* @param xmlComments
* @return
* @throws IOException
* @throws DocumentException
*/
public static List<String> getContent(String xmlContent, String xmlComments) throws IOException, DocumentException {
// 删除content.xml里面不能识别的字符串
xmlContent = xmlContent.replace("xmlns=\"urn:xmind:xmap:xmlns:content:2.0\"", "");
xmlContent = xmlContent.replace("xmlns:fo=\"http://www.w3.org/1999/XSL/Format\"", "");
// 删除<topic>节点
xmlContent = xmlContent.replace("<topics type=\"attached\">", "");
xmlContent = xmlContent.replace("</topics>", "");
// 去除title中svg:width属性
xmlContent = xmlContent.replaceAll("<title svg:width=\"[0-9]*\">", "<title>");
// 去除title中svg:width属性
xmlContent = xmlContent.replaceAll("<title svg:width=\"[0-9]*\">", "<title>");
//去除自由风格主题
xmlContent = xmlContent.replaceAll("<topics type=\"detached\">", "");
Document document = DocumentHelper.parseText(xmlContent);// 读取XML文件,获得document对象
Element root = document.getRootElement();
List<Node> topics = root.selectNodes("//topic");
Document document = DocumentHelper.parseText(xmlContent);// 读取XML文件,获得document对象
Element root = document.getRootElement();
List<Node> topics = root.selectNodes("//topic");
if (xmlComments != null) {
// 删除comments.xml里面不能识别的字符串
xmlComments = xmlComments.replace("xmlns=\"urn:xmind:xmap:xmlns:comments:2.0\"", "");
if (xmlComments != null) {
// 删除comments.xml里面不能识别的字符串
xmlComments = xmlComments.replace("xmlns=\"urn:xmind:xmap:xmlns:comments:2.0\"", "");
// 添加评论到content中
Document commentDocument = DocumentHelper.parseText(xmlComments);
List<Node> commentsList = commentDocument.selectNodes("//comment");
// 添加评论到content中
Document commentDocument = DocumentHelper.parseText(xmlComments);
List<Node> commentsList = commentDocument.selectNodes("//comment");
for (Node topic : topics) {
for (Node commentNode : commentsList) {
Element commentElement = (Element) commentNode;
Element topicElement = (Element) topic;
if (topicElement.attribute("id").getValue()
.equals(commentElement.attribute("object-id").getValue())) {
Element comment = topicElement.addElement("comments");
comment.addAttribute("creationTime", commentElement.attribute("time").getValue());
comment.addAttribute("author", commentElement.attribute("author").getValue());
comment.addAttribute("content", commentElement.element("content").getText());
}
}
for (Node topic : topics) {
for (Node commentNode : commentsList) {
Element commentElement = (Element) commentNode;
Element topicElement = (Element) topic;
if (topicElement.attribute("id").getValue()
.equals(commentElement.attribute("object-id").getValue())) {
Element comment = topicElement.addElement("comments");
comment.addAttribute("creationTime", commentElement.attribute("time").getValue());
comment.addAttribute("author", commentElement.attribute("author").getValue());
comment.addAttribute("content", commentElement.element("content").getText());
}
}
}
}
}
}
// 第一个topic转换为json中的rootTopic
Node rootTopic = root.selectSingleNode("/xmap-content/sheet/topic");
rootTopic.setName("rootTopic");
// 第一个topic转换为json中的rootTopic
List<Node> rootTopics = root.selectNodes("/xmap-content/sheet/topic");
for (Node rootTopic : rootTopics) {
rootTopic.setName("rootTopic");
// 将xml中topic节点转换为attached节点
List<Node> topicList = rootTopic.selectNodes("//topic");
// 将xml中topic节点转换为attached节点
List<Node> topicList = rootTopic.selectNodes("//topic");
for (Node node : topicList) {
node.setName("attached");
}
for (Node node : topicList) {
node.setName("attached");
}
// 选取第一个sheet
Element sheet = root.elements("sheet").get(0);
String res = sheet.asXML();
// 将xml转为json
JSONObject xmlJSONObj = XML.toJSONObject(res);
JSONObject jsonObject = xmlJSONObj.getJSONObject("sheet");
// 设置缩进
return jsonObject.toString(4);
}
}
List<String> sheets = new ArrayList<>();
for (Element sheet : root.elements("sheet")) {
String res = sheet.asXML();
// 将xml转为json
JSONObject xmlJSONObj = XML.toJSONObject(res);
JSONObject jsonObject = xmlJSONObj.getJSONObject("sheet");
sheets.add(jsonObject.toString(4));
}
// 设置缩进
return sheets;
}
}

View File

@ -34,61 +34,68 @@ public class XmindParser {
* @throws ArchiveException
* @throws DocumentException
*/
public static String parseJson(MultipartFile multipartFile) throws IOException, ArchiveException, DocumentException {
public static List<String> parseJson(MultipartFile multipartFile) throws IOException, ArchiveException, DocumentException {
File file = FileUtil.multipartFileToFile(multipartFile);
List<String> contents = null;
String res = null;
if (file == null || !file.exists())
MSException.throwException(Translator.get("incorrect_format"));
String res = ZipUtils.extract(file);
String content = null;
if (isXmindZen(res, file)) {
content = getXmindZenContent(file, res);
} else {
content = getXmindLegacyContent(file, res);
try {
res = ZipUtils.extract(file);
if (isXmindZen(res, file)) {
contents = (getXmindZenContent(file, res));
} else {
contents = getXmindLegacyContent(file, res);
}
} catch (Exception e) {
MSException.throwException(e.getMessage());
} finally {
// 删除生成的文件夹
if (res != null) {
File dir = new File(res);
FileUtil.deleteDir(dir);
}
// 删除零时文件
if (file != null)
file.delete();
}
// 删除生成的文件夹
File dir = new File(res);
FileUtil.deleteDir(dir);
JsonRootBean jsonRootBean = JSON.parseObject(content, JsonRootBean.class);
// 删除零时文件
if (file != null)
file.delete();
String json = (JSON.toJSONString(jsonRootBean, false));
if (StringUtils.isEmpty(content) || content.split("(?:tc:|tc|TC:|TC|tc|TC)").length == 1) {
MSException.throwException(Translator.get("import_xmind_not_found"));
}
if (!StringUtils.isEmpty(content) && content.split("(?:tc:|tc|TC:|TC|tc|TC)").length > 500) {
MSException.throwException(Translator.get("import_xmind_count_error"));
}
return json;
return contents;
}
public static JsonRootBean parseObject(MultipartFile multipartFile) throws DocumentException, ArchiveException, IOException {
String content = parseJson(multipartFile);
JsonRootBean jsonRootBean = JSON.parseObject(content, JsonRootBean.class);
return jsonRootBean;
public static List<JsonRootBean> parseObject(MultipartFile multipartFile) throws DocumentException, ArchiveException, IOException {
List<String> contents = parseJson(multipartFile);
int caseCount = 0;
List<JsonRootBean> jsonRootBeans = new ArrayList<>();
if (contents != null) {
for (String content : contents) {
caseCount += content.split("(?:tc:|tc|TC:|TC|tc|TC)").length;
JsonRootBean jsonRootBean = JSON.parseObject(content, JsonRootBean.class);
jsonRootBeans.add(jsonRootBean);
}
if (caseCount > 500) {
MSException.throwException(Translator.get("import_xmind_count_error"));
}
}
return jsonRootBeans;
}
/**
* @return
*/
public static String getXmindZenContent(File file, String extractFileDir)
public static List<String> getXmindZenContent(File file, String extractFileDir)
throws IOException, ArchiveException {
List<String> keys = new ArrayList<>();
keys.add(xmindZenJson);
Map<String, String> map = ZipUtils.getContents(keys, file, extractFileDir);
String content = map.get(xmindZenJson);
content = XmindZen.getContent(content);
return content;
return XmindZen.getContent(content);
}
/**
* @return
*/
public static String getXmindLegacyContent(File file, String extractFileDir)
public static List<String> getXmindLegacyContent(File file, String extractFileDir)
throws IOException, ArchiveException, DocumentException {
List<String> keys = new ArrayList<>();
keys.add(xmindLegacyContent);
@ -97,7 +104,7 @@ public class XmindParser {
String contentXml = map.get(xmindLegacyContent);
String commentsXml = map.get(xmindLegacyComments);
String xmlContent = XmindLegacy.getContent(contentXml, commentsXml);
List<String> xmlContent = XmindLegacy.getContent(contentXml, commentsXml);
return xmlContent;
}

View File

@ -5,61 +5,68 @@ import com.alibaba.fastjson.JSONObject;
import org.dom4j.DocumentException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class XmindZen {
/**
* @param jsonContent
* @return
* @throws IOException
* @throws DocumentException
*/
public static String getContent(String jsonContent) {
JSONObject jsonObject = JSONArray.parseArray(jsonContent).getJSONObject(0);
JSONObject rootTopic = jsonObject.getJSONObject("rootTopic");
transferNotes(rootTopic);
JSONObject children = rootTopic.getJSONObject("children");
recursionChildren(children);
return jsonObject.toString();
}
/**
* @param jsonContent
* @return
* @throws IOException
* @throws DocumentException
*/
public static List<String> getContent(String jsonContent) {
JSONArray jsonArray = JSONArray.parseArray(jsonContent);//.getJSONObject(0);
List<String> contents = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
JSONObject rootTopic = jsonObject.getJSONObject("rootTopic");
transferNotes(rootTopic);
JSONObject children = rootTopic.getJSONObject("children");
recursionChildren(children);
contents.add(jsonObject.toString());
}
return contents;
}
/**
* 递归转换children
*
* @param children
*/
private static void recursionChildren(JSONObject children) {
if (children == null) {
return;
}
JSONArray attachedArray = children.getJSONArray("attached");
if (attachedArray == null) {
return;
}
for (Object attached : attachedArray) {
JSONObject attachedObject = (JSONObject) attached;
transferNotes(attachedObject);
JSONObject childrenObject = attachedObject.getJSONObject("children");
if (childrenObject == null) {
continue;
}
recursionChildren(childrenObject);
}
}
/**
* 递归转换children
*
* @param children
*/
private static void recursionChildren(JSONObject children) {
if (children == null) {
return;
}
JSONArray attachedArray = children.getJSONArray("attached");
if (attachedArray == null) {
return;
}
for (Object attached : attachedArray) {
JSONObject attachedObject = (JSONObject) attached;
transferNotes(attachedObject);
JSONObject childrenObject = attachedObject.getJSONObject("children");
if (childrenObject == null) {
continue;
}
recursionChildren(childrenObject);
}
}
private static void transferNotes(JSONObject object) {
JSONObject notes = object.getJSONObject("notes");
if (notes == null) {
return;
}
JSONObject plain = notes.getJSONObject("plain");
if (plain != null) {
String content = plain.getString("content");
notes.remove("plain");
notes.put("content", content);
} else {
notes.put("content", null);
}
}
private static void transferNotes(JSONObject object) {
JSONObject notes = object.getJSONObject("notes");
if (notes == null) {
return;
}
JSONObject plain = notes.getJSONObject("plain");
if (plain != null) {
String content = plain.getString("content");
notes.remove("plain");
notes.put("content", content);
} else {
notes.put("content", null);
}
}
}

@ -1 +1 @@
Subproject commit cf6b06526324326a563d933e07118fac014a63b4
Subproject commit c2dacf960cdb1ed35664bdd3432120b1203b73d8

View File

@ -0,0 +1,3 @@
alter table test_case add review_status varchar(25) null;
update test_case set review_status = 'Prepare' where review_status is null;

View File

@ -0,0 +1,2 @@
ALTER TABLE test_case
MODIFY maintainer varchar(50) NOT NULL COMMENT 'Test case maintainer';

View File

@ -158,3 +158,10 @@ license_valid_license_error=Authorization authentication failed
timing_task_result_notification=Timing task result notification
test_review_task_notice=Test review task notice
test_track.length_less_than=The title is too long, the length must be less than
# check owner
check_owner_project=The current user does not have permission to operate this project
check_owner_test=The current user does not have permission to operate this test
check_owner_case=The current user does not have permission to operate this use case
check_owner_plan=The current user does not have permission to operate this plan
check_owner_review=The current user does not have permission to operate this review
upload_content_is_null=Imported content is empty

View File

@ -158,4 +158,10 @@ import_xmind_not_found=未找到测试用例
timing_task_result_notification=定时任务结果通知
test_review_task_notice=测试评审任务通知
test_track.length_less_than=标题过长,字数必须小于
# check owner
check_owner_project=当前用户没有操作此项目的权限
check_owner_test=当前用户没有操作此测试的权限
check_owner_case=当前用户没有操作此用例的权限
check_owner_plan=当前用户没有操作此计划的权限
check_owner_review=当前用户没有操作此评审的权限
upload_content_is_null=导入内容为空

View File

@ -158,4 +158,11 @@ import_xmind_count_error=思維導圖導入用例數量不能超過 500 條
import_xmind_not_found=未找到测试用例
timing_task_result_notification=定時任務結果通知
test_review_task_notice=測試評審任務通知
test_track.length_less_than=標題過長,字數必須小於
test_track.length_less_than=標題過長,字數必須小於
# check owner
check_owner_project=當前用戶沒有操作此項目的權限
check_owner_test=當前用戶沒有操作此測試的權限
check_owner_case=當前用戶沒有操作此用例的權限
check_owner_plan=當前用戶沒有操作此計劃的權限
check_owner_review=當前用戶沒有操作此評審的權限
upload_content_is_null=導入內容為空

View File

@ -32,7 +32,8 @@
"js-base64": "^3.4.4",
"json-bigint": "^1.0.0",
"html2canvas": "^1.0.0-rc.7",
"jspdf": "^2.1.1"
"jspdf": "^2.1.1",
"yan-progress": "^1.0.3"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.1.0",

View File

@ -3,7 +3,7 @@
<template v-slot:header>
<span class="title">{{$t('api_report.title')}}</span>
</template>
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link">
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link" height="300px">
<el-table-column prop="name" :label="$t('commons.name')" width="150" show-overflow-tooltip/>
<el-table-column width="250" :label="$t('commons.create_time')">
<template v-slot:default="scope">

View File

@ -3,7 +3,7 @@
<template v-slot:header>
<span class="title">{{$t('commons.test')}}</span>
</template>
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link">
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link" height="300px">
<el-table-column prop="name" :label="$t('commons.name')" width="150" show-overflow-tooltip/>
<el-table-column prop="projectName" :label="$t('load_test.project_name')" width="150" show-overflow-tooltip/>
<el-table-column width="250" :label="$t('commons.create_time')">

View File

@ -65,7 +65,6 @@ export default {
},
mounted() {
console.log(this.response.headers);
if (!this.response.headers) {
return;
}

View File

@ -70,348 +70,348 @@
</template>
<script>
import MsApiScenarioConfig from "./components/ApiScenarioConfig";
import {Scenario, Test} from "./model/ScenarioModel"
import MsApiReportStatus from "../report/ApiReportStatus";
import MsApiReportDialog from "./ApiReportDialog";
import {checkoutTestManagerOrTestUser, downloadFile, getUUID} from "@/common/js/utils";
import MsScheduleConfig from "../../common/components/MsScheduleConfig";
import ApiImport from "./components/import/ApiImport";
import {ApiEvent, LIST_CHANGE} from "@/business/components/common/head/ListEvent";
import MsContainer from "@/business/components/common/components/MsContainer";
import MsMainContainer from "@/business/components/common/components/MsMainContainer";
import MsApiScenarioConfig from "./components/ApiScenarioConfig";
import {Scenario, Test} from "./model/ScenarioModel"
import MsApiReportStatus from "../report/ApiReportStatus";
import MsApiReportDialog from "./ApiReportDialog";
import {checkoutTestManagerOrTestUser, downloadFile, getUUID} from "@/common/js/utils";
import MsScheduleConfig from "../../common/components/MsScheduleConfig";
import ApiImport from "./components/import/ApiImport";
import {ApiEvent, LIST_CHANGE} from "@/business/components/common/head/ListEvent";
import MsContainer from "@/business/components/common/components/MsContainer";
import MsMainContainer from "@/business/components/common/components/MsMainContainer";
export default {
name: "MsApiTestConfig",
export default {
name: "MsApiTestConfig",
components: {
MsMainContainer,
MsContainer, ApiImport, MsScheduleConfig, MsApiReportDialog, MsApiReportStatus, MsApiScenarioConfig
},
props: ["id"],
data() {
return {
reportVisible: false,
create: false,
result: {},
projects: [],
change: false,
test: new Test(),
isReadOnly: false,
debugReportId: ''
}
},
watch: {
'$route': 'init',
test: {
handler: function () {
this.change = true;
},
deep: true
}
},
methods: {
init() {
let projectId;
this.isReadOnly = !checkoutTestManagerOrTestUser();
if (this.id) {
this.create = false;
this.getTest(this.id);
} else {
this.create = true;
this.test = new Test();
if (this.$refs.config) {
this.$refs.config.reset();
}
//
projectId = this.$store.state.common.projectId;
}
this.result = this.$get("/project/listAll", response => {
this.projects = response.data;
//
if (projectId) this.test.projectId = projectId;
})
components: {
MsMainContainer,
MsContainer, ApiImport, MsScheduleConfig, MsApiReportDialog, MsApiReportStatus, MsApiScenarioConfig
},
updateReference() {
let updateIds = [];
this.test.scenarioDefinition.forEach(scenario => {
if (scenario.isReference()) {
updateIds.push(scenario.id.split("#")[0]);
}
})
if (updateIds.length === 0) return;
//
this.result = this.$post("/api/list/ids", {ids: updateIds}, response => {
let scenarioMap = {};
if (response.data) {
response.data.forEach(test => {
JSON.parse(test.scenarioDefinition).forEach(options => {
let referenceId = test.id + "#" + options.id;
scenarioMap[referenceId] = new Scenario(options);
scenarioMap[referenceId].id = referenceId;
})
})
}
props: ["id"],
let scenarios = [];
data() {
return {
reportVisible: false,
create: false,
result: {},
projects: [],
change: false,
test: new Test(),
isReadOnly: false,
debugReportId: ''
}
},
watch: {
'$route': 'init',
test: {
handler: function () {
this.change = true;
},
deep: true
}
},
methods: {
init() {
let projectId;
this.isReadOnly = !checkoutTestManagerOrTestUser();
if (this.id) {
this.create = false;
this.getTest(this.id);
} else {
this.create = true;
this.test = new Test();
if (this.$refs.config) {
this.$refs.config.reset();
}
//
projectId = this.$store.state.common.projectId;
}
this.result = this.$get("/project/listAll", response => {
this.projects = response.data;
//
if (projectId) this.test.projectId = projectId;
})
},
updateReference() {
let updateIds = [];
this.test.scenarioDefinition.forEach(scenario => {
if (scenario.isReference()) {
if (scenarioMap[scenario.id]) scenarios.push(scenarioMap[scenario.id]);
} else {
scenarios.push(scenario);
updateIds.push(scenario.id.split("#")[0]);
}
})
this.test.scenarioDefinition = scenarios;
})
},
getTest(id) {
this.result = this.$get("/api/get/" + id, response => {
if (response.data) {
let item = response.data;
this.test = new Test({
id: item.id,
projectId: item.projectId,
name: item.name,
status: item.status,
scenarioDefinition: JSON.parse(item.scenarioDefinition),
schedule: item.schedule ? item.schedule : {},
});
this.updateReference();
if (updateIds.length === 0) return;
//
this.result = this.$post("/api/list/ids", {ids: updateIds}, response => {
let scenarioMap = {};
if (response.data) {
response.data.forEach(test => {
JSON.parse(test.scenarioDefinition).forEach(options => {
let referenceId = test.id + "#" + options.id;
scenarioMap[referenceId] = new Scenario(options);
scenarioMap[referenceId].id = referenceId;
})
})
}
this.$refs.config.reset();
}
});
},
save(callback) {
let validator = this.test.isValid();
if (!validator.isValid) {
this.$warning(this.$t(validator.info));
return;
}
this.change = false;
let bodyFiles = this.getBodyUploadFiles();
let url = this.create ? "/api/create" : "/api/update";
let jmx = this.test.toJMX();
let blob = new Blob([jmx.xml], {type: "application/octet-stream"});
let file = new File([blob], jmx.name);
this.result = this.$fileUpload(url, file, bodyFiles, this.test, () => {
if (callback) callback();
this.create = false;
this.resetBodyFile();
});
},
saveTest() {
this.save(() => {
this.$success(this.$t('commons.save_success'));
if (this.create) {
this.$router.push({
path: '/api/test/edit?id=' + this.test.id
let scenarios = [];
this.test.scenarioDefinition.forEach(scenario => {
if (scenario.isReference()) {
if (scenarioMap[scenario.id]) scenarios.push(scenarioMap[scenario.id]);
} else {
scenarios.push(scenario);
}
})
}
// 广 head
ApiEvent.$emit(LIST_CHANGE);
})
},
runTest() {
this.result = this.$post("/api/run", {id: this.test.id, triggerMode: 'MANUAL'}, (response) => {
this.$success(this.$t('api_test.running'));
this.$router.push({
path: '/api/report/view/' + response.data
this.test.scenarioDefinition = scenarios;
})
});
},
saveRunTest() {
this.change = false;
if (!this.validateEnableTest()) {
this.$warning(this.$t('api_test.enable_validate_tip'));
return;
}
this.save(() => {
this.$success(this.$t('commons.save_success'));
this.runTest();
// 广 head
ApiEvent.$emit(LIST_CHANGE);
})
},
getBodyUploadFiles() {
let bodyUploadFiles = [];
this.test.bodyUploadIds = [];
this.test.scenarioDefinition.forEach(scenario => {
scenario.requests.forEach(request => {
if (request.body) {
request.body.kvs.forEach(param => {
if (param.files) {
param.files.forEach(item => {
if (item.file) {
let fileId = getUUID().substring(0, 8);
item.name = item.file.name;
item.id = fileId;
this.test.bodyUploadIds.push(fileId);
bodyUploadFiles.push(item.file);
}
});
}
},
getTest(id) {
this.result = this.$get("/api/get/" + id, response => {
if (response.data) {
let item = response.data;
this.test = new Test({
id: item.id,
projectId: item.projectId,
name: item.name,
status: item.status,
scenarioDefinition: JSON.parse(item.scenarioDefinition),
schedule: item.schedule ? item.schedule : {},
});
this.updateReference();
this.$refs.config.reset();
}
});
});
return bodyUploadFiles;
},
validateEnableTest() {
for (let scenario of this.test.scenarioDefinition) {
if (scenario.enable) {
for (let request of scenario.requests) {
if (request.enable) {
return true;
},
save(callback) {
let validator = this.test.isValid();
if (!validator.isValid) {
this.$warning(this.$t(validator.info));
return;
}
this.change = false;
let bodyFiles = this.getBodyUploadFiles();
let url = this.create ? "/api/create" : "/api/update";
let jmx = this.test.toJMX();
let blob = new Blob([jmx.xml], {type: "application/octet-stream"});
let file = new File([blob], jmx.name);
this.result = this.$fileUpload(url, file, bodyFiles, this.test, () => {
if (callback) callback();
this.create = false;
this.resetBodyFile();
});
},
saveTest() {
this.save(() => {
this.$success(this.$t('commons.save_success'));
if (this.create) {
this.$router.push({
path: '/api/test/edit?id=' + this.test.id
})
}
// 广 head
ApiEvent.$emit(LIST_CHANGE);
})
},
runTest() {
this.result = this.$post("/api/run", {id: this.test.id, triggerMode: 'MANUAL'}, (response) => {
this.$success(this.$t('api_test.running'));
this.$router.push({
path: '/api/report/view/' + response.data
})
});
},
saveRunTest() {
this.change = false;
if (!this.validateEnableTest()) {
this.$warning(this.$t('api_test.enable_validate_tip'));
return;
}
this.save(() => {
this.$success(this.$t('commons.save_success'));
this.runTest();
// 广 head
ApiEvent.$emit(LIST_CHANGE);
})
},
getBodyUploadFiles() {
let bodyUploadFiles = [];
this.test.bodyUploadIds = [];
this.test.scenarioDefinition.forEach(scenario => {
scenario.requests.forEach(request => {
if (request.body) {
request.body.kvs.forEach(param => {
if (param.files) {
param.files.forEach(item => {
if (item.file) {
let fileId = getUUID().substring(0, 8);
item.name = item.file.name;
item.id = fileId;
this.test.bodyUploadIds.push(fileId);
bodyUploadFiles.push(item.file);
}
});
}
});
}
});
});
return bodyUploadFiles;
},
validateEnableTest() {
for (let scenario of this.test.scenarioDefinition) {
if (scenario.enable) {
for (let request of scenario.requests) {
if (request.enable) {
return true;
}
}
}
}
}
return false;
},
resetBodyFile() {
//
this.test.scenarioDefinition.forEach(scenario => {
scenario.requests.forEach(request => {
if (request.body) {
request.body.kvs.forEach(param => {
if (param.files) {
param.files.forEach(item => {
if (item.file) {
item.file = undefined;
}
});
}
});
}
return false;
},
resetBodyFile() {
//
this.test.scenarioDefinition.forEach(scenario => {
scenario.requests.forEach(request => {
if (request.body) {
request.body.kvs.forEach(param => {
if (param.files) {
param.files.forEach(item => {
if (item.file) {
item.file = undefined;
}
});
}
});
}
});
});
});
},
cancel() {
this.$router.push('/api/test/list/all');
},
handleCommand(command) {
switch (command) {
case "report":
this.$refs.reportDialog.open();
break;
case "performance":
this.$store.commit('setTest', {
projectId: this.test.projectId,
name: this.test.name,
jmx: this.test.toJMX()
})
this.$router.push({
path: "/performance/test/create"
})
break;
case "export":
downloadFile(this.test.name + ".json", this.test.export());
break;
case "import":
this.$refs.apiImport.open();
break;
}
},
saveCronExpression(cronExpression) {
this.test.schedule.enable = true;
this.test.schedule.value = cronExpression;
this.saveSchedule();
},
saveSchedule() {
this.checkScheduleEdit();
let param = {};
param = this.test.schedule;
param.resourceId = this.test.id;
let url = '/api/schedule/create';
if (param.id) {
url = '/api/schedule/update';
}
this.$post(url, param, () => {
this.$success(this.$t('commons.save_success'));
this.getTest(this.test.id);
});
},
checkScheduleEdit() {
if (this.create) {
this.$message(this.$t('api_test.environment.please_save_test'));
return false;
}
return true;
},
runDebug(scenario) {
if (this.create) {
this.$warning(this.$t('api_test.environment.please_save_test'));
return;
}
},
cancel() {
this.$router.push('/api/test/list/all');
},
handleCommand(command) {
switch (command) {
case "report":
this.$refs.reportDialog.open();
break;
case "performance":
this.$store.commit('setTest', {
projectId: this.test.projectId,
name: this.test.name,
jmx: this.test.toJMX()
})
this.$router.push({
path: "/performance/test/create"
})
break;
case "export":
downloadFile(this.test.name + ".json", this.test.export());
break;
case "import":
this.$refs.apiImport.open();
break;
}
},
saveCronExpression(cronExpression) {
this.test.schedule.enable = true;
this.test.schedule.value = cronExpression;
this.saveSchedule();
},
saveSchedule() {
this.checkScheduleEdit();
let param = {};
param = this.test.schedule;
param.resourceId = this.test.id;
let url = '/api/schedule/create';
if (param.id) {
url = '/api/schedule/update';
}
this.$post(url, param, () => {
this.$success(this.$t('commons.save_success'));
this.getTest(this.test.id);
});
},
checkScheduleEdit() {
if (this.create) {
this.$message(this.$t('api_test.environment.please_save_test'));
return false;
}
return true;
},
runDebug(scenario) {
if (this.create) {
this.$warning(this.$t('api_test.environment.please_save_test'));
return;
}
let url = "/api/run/debug";
let runningTest = new Test();
Object.assign(runningTest, this.test);
let bodyFiles = this.getBodyUploadFiles();
runningTest.scenarioDefinition = [];
runningTest.scenarioDefinition.push(scenario);
let validator = runningTest.isValid();
if (!validator.isValid) {
this.$warning(this.$t(validator.info));
return;
}
let url = "/api/run/debug";
let runningTest = new Test();
Object.assign(runningTest, this.test);
let bodyFiles = this.getBodyUploadFiles();
runningTest.scenarioDefinition = [];
runningTest.scenarioDefinition.push(scenario);
let validator = runningTest.isValid();
if (!validator.isValid) {
this.$warning(this.$t(validator.info));
return;
}
let jmx = runningTest.toJMX();
let blob = new Blob([jmx.xml], {type: "application/octet-stream"});
let file = new File([blob], jmx.name);
this.$fileUpload(url, file, bodyFiles, this.test, response => {
this.debugReportId = response.data;
this.resetBodyFile();
});
let jmx = runningTest.toJMX();
let blob = new Blob([jmx.xml], {type: "application/octet-stream"});
let file = new File([blob], jmx.name);
this.$fileUpload(url, file, bodyFiles, this.test, response => {
this.debugReportId = response.data;
this.resetBodyFile();
});
},
handleEvent(event) {
if (event.keyCode === 83 && event.ctrlKey) {
console.log('拦截到 ctrl + s');//ctrl+s
this.saveTest();
event.preventDefault();
event.returnValue = false;
return false;
}
},
},
handleEvent(event) {
if (event.keyCode === 83 && event.ctrlKey) {
console.log('拦截到 ctrl + s');//ctrl+s
this.saveTest();
event.preventDefault();
event.returnValue = false;
return false;
}
},
},
created() {
this.init();
//
document.addEventListener('keydown', this.handleEvent)
},
beforeDestroy() {
document.removeEventListener('keydown', this.handleEvent);
created() {
this.init();
//
document.addEventListener('keydown', this.handleEvent)
},
beforeDestroy() {
document.removeEventListener('keydown', this.handleEvent);
}
}
}
</script>
<style scoped>
.test-container {
height: calc(100vh - 155px);
min-height: 600px;
}
.test-container {
height: calc(100vh - 155px);
min-height: 600px;
}
.test-name {
width: 600px;
margin-left: -20px;
margin-right: 20px;
}
.test-name {
width: 600px;
margin-left: -20px;
margin-right: 20px;
}
.test-project {
min-width: 150px;
}
.test-project {
min-width: 150px;
}
.test-container .more {
margin-left: 10px;
}
.test-container .more {
margin-left: 10px;
}
</style>

View File

@ -1043,11 +1043,8 @@ class JMXGenerator {
this.addScenarioHeaders(threadGroup, scenario);
this.addScenarioCookieManager(threadGroup, scenario);
// 放在计划或线程组中,不建议放具体某个请求中
this.addDNSCacheManager(threadGroup, scenario);
this.addJDBCDataSources(threadGroup, scenario);
scenario.requests.forEach(request => {
if (request.enable) {
if (!request.isValid()) return;
@ -1065,6 +1062,8 @@ class JMXGenerator {
sampler = new JDBCSampler(request.name || "", request);
}
this.addDNSCacheManager(sampler, scenario.environment, request.useEnvironment);
this.addRequestExtractor(sampler, request);
this.addRequestAssertion(sampler, request);
@ -1126,28 +1125,26 @@ class JMXGenerator {
}
}
addDNSCacheManager(threadGroup, scenario) {
if (scenario.requests.length < 1) {
return
}
let request = scenario.requests[0];
if (request.environment) {
let commonConfig = request.environment.config.commonConfig;
addDNSCacheManager(httpSamplerProxy, environment, useEnv) {
if (environment && useEnv === true) {
let commonConfig = environment.config.commonConfig;
let hosts = commonConfig.hosts;
if (commonConfig.enableHost && hosts.length > 0) {
let name = request.name + " DNSCacheManager";
let name = " DNSCacheManager";
// 强化判断如果未匹配到合适的host则不开启DNSCache
let domain = request.environment.config.httpConfig.domain;
let domain = environment.config.httpConfig.domain;
let validHosts = [];
hosts.forEach(item => {
let d = item.domain.trim().replace("http://", "").replace("https://", "");
if (item && d === domain.trim()) {
item.domain = d; // 域名去掉协议
validHosts.push(item);
if (item.domain != undefined && domain != undefined) {
let d = item.domain.trim().replace("http://", "").replace("https://", "");
if (d === domain.trim()) {
item.domain = d; // 域名去掉协议
validHosts.push(item);
}
}
});
if (validHosts.length > 0) {
threadGroup.put(new DNSCacheManager(name, validHosts));
httpSamplerProxy.put(new DNSCacheManager(name, validHosts));
}
}
}

View File

@ -41,6 +41,13 @@ router.beforeEach((to, from, next) => {
}
});
//重复点击导航路由报错
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error => error)
}
// 登入后跳转至原路径
function redirectLoginPath(originPath) {
let redirectUrl = sessionStorage.getItem('redirectUrl');

View File

@ -3,7 +3,7 @@
<template v-slot:header>
<span class="title">{{$t('api_report.title')}}</span>
</template>
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link">
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link" height="300px">
<el-table-column prop="name" :label="$t('commons.name')" width="150" show-overflow-tooltip/>
<el-table-column width="250" :label="$t('commons.create_time')">
<template v-slot:default="scope">

View File

@ -3,7 +3,7 @@
<template v-slot:header>
<span class="title">{{$t('commons.test')}}</span>
</template>
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link">
<el-table border :data="tableData" class="adjust-table table-content" @row-click="link" height="300px">
<el-table-column prop="name" :label="$t('commons.name')" width="150" show-overflow-tooltip/>
<el-table-column prop="projectName" :label="$t('load_test.project_name')" width="150" show-overflow-tooltip/>
<el-table-column width="250" :label="$t('commons.create_time')">

View File

@ -39,8 +39,7 @@
:disabled="!row.edit || readOnly"
size="mini"
v-model="row.enable"
active-color="#13ce66"
inactive-color="#ff4949">
inactive-color="#DCDFE6">
</el-switch>
</template>
</el-table-column>

View File

@ -37,8 +37,7 @@
<el-table-column prop="status" :label="$t('commons.status')">
<template v-slot:default="scope">
<el-switch v-model="scope.row.status"
active-color="#13ce66"
inactive-color="#ff4949"
inactive-color="#DCDFE6"
active-value="ACTIVE"
inactive-value="DISABLED"
@change="changeSwitch(scope.row)"

View File

@ -16,8 +16,7 @@
<el-table-column prop="status" :label="$t('test_resource_pool.enable_disable')">
<template v-slot:default="scope">
<el-switch v-model="scope.row.status"
active-color="#13ce66"
inactive-color="#ff4949"
inactive-color="#DCDFE6"
active-value="VALID"
inactive-value="INVALID"
@change="changeSwitch(scope.row)"

View File

@ -19,8 +19,7 @@
<el-table-column prop="status" :label="$t('commons.status')" width="120">
<template v-slot:default="scope">
<el-switch v-model="scope.row.status"
active-color="#13ce66"
inactive-color="#ff4949"
inactive-color="#DCDFE6"
active-value="1"
inactive-value="0"
@change="changeSwitch(scope.row)"

View File

@ -35,7 +35,6 @@
@filter-change="filter"
@select-all="handleSelectAll"
@select="handleSelectionChange"
@row-click="showDetail"
row-key="id"
class="test-content adjust-table">
<el-table-column
@ -54,7 +53,13 @@
<el-table-column
prop="name"
:label="$t('commons.name')"
show-overflow-tooltip>
show-overflow-tooltip
>
<template v-slot:default="scope">
<div @mouseover="showDetail(scope.row)">
<p>{{ scope.row.name }}</p>
</div>
</template>
</el-table-column>
<el-table-column
prop="priority"
@ -86,6 +91,18 @@
<method-table-item :value="scope.row.method"/>
</template>
</el-table-column>
<el-table-column
:filters="statusFilters"
column-key="status"
:label="$t('test_track.case.status')">
<template v-slot:default="scope">
<span class="el-dropdown-link">
<status-table-item :value="scope.row.reviewStatus"/>
</span>
</template>
</el-table-column>
<el-table-column
prop="nodePath"
:label="$t('test_track.case.module')"
@ -146,6 +163,7 @@
import BatchEdit from "./BatchEdit";
import {WORKSPACE_ID} from "../../../../../common/js/constants";
import {LIST_CHANGE, TrackEvent} from "@/business/components/common/head/ListEvent";
import StatusTableItem from "@/business/components/track/common/tableItems/planview/StatusTableItem";
export default {
name: "TestCaseList",
@ -163,7 +181,8 @@
NodeBreadcrumb,
MsTableHeader,
ShowMoreBtn,
BatchEdit
BatchEdit,
StatusTableItem
},
data() {
return {
@ -192,6 +211,11 @@
{text: this.$t('commons.performance'), value: 'performance'},
{text: this.$t('commons.api'), value: 'api'}
],
statusFilters: [
{text: this.$t('test_track.plan.plan_status_prepare'), value: 'Prepare'},
{text: this.$t('test_track.plan_view.pass'), value: 'Pass'},
{text: '未通过', value: 'UnPass'},
],
showMore: false,
buttons: [
{

View File

@ -5,7 +5,7 @@
border
:data="tableData"
@row-click="intoPlan"
v-loading="result.loading">
v-loading="result.loading" height="300px">
<el-table-column
prop="name"
fixed

View File

@ -14,7 +14,7 @@
border
:data="tableData"
@row-click="intoPlan"
v-loading="result.loading">
v-loading="result.loading" height="300px">
<el-table-column
prop="name"
fixed
@ -36,29 +36,19 @@
<el-table-column
prop="status"
:label="$t('test_track.plan.plan_status')"
show-overflow-tooltip>
:label="$t('test_track.plan.plan_status')">
<template v-slot:default="scope">
<plan-status-table-item :value="scope.row.status"/>
</template>
</el-table-column>
<el-table-column
prop="projectName"
:label="$t('test_track.review.done')"
show-overflow-tooltip>
:label="$t('test_track.review.result_distribution')">
<template v-slot:default="scope">
{{scope.row.reviewed}}/{{scope.row.total}}
</template>
</el-table-column>
<el-table-column
prop="projectName"
:label="$t('test_track.home.review_progress')"
min-width="100"
show-overflow-tooltip>
<template v-slot:default="scope">
<el-progress :percentage="scope.row.testRate"></el-progress>
<el-tooltip :content="getResultTip(scope.row.total,scope.row.reviewed,scope.row.pass)"
placement="top" :enterable="false" class="item" effect="dark">
<yan-progress :total="scope.row.total" :done="scope.row.reviewed" :modify="scope.row.pass" :tip="tip"/>
</el-tooltip>
</template>
</el-table-column>
@ -87,7 +77,12 @@ export default {
return {
result: {},
tableData: [],
showMyCreator: false
showMyCreator: false,
tip: [
{text: "X", fillStyle: '#D3D3D3'},
{text: "X", fillStyle: '#ee4545'},
{text: "X", fillStyle: '#4dcf4d'}
]
}
},
mounted() {
@ -115,11 +110,14 @@ export default {
},
searchMyCreator() {
this.showMyCreator = !this.showMyCreator;
if (this.showMyCreator){
if (this.showMyCreator) {
this.initTableData("creator");
} else {
this.initTableData("reviewer");
}
},
getResultTip(total, reviewed, pass) {
return '通过: ' + pass + '; ' + '未通过: ' + (reviewed - pass) + '; ' + '未评审: ' + (total - reviewed);
}
}
}

View File

@ -8,7 +8,7 @@
class="adjust-table"
@row-click="editTestCase"
:data="tableData"
v-loading="result.loading">
v-loading="result.loading" height="300px">
<el-table-column
prop="name"

View File

@ -62,6 +62,15 @@
<type-table-item :value="scope.row.type"/>
</template>
</el-table-column>
<el-table-column
:filters="statusFilters"
column-key="status"
:label="$t('test_track.case.status')"
show-overflow-tooltip>
<template v-slot:default="scope">
<status-table-item :value="scope.row.reviewStatus"/>
</template>
</el-table-column>
</el-table>
<div style="text-align: center"> {{testReviews.length}} </div>
</el-main>
@ -91,6 +100,7 @@ import MsTableHeader from "../../../../common/components/MsTableHeader";
import SwitchProject from "../../../case/components/SwitchProject";
import {TEST_CASE_CONFIGS} from "../../../../common/components/search/search-components";
import {_filter} from "../../../../../../common/js/utils";
import StatusTableItem from "@/business/components/track/common/tableItems/planview/StatusTableItem";
export default {
name: "TestReviewRelevance",
@ -102,7 +112,8 @@ export default {
MsTableSearchBar,
MsTableAdvSearchBar,
MsTableHeader,
SwitchProject
SwitchProject,
StatusTableItem
},
data() {
return {
@ -130,7 +141,12 @@ export default {
{text: this.$t('commons.functional'), value: 'functional'},
{text: this.$t('commons.performance'), value: 'performance'},
{text: this.$t('commons.api'), value: 'api'}
]
],
statusFilters: [
{text: this.$t('test_track.case.status_prepare'), value: 'Prepare'},
{text: this.$t('test_track.case.status_pass'), value: 'Pass'},
{text: this.$t('test_track.case.status_un_pass'), value: 'UnPass'},
],
};
},
props: {

View File

@ -283,6 +283,7 @@ export default {
saveCase(status) {
let param = {};
param.id = this.testCase.id;
param.caseId = this.testCase.caseId;
param.reviewId = this.testCase.reviewId;
param.status = status;
this.$post('/test/review/case/edit', param, () => {

View File

@ -104,13 +104,12 @@
</el-table-column>
<el-table-column
prop="status"
:filters="statusFilters"
column-key="status"
:label="$t('test_track.review_view.execute_result')">
<template v-slot:default="scope">
<span class="el-dropdown-link">
<status-table-item :value="scope.row.status"/>
<status-table-item :value="scope.row.reviewStatus"/>
</span>
</template>
</el-table-column>
@ -207,9 +206,9 @@ export default {
{text: this.$t('commons.api'), value: 'api'}
],
statusFilters: [
{text: this.$t('test_track.plan.plan_status_prepare'), value: 'Prepare'},
{text: this.$t('test_track.plan_view.pass'), value: 'Pass'},
{text: '未通过', value: 'UnPass'},
{text: this.$t('test_track.case.status_prepare'), value: 'Prepare'},
{text: this.$t('test_track.case.status_pass'), value: 'Pass'},
{text: this.$t('test_track.case.status_un_pass'), value: 'UnPass'},
],
showMore: false,
buttons: [

@ -1 +1 @@
Subproject commit 06d935cd1d22ab36f09763745c2aff8ad3fb08c1
Subproject commit cc38137a69a0f20fadece9c0f9f50a9468c4ace9

View File

@ -7,6 +7,7 @@ import ajax from "../common/js/ajax";
import App from './App.vue';
import message from "../common/js/message";
import router from "./components/common/router/router";
import YanProgress from 'yan-progress';
import './permission' // permission control
import i18n from "../i18n/i18n";
import store from "./store";
@ -28,6 +29,7 @@ Vue.use(chart);
Vue.use(CalendarHeatmap);
Vue.use(message);
Vue.use(CKEditor);
Vue.use(YanProgress)
// v-permission
Vue.directive('permission', permission);

View File

@ -53,6 +53,10 @@ export default {
login();
return;
}
if (error.response && error.response.status === 403) {
window.location.href = "/";
return;
}
result.loading = false;
window.console.error(error.response || error.message);
if (error.response && error.response.data) {

View File

@ -695,6 +695,10 @@ export default {
batch_delete_case: 'Batch delete',
batch_unlink: 'Batch Unlink',
project_name: "Project",
status: 'Status',
status_prepare: 'Prepare',
status_pass: 'Pass',
status_un_pass: 'UnPass',
import: {
import: "Import test case",
case_import: "Import test case",
@ -769,7 +773,8 @@ export default {
my_create: "My Create",
reviewed_by_me: "Review By Me",
creator: "Creator",
done: "Commented use cases"
done: "Commented use cases",
result_distribution: "Result Distribution"
},
comment: {
no_comment: "No Comment",

View File

@ -697,6 +697,10 @@ export default {
batch_delete_case: '批量删除用例',
batch_unlink: '批量取消关联',
project_name: '所属项目',
status: '状态',
status_prepare: '未开始',
status_pass: '通过',
status_un_pass: '未通过',
import: {
import: "导入用例",
case_import: "导入测试用例",
@ -771,7 +775,8 @@ export default {
my_create: "我创建的评审",
reviewed_by_me: "待我评审",
creator: "创建人",
done: "已评用例"
done: "已评用例",
result_distribution: "结果分布"
},
comment: {
no_comment: "暂无评论",
@ -785,7 +790,7 @@ export default {
all_case: "全部用例",
start_review: "开始评审",
relevance_case: "关联用例",
execute_result: "执行结果",
execute_result: "评审结果",
},
module: {
search: "搜索模块",

View File

@ -697,6 +697,10 @@ export default {
batch_delete_case: '批量刪除用例',
batch_unlink: '批量取消關聯',
project_name: '所屬項目',
status: '狀態',
status_prepare: '未開始',
status_pass: '通過',
status_un_pass: '未通過',
import: {
import: "導入用例",
case_import: "導入測試用例",
@ -771,7 +775,8 @@ export default {
my_create: "我創建的評審",
reviewed_by_me: "待我評審",
creator: "創建人",
done: "已評用例"
done: "已評用例",
result_distribution: "結果分佈"
},
comment: {
no_comment: "暫無評論",
@ -785,7 +790,7 @@ export default {
all_case: "全部用例",
start_review: "開始評審",
relevance_case: "關聯用例",
execute_result: "執行結果",
execute_result: "評審結果",
},
module: {
search: "搜索模塊",