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.P7SignRequest;
import cn.unitid.matrix.pkiservice.sdk.ces.response.P7SignResponse;
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 P7SignTest extends AbstractJavaSamplerClient {

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

    /**
     * 测试执行的循环体，根据线程数和循环次数的不同可执行多次
     * @param context
     * @return
     */
    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult sampleResult = new SampleResult();

        // 计时开始
        sampleResult.sampleStart();

        //测试方法
        try {
            String url = "http://127.0.0.1:20402/openapi/svs/v1";
            String appKey = "60a1d401bb8c707040029624";
            String appSecret = "w4ouV1Vw24HMpDJyCWs40qMPaNS7WL4V";

            PkiClient pkiClient = new DefaultPkiClient(url, appKey, appSecret);

            String certId = context.getParameter("certId");
            String original = context.getParameter("original");

            P7SignRequest request = new P7SignRequest();
            request.setSignType(CertSearchEnum.CERT_ID);
            request.setSignItemValue(certId);
            request.setData(original);
            request.setDataType(DataType.ORIGINAL);
            request.setSignatureAlgorithm(SignatureAlgorithm.SHA1withRSA);
            request.setAttach(false);

            P7SignResponse 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;
    }

}
