专栏首页FunTester我的开发日记(五)

我的开发日记(五)

今天主要处理测试用例属性的相关功能以及抄了一份在过滤器中打印请求参数和响应结果的方法。

mybatis

今天主要学习使用了比较常用的功能:1:更新数据时从其他表读取数据(这里有个问题,有个更好的办法是inner join,但是我这个更新涉及到了修改关联项apiId,不能使用这个方法)2:处理list属性批量插入

插入数据时读取

下面是一个更新用例的SQL配置:

    <update id="updateCase" parameterType="com.okay.family.common.bean.testcase.request.CaseAttributeBean">
        UPDATE
        <include refid="table"/>
        c
        SET
        editor=#{uid},name=#{name},envId=#{envId},serviceId=#{serviceId},moduleId=#{moduleId},projectList=#{projectList,jdbcType=OTHER,typeHandler=com.okay.family.common.typehandler.ListIntegerHandler},apiId=#{apiId},headermoco=(SELECT
        header_para FROM family_server_api_info WHERE id = #{apiId}),paramsmoco=(SELECT request_par FROM
        family_server_api_info WHERE id = #{apiId})
        WHERE
        id = #{id}
    </update>

处理list属性

批量插入的SQL配置:

    <insert id="addCaseProjectRelation" parameterType="com.okay.family.common.bean.testcase.request.CaseAttributeBean">
        insert into
        <include refid="case_project_relation"/>
        (caseId,projectId)
        values
        <foreach collection="projectList" item="projectId" index="index" separator=",">
            (
            #{id}, #{projectId}
            )
        </foreach>
    </insert>

CaseAttributeBean代码:

class CaseAttributeBean extends AbstractBean {

    private static final long serialVersionUID = -629232822729332L;

    int id

    int uid

    int envId

    /**
     * 关联服务id
     */
    int serviceId

    /**
     * 关联服务模块id
     */
    int moduleId

    @NotNull
    String name

    List<Integer> projectList

    int apiId

    @NotNull
    @Pattern(regexp = "add|update|copy",message = "类型错误,应该传:add|update|copy")
    String type

}

过滤器打印请求参数和响应结果

过滤器代码

package com.okay.family.common.wapper;


import com.okay.family.fun.utils.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.invoke.MethodHandles;


@Component
@WebFilter(urlPatterns = "/*", filterName = "wrappingFilter")
public class WrappingFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        ResponseWrapper responseWrapper = new ResponseWrapper(resp);
        RequestWrapper requestWrapper = new RequestWrapper(req);
        String url = requestWrapper.getRequestURL().toString();
        String queryArgs = requestWrapper.getQueryString();
        queryArgs = queryArgs == null ? requestWrapper.getBody() : queryArgs;
        long start = Time.getTimeStamp();
        chain.doFilter(requestWrapper == null ? request : requestWrapper, responseWrapper);
        long end = Time.getTimeStamp();
        byte[] bytes = responseWrapper.getContent();
        String respContent = new String(bytes);
        logger.info("请求:{},耗时:{}ms,参数:{},响应:{}", url, end - start,queryArgs,respContent);
        response.getOutputStream().write(respContent.getBytes());
    }


}

  • 这里有一个知识点:无论是请求对象还是响应对象,里面的数据只能读一次,读完还得写回去,这样才能保证程序正常处理。

RequestWrapper代码

package com.okay.family.common.wapper;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class RequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }
}

RequestWrapper代码

这个跟上面很相似

package com.okay.family.common.wapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    private PrintWriter printWriter = new PrintWriter(outputStream);

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {

            }

            @Override
            public void write(int b) throws IOException {
                outputStream.write(b);
            }

            @Override
            public void write(byte[] b) throws IOException {
                outputStream.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                outputStream.write(b, off, len);
            }

            @Override
            public void flush() throws IOException {
                outputStream.flush();
            }
        };
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return printWriter;
    }

    public void flush(){
        try {
            printWriter.flush();
            printWriter.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public byte[] getContent() {
        flush();
        return outputStream.toByteArray();
    }
}


  • 郑重声明:公众号“FunTester”首发,欢迎关注,禁止第三方转载。更多原创文章:FunTester十八张原创专辑,合作请联系Fhaohaizi@163.com

本文分享自微信公众号 - FunTester(NuclearTester),作者:八音弦

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2020-06-19

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 性能测试框架

    之前写过一个性能测试框架,只是针对单一的HTTP接口的测试,对于业务接口和非HTTP接口还无非适配,刚好前段时间工作中用到了,就更新了自己的测试框架,这次不再以...

    FunTester
  • 基于HTTP请求的多线程实现类--视频讲解

    上期将了定时和定量两种压测模式的虚拟类,本期分享一下基于单个HTTP请求对象HTTPrequestbase的两个压测模式的具体实现类。比较关键的就是GCThre...

    FunTester
  • 性能框架多线程基类和执行类--视频讲解

    讲完了自动化测试的相关内容,接下来开喷性能测试了。首先分享了我的思路:通过一个继承Thread的基类(虚拟类)来规范一些通用的行为和功能,这一部分比较浅,然后通...

    FunTester
  • SpringBoot 整合 elasticsearch 实例

    下载地址:https://www.elastic.co/downloads/past-releases

    ZhangXianSheng
  • Spring Boot:整合Shiro权限框架

    Shiro是Apache旗下的一个开源项目,它是一个非常易用的安全框架,提供了包括认证、授权、加密、会话管理等功能,与Spring Security一样属基于权...

    朝雨忆轻尘
  • AOP编程简介及其在Spring框架中的使用

    AOP与OOP互为补充,面向对象编程(OOP)将程序分解成各个层次的对象;面向切面编程(AOP)则是将程序运行过程中分解成各个切面。可以说OOP是从静态角度考虑...

    东溪陈姓少年
  • 使用shiro安全管理

    dalaoyang
  • MyBatis注解开发

    指的是MyBatis中SqlSession对象的缓存,当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。

    用户3112896
  • Mybatis利用拦截器做统一分页

    查询传递Page参数,或者传递继承Page的对象参数。拦截器查询记录之后,通过改造查询sql获取总记录数。赋值Page对象,返回。

    WindWant
  • springboot之单元测试

    https://wap.ztestin.com/site/register?usercode=FAAAQwMQGAAXAwQBA3QhExcDHAQDPjVaA...

    小老鼠

扫码关注云+社区

领取腾讯云代金券