美文网首页
JMeter接口测试 增加校验

JMeter接口测试 增加校验

作者: Fitz_e74a | 来源:发表于2024-09-13 13:10 被阅读0次

    接口Common Header,注意不要再加双引号了,默认就是string


    image.png

    BeanShell 增加签名

    前提条件,需要增加对应的jar包到JMeter lib 目录, 并在对应位置增加相关引入


    image.png

    BeanShell 脚本程序如下

    import org.apache.jmeter.config.Arguments;
    import org.apache.jmeter.protocol.http.control.HeaderManager;
    import org.apache.jmeter.protocol.http.control.Header;
    import java.util.*;
    import com.google.gson.Gson;
    import GenerateSign;
    import org.apache.jmeter.protocol.http.util.HTTPArgument;
    import java.text.SimpleDateFormat;
    import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
    import org.bouncycastle.asn1.gm.GMNamedCurves;
    import org.bouncycastle.asn1.x9.X9ECParameters;
    import org.bouncycastle.crypto.digests.SM3Digest;
    import org.bouncycastle.crypto.engines.SM2Engine;
    import org.bouncycastle.crypto.macs.HMac;
    import org.bouncycastle.crypto.params.ECDomainParameters;
    import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    
    
     public static String getSM3hmac(String srcData) {
            String secret = "FJJKLIUYGHJ2456766GGR345GHHH456FJJKJ";
         byte[] key = secret.getBytes();
            byte[] src = srcData.getBytes();
            KeyParameter keyParameter = new KeyParameter(key);
            SM3Digest digest = new SM3Digest();
            HMac mac = new HMac(digest);
            mac.init(keyParameter);
            mac.update(src, 0, src.length);
            byte[] encode = new byte[mac.getMacSize()];
            mac.doFinal(encode, 0);
            String result = Hex.toHexString(encode);
            return result;
        }
    
    //获取当前日期
    log.info("获取日期。。。。。。");
    String timestamp= System.currentTimeMillis() + "";
    log.info("getCurrent:{}",timestamp);
    
    //开始处理
    log.info("接口调用前置处理器-签名/加密相关处理");
    Arguments args = sampler.getArguments(); 
    
    //获取请求参数
    String body = args.getArgument(0).getValue();
    log.info("业务参数:{}",body);
    
    //获取请求路径
    String path = sampler.getPath();
    log.info("获取请求路径:{}",path);
    
    String host = sampler.getDomain();
    log.info("获取host:{}",host);
    //获取协议
    String protocol = sampler.getProtocol();
    log.info("获取协议:{}",protocol);
    //拼接URL
    String requestUrl = protocol + "//" + host + path;
    log.info("拼接URL:{}",requestUrl);
    //获取请求方法返回值为大写GET
    String method = sampler.getMethod();
    log.info("获取请求方法返回值为大写GET:{}",method);
    
    HeaderManager headerManager = sampler.getHeaderManager();
    if(headerManager != null){
    for(int i=0;i<headerManager.size();i++){
         Header header = headerManager.get(i);
         log.info(header.getName()+" : "+header.getValue());
        }
    }
    
    
    String payload = body;
    String[] split = path.split("/");
    String urlSufix= split[split.length-1];
    log.info("Url 后缀:{}",urlSufix);
    String source = urlSufix + timestamp + "CARSERVICE" + payload;
    log.info("加密之前数据source:{}",source);
    
    String result = getSM3hmac(source);
    log.info("加密之后数据result:{}",result);
    // new一个Header对象
    Header myHeader = new Header("sign",result);
    // 添加Header到请求头管理器
    headerManager.add(myHeader);
    
    Header sourceHeader = new Header("signSource", source);
    // 添加Header到请求头管理器
    headerManager.add(sourceHeader);
    
    
    Header time = new Header("timeStamp", timestamp);
    // 添加Header到请求头管理器
    headerManager.add(time);
    

    BeanShell 后置脚本,前提条件需要将JMeter中
    jmeter.properties文件,添加如下设置:security.manager.enabled=false(之前排查了好久) ,不然无法调起cmd
    同时引入FastJson

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import com.alibaba.fastjson2.JSON;
    import com.alibaba.fastjson2.JSONObject;
    
    String statusCode = prev.getResponseCode(); //获取响应代码
    log.info("statusCode {}",statusCode);
    String response_headers = prev.getResponseHeaders();   //获取响应头
    log.info("response_headers {}",response_headers);
    String response_reason = prev.getResponseMessage();   //获取响应信息
    log.info("response_reason {}",response_reason);
    // 获取响应数据
    String responseData = prev.getResponseDataAsString();
    log.info("responseData {}",responseData);
    JSONObject data = JSON.parseObject(responseData);
    JSONObject data1 = (JSONObject) data.get("data");
    String qrCode = data1.getString("qrCode");
    log.info("qrCode {}",qrCode);
    String command = "cmd /c python D:\\APP\\apache-jmeter-5.6.3\\case\\python\\showQrcode.py -t "+qrCode;
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(command);
    
    pr.waitFor();
     
    BufferedReader b = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line = "";
    StringBuilder response = new StringBuilder();
    while ((line = b.readLine()) != null) {
        response.append(line);
     
    }
     
    String response_data = response.toString();
     
    System.out.println("二维码结果:"+response_data);
    b.close();
    

    对应的Python3脚本文件

    import argparse
    import qrcode as qrcode
    import matplotlib.pyplot as plt
    
    filename = '二维码.png'
    # 获取二维码
    def make_qr_code():
         # 接收cmd命令里面的参数
        parse = argparse.ArgumentParser()
        parse.add_argument("-t", "--ticket")
        args = parse.parse_args()
        content = args.ticket
        q = qrcode.QRCode()
        q.add_data(content)
        q.make()
        img = q.make_image()
        img.save(filename)
        plt.title = '登录二维码'
        plt.imshow(img)
        plt.show()
        print("generate success")
    
    if __name__ == '__main__':
        make_qr_code()
    

    相关文章

      网友评论

          本文标题:JMeter接口测试 增加校验

          本文链接:https://www.haomeiwen.com/subject/qsevljtx.html