从0到1开发测试平台(十四)性能测试用例管理页面对应的后台接口的编写

原创
2020/09/12 20:25
阅读数 648

| 前言


前面我们写好了登录和首页,这篇文章我们将编写性能测试用例管理功能对应的增删改查后台接口,这样方便我们下篇文章的前端页面调用。Let's begin.


| 新建性能测试用例表performance_case


SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;
-- ------------------------------ Table structure for performance_case-- ----------------------------DROP TABLE IF EXISTS `performance_case`;CREATE TABLE `performance_case` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `CASE_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `SCRIPT_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `SCRIPT_URL` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `SCRIPT_DATA_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `SCRIPT_DATA_URL` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `PROJECT_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `MODULE_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `OPERATOR` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `CREATE_DATE` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), `LAST_UPDATE_DATE` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), `IS_VALID` tinyint(2) UNSIGNED ZEROFILL NOT NULL DEFAULT 01, PRIMARY KEY (`ID`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;


| 编写与表对应的实体类PerformanceCase


package com.caomingyu.cctestplatform.bean;
import lombok.Data;import lombok.ToString;
import javax.persistence.*;
@Data@Entity@Table(name = "performance_case")@ToStringpublic class PerformanceCase extends BaseDomain { //主键 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; //用例名 private String caseName; //脚本名 private String scriptName; //脚本存储地址 private String scriptUrl; //脚本数据文件名称(csv文件) private String scriptDataName; //脚本数据文件存储地址(csv文件) private String scriptDataUrl; //项目名称 private String projectName; //模块名 private String moduleName; //操作人 private String operator;}


| pom.xml引入分页第三方依赖库


<!-- pagehelper -->    <dependency>      <groupId>com.github.pagehelper</groupId>      <artifactId>pagehelper-spring-boot-starter</artifactId>      <version>1.2.10</version>    </dependency>


| 编写性能测试用例管理页面的查询接口


1.在持久层接口PerformanceCaseDao增加查询方法


package com.caomingyu.cctestplatform.dao;
import com.caomingyu.cctestplatform.bean.PerformanceCase;import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapperpublic interface PerformanceCaseDao { List<PerformanceCase> queryAll(String query);}


2.在PerformanceCaseMapper.xml增加对应的查询sql


<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.caomingyu.cctestplatform.dao.PerformanceCaseDao">    <resultMap id="performanceCase" type="com.caomingyu.cctestplatform.bean.PerformanceCase">        <result column="ID" property="id"/>        <result column="CASE_NAME" property="caseName"/>        <result column="SCRIPT_NAME" property="scriptName"/>        <result column="SCRIPT_URL" property="scriptUrl"/>        <result column="SCRIPT_DATA_NAME" property="scriptDataName"/>        <result column="SCRIPT_DATA_URL" property="scriptDataUrl"/>        <result column="PROJECT_NAME" property="projectName"/>        <result column="MODULE_NAME" property="moduleName"/>        <result column="OPERATOR" property="operator"/>        <result column="CREATE_DATE" property="createDate"/>        <result column="LAST_UPDATE_DATE" property="lastUpdateDate"/>        <result column="IS_VALID" property="isValid"/>    </resultMap>
<select id="queryAll" resultMap="performanceCase"> select * from performance_case where IS_VALID = 1 <if test="query != null"> and CASE_NAME like concat('%', #{query}, '%') </if> order by ID desc </select></mapper>


3.编写PerformanceService,增加对应的查询方法


package com.caomingyu.cctestplatform.service;
import com.caomingyu.cctestplatform.bean.Result;
public interface PerformanceService { Result queryAll(Integer pageNum, Integer pageSize, String query);}


4.编写PerformanceServiceImpl,增加对应的查询方法


package com.caomingyu.cctestplatform.service.impl;
import com.caomingyu.cctestplatform.bean.Page;import com.caomingyu.cctestplatform.bean.PerformanceCase;import com.caomingyu.cctestplatform.bean.Result;import com.caomingyu.cctestplatform.common.ResultType;import com.caomingyu.cctestplatform.dao.PerformanceCaseDao;import com.caomingyu.cctestplatform.service.PerformanceService;import com.github.pagehelper.PageHelper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
import java.util.List;
@Servicepublic class PerformanceServiceImpl implements PerformanceService {
@Autowired private PerformanceCaseDao performanceCaseDao; @Autowired private Page pageCustomer;
@Override public Result queryAll(Integer pageNum, Integer pageSize, String query) { if (pageNum == null){ pageNum = 1; } if (pageSize == null){ pageSize = 10; } if ("".equals(query)){ query = null; } com.github.pagehelper.Page pageInfo = PageHelper.startPage(pageNum, pageSize); List<PerformanceCase> performanceCaseList = performanceCaseDao.queryAll(query); pageCustomer.setTotal(pageInfo.getTotal()); pageCustomer.setPageSize(pageInfo.getPageSize()); pageCustomer.setPageNum(pageInfo.getPageNum()); pageCustomer.setPages(pageInfo.getPages()); return Result.resultSuccess(pageCustomer, performanceCaseList, ResultType.GET_PERFORMANCE_TEST_CASE_SUCCESS); }}


5.编写PerformanceController,增加对应的查询接口


package com.caomingyu.cctestplatform.controller;
import com.caomingyu.cctestplatform.bean.Result;import com.caomingyu.cctestplatform.service.PerformanceService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/performance")public class PerformanceController {
@Autowired private PerformanceService performanceService;
//根据搜索字符串从数据库查询出对应的测试用例数据,如果为空则默认查全部 @GetMapping("/queryAll") public Result queryAll(@RequestParam(value="pageNum") Integer pageNum, @RequestParam (value="pageSize") Integer pageSize, @RequestParam (value="query") String query){ return performanceService.queryAll(pageNum, pageSize,query); }}


| 编写性能测试用例管理页面的添加/编辑 用例接口


1.增加jpa相关接口类PerformanceCaseRepository


package com.caomingyu.cctestplatform.repository;
import com.caomingyu.cctestplatform.bean.PerformanceCase;import org.springframework.data.jpa.repository.JpaRepository;
public interface PerformanceCaseRepository extends JpaRepository<PerformanceCase,Long> {}


2.由于添加测试用例有相关脚本文件上传,所以我们需要有一个保存base64成文件的方法


public class FileUtil {    //BASE64解码成File文件    public static void base64ToFile(String filePath,String base64) {        if (base64.contains(",")){            base64 = base64.split(",")[1];        }
File file = new File(filePath); if(!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } try (FileOutputStream fos = new java.io.FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos);) { byte[] bytes = Base64.getDecoder().decode(base64); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } }
}


3.在PerformanceServiceImpl增加addTestCase方法


@Override    public Result addTestCase(HttpServletRequest request) {        StandardMultipartHttpServletRequest httpServletRequest = (StandardMultipartHttpServletRequest) request;        String caseName = httpServletRequest.getParameter("caseName");        String moduleName = httpServletRequest.getParameter("moduleName");        String projectName = httpServletRequest.getParameter("projectName");        String operator = httpServletRequest.getParameter("operator");        String scriptName = httpServletRequest.getParameter("scriptName");        String scriptDataName = httpServletRequest.getParameter("scriptDataName");        String scriptFileArray = httpServletRequest.getParameter("scriptFileArray");        String scriptDataFileArray = httpServletRequest.getParameter("scriptDataFileArray");        if (StringUtil.isEmpty(caseName)){            return Result.resultError(ResultType.CASE_NAME_NULL, StatusCode.CASE_NAME_NULL);        }        if (StringUtil.isEmpty(moduleName)){            return Result.resultError(ResultType.MODULE_NAME_NULL, StatusCode.MODULE_NAME_NULL);        }        if (StringUtil.isEmpty(projectName)){            return Result.resultError(ResultType.PROJECT_NAME_NULL, StatusCode.PROJECT_NAME_NULL);        }        if (StringUtil.isEmpty(operator)){            return Result.resultError(ResultType.OPERATOR_NULL, StatusCode.OPERATOR_NULL);        }        if (StringUtil.isEmpty(scriptName)){            return Result.resultError(ResultType.SCRIPT_NAME_NULL, StatusCode.SCRIPT_NAME_NULL);        }        if (!scriptName.toLowerCase().endsWith(".jmx")){            return Result.resultError(ResultType.WRONG_FILE_FORMAT, StatusCode.WRONG_FILE_FORMAT);        }
if (StringUtil.isEmpty(scriptDataFileArray)){ return Result.resultError(ResultType.FILE_NULL, StatusCode.FILE_NULL); }
StringBuilder realPath = new StringBuilder(); realPath.append(scriptUploadBaseuri).append(DateUtils.getCurrentYear()).append(DateUtils.getCurrentMonth()).append(DateUtils.getCurrentDay()).append(File.separator).append(UUID.randomUUID().toString()); scriptUploadBaseuri = realPath.toString(); String scriptPath = scriptUploadBaseuri + scriptName; String scriptDataPath = scriptUploadBaseuri + scriptDataName; //保存文件 FileUtil.base64ToFile(scriptPath,scriptFileArray); //由于脚本数据文件非必传。所以不需要判空返回错误 if (!StringUtil.isEmpty(scriptDataFileArray)){ FileUtil.base64ToFile(scriptDataPath,scriptDataFileArray); } //保存测试用例数据 PerformanceCase performanceCase = savePerformanceCase(caseName,moduleName,projectName,operator,scriptName,scriptDataName,scriptPath,scriptDataPath); return Result.resultSuccess(null, performanceCase, ResultType.ADD_PERFORMANCE_TEST_CASE_SUCCESS); }


private PerformanceCase savePerformanceCase(String caseName, String moduleName, String projectName, String operator,String scriptName,String scriptDataName, String scriptPath,String scriptDataPath) {        PerformanceCase performanceCase = new PerformanceCase();        performanceCase.setCaseName(caseName);        performanceCase.setModuleName(moduleName);        performanceCase.setProjectName(projectName);        performanceCase.setOperator(operator);        performanceCase.setScriptName(scriptName);        performanceCase.setScriptDataName(scriptDataName);        performanceCase.setScriptUrl(scriptPath);        performanceCase.setScriptDataUrl(scriptDataPath);        performanceCase.setIsValid(1);        performanceCase = performanceCaseRepository.save(performanceCase);        return performanceCase;    }


4.在PerformanceService.java文件里增加addTestCase方法


Result addTestCase(HttpServletRequest request);


5.在PerformanceController增加addTestCase接口提供给前端


//添加测试用例    @PostMapping("addTestCase")    public Result addTestCase(HttpServletRequest request){        return  performanceService.addTestCase(request);    }


| 编写性能测试用例管理页面的编辑弹窗对应的回显数据接口


1.在PerformanceCaseDao.java文件里添加getPerformanceCaseById方法


PerformanceCase getPerformanceCaseById(Long id);


2.在PerformanceCaseMapper.xml文件里添加根据id查询用例的sql


<select id="getPerformanceCaseById" resultMap="performanceCase">        select * from performance_case        where ID=#{id}    </select>


3.在PerformanceServiceImpl.java和PerformanceService.java文件中增加getPerformanceCaseById方法


@Override    public Result getPerformanceCaseById(Long id) {        if (id == null || id.intValue() == 0){            return Result.resultError(ResultType.CASE_ID_NULL, StatusCode.CASE_ID_NULL);        }        PerformanceCase performanceCase = performanceCaseDao.getPerformanceCaseById(id);        return Result.resultSuccess(null, performanceCase, ResultType.GET_PERFORMANCE_TEST_CASE_SUCCESS);    }


Result getPerformanceCaseById(Long id);


4.在PerformanceController.java文件中增加getPerformanceCaseById接口


//根据id获取测试用例,用于编辑窗口回显数据    @GetMapping("getPerformanceCase/{id}")    public Result getPerformanceCaseById(@PathVariable Long id) {        return performanceService.getPerformanceCaseById(id);    }


| 编写性能测试用例管理页面的删除测试用例接口


1.在PerformanceCaseDao.java文件里添加deletePerformanceCaseById方法


void deletePerformanceCaseById(Long id);


2.在PerformanceCaseMapper.xml文件里添加根据id删除用例的sql(注:这里只是逻辑删除,把表的is_valid字段置为0,不是真的物理删除)


<update id="deletePerformanceCaseById">        update performance_case set IS_VALID = 0 where ID = #{id}    </update>


3.在PerformanceServiceImpl.java和PerformanceService.java文件中增加deletePerformanceCaseById方法


@Override    public Result deletePerformanceCaseById(Long id) {        if (id == null || id.intValue() == 0){            return Result.resultError(ResultType.CASE_ID_NULL, StatusCode.CASE_ID_NULL);        }        performanceCaseDao.deletePerformanceCaseById(id);        return Result.resultSuccess(null, null, ResultType.DELETE_PERFORMANCE_TEST_CASE_SUCCESS);    }


Result deletePerformanceCaseById(Long id);


4.在PerformanceController.java文件中增加deletePerformanceCase接口


@DeleteMapping("deletePerformanceCase/{id}")    public Result deletePerformanceCaseById(@PathVariable Long id) {        return performanceService.deletePerformanceCaseById(id);    }


至此,我们的性能测试用例管理相关的增删改查接口就已经完成了。


从0到1开发测试平台(十三)前后端接口token验证


从0到1开发测试平台(十二)首页面home的编写


从0到1开发测试平台(十一)前端登录页面的编写及与后端登录接口的交互


从0到1开发测试平台(十)后端增加登录token返回


从0到1开发测试平台(九)后端对接口response的封装


从0到1开发测试平台(八)后端服务添加lombok第三方类库


从0到1开发测试平台(七)后端服务添加swagger第三方类库


从0到1开发测试平台(六)增加登录接口


从0到1开发测试平台(五)RESTful API接口设计标准及规范


从0到1开发测试平台(四)Controller+Service +Dao三层的功能划分


从0到1开发测试平台(三)利用vue cli创建前端vue项目


从0到1开发测试平台(二)springboot搭建常见问题


带你用java从0到1开发测试平台

本文分享自微信公众号 - 软件测试架构师俱乐部(gh_03227f9a322f)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部