package cn.unitid.matrix.pkiservice.test.svs.jmetertest;

import cn.unitid.matrix.pkiservice.sdk.DefaultPkiClient;
import cn.unitid.matrix.pkiservice.sdk.PkiClient;
import cn.unitid.matrix.pkiservice.sdk.ces.request.P1SignRequest;
import cn.unitid.matrix.pkiservice.sdk.ces.response.P1SignResponse;
import cn.unitid.matrix.pkiservice.sdk.consts.CertSearchEnum;
import cn.unitid.matrix.pkiservice.sdk.consts.DataType;
import cn.unitid.matrix.pkiservice.sdk.consts.SignatureAlgorithm;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

/**
 * 作者： 徐霁
 * <p>
 * 时间： 2021/5/21 14:47
 * <p>
 * 描述信息： P1签名测试
 */
public class P1SignTest extends AbstractJavaSamplerClient {

    @Override
    public Arguments getDefaultParameters() {
        Arguments argumets = new Arguments();
        argumets.addArgument("certId", "");
        argumets.addArgument("original", "");
        return argumets;
    }

    /**
     * 测试执行的循环体，根据线程数和循环次数的不同可执行多次
     * @param javaSamplerContext
     * @return
     */
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult sampleResult = new SampleResult();
        sampleResult.setSampleLabel("p1-sign-test");
        String certId = javaSamplerContext.getParameter("certId");
        String data = javaSamplerContext.getParameter("original");


        String url = "http://127.0.0.1:20402/openapi/svs/v1";
        String appKey = "62342167e5b4803034c6993e";
        String appSecret = "qR5Hpz5e8cReXvMjxw0sdD5h8AWMio5J";

        // 1.原客户端
        PkiClient pkiClient = new DefaultPkiClient(url, appKey, appSecret);

        //测试方法
        try {
            sampleResult.sampleStart();
            P1SignRequest request = new P1SignRequest();
            request.setSignType(CertSearchEnum.CERT_ID);
            request.setSignItemValue(certId);
            request.setData(data);
            request.setDataType(DataType.ORIGINAL);
            request.setSignatureAlgorithm(SignatureAlgorithm.SHA1withRSA);
            P1SignResponse response = pkiClient.execute(request);

            //将结果写入结果树：在jmeter的监听器-查看结果树时即可查看返回结果
            sampleResult.setRequestHeaders("url:" + url);
            sampleResult.setResponseData("result:" + response.getBody(), null);
            sampleResult.setSuccessful(response.isSuccess() && response.getResult() != null);
        } catch (Exception e) {
            sampleResult.setSuccessful(false);
            e.printStackTrace();
        } finally {
            sampleResult.sampleEnd();
        }
        return sampleResult;
    }

}
