当前位置:网站首页>About the application of writing shell script JSON in JMeter

About the application of writing shell script JSON in JMeter

2022-07-07 11:14:00 Koki can test a rookie

One 、 Application parameters

stay BeanShell Script , Post this code , Will output one test1 by json Formatted string .


import org.json.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
JSONObject request_data = new JSONObject();
request_data.put("merCode", "${mercode}");
request_data.put("batchNo", "${a}${b}");
request_data.put("insCode","${mercode}");
request_data.put("insName","${insName}");
request_data.put("orderId","${a}${b}");
request_data.put("idCard","${idCard}");
request_data.put("settAmt","${settAmt}");
request_data.put("userName","${userName}");
request_data.put("settAcctName","${settAcctName}");
request_data.put("tranType","${tranType}");
request_data.put("settAcct","${settAcct}");
request_data.put("acctType","${acctType}");
request_data.put("merCbName","${merCbName}");
request_data.put("merCbCode","${merCbCode}");
JSONArray jsonArray = JSONArray.fromObject(request_data);
log.info("request_data:"+jsonArray.toString());
vars.put("test1",(String)jsonArray.toString());
log.info(" Final request parameters :"+test1);

If there is a problem in operation :

java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException

Explain that there is no corresponding jay package :
commons-beanutils-1.8.3.jar
commons-lang-2.5.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar

These packages should be downloaded by the domestic authorities : Poke it here
Search the input box below for what you want jar package , Then go in , Click on , download , Look at the picture !

One , Select first :commons-beanutils

 Insert picture description here

Two , Choose the latest version of

 commonly

3、 ... and , download jar package

After that, go to the local , Then put the corresponding code into jemter Install under directory lib/ext Under the table of contents

 Insert picture description here

When it's done , The log will show such a string : It can be used in combination with practice

INFO o.a.j.u.BeanShellTestElement: request_data:[{
    "merCode":"${mercode}","batchNo":"${a}${b}","insCode":"${mercode}","insName":"${insName}","orderId":"${a}${b}","idCard":"${idCard}","settAmt":"${settAmt}","userName":"${userName}","settAcctName":"${settAcctName}","tranType":"${tranType}","settAcct":"${settAcct}","acctType":"${acctType}","merCbName":"${merCbName}","merCbCode":"${merCbCode}"}]

Two 、 Combining with the code

for instance : stay BeanShell Write content to the file . Reference to the original Poke it here
The content of the request is like this :{“data”: “[id1, id2, id3…]”}

Use BeanShell Realize the operation of writing files , Think about it 3 spot :
① The format written into the file should be parameterized for the business to be tested
② id Non reusable , It requires that the contents in the document be new every time id, That is, the old file should be deleted
③ Although the front-end business returns JSON, But considering that Java Handle JSON Rely on the 3 Fang jar package , Script migration is inconvenient , Just manipulate the string directly

shell The code is :

import java.io.*;

var idFile = "data/id.csv";  //  Define storage id File path 

try{
    
    File f = new File(idFile);
    f.delete();     //  Delete the old idFile file 
}catch(Exception e){
    
    e.printStackTrace();
}

var idStr = vars.get("data");    //  obtain JSON Extractor Extracted from data
idStr = idStr.replace("[","");     //  Get rid of  "[id1, id2, id3...]"  Brackets at the beginning and end 
idStr = idStr.replace("]","");
String[] temp = idStr.split(",");   //  With ","  Split string  "id1, id2, id3...", Save as String An array of types 

FileWriter fstream = new FileWriter(idFile);   //FileWriter("file01.txt",true)  Append mode 
BufferedWriter out = new BufferedWriter(fstream);

for (int i = 0; i < temp.length; i++){
    
    out.write(temp[i]);
    out.write(System.getProperty("line.separator"));  //  Line break 
}

out.close();
fstream.close();

Notice that there's a hole , Namely JMeter When the script executes , Will check csv Does the file exist , There is no error reporting , So you need to manually create a “id.csv” stay data Under the table of contents , It doesn't matter whether there is content , Mainly to pass the inspection

3、 ... and 、 The actual use

I need to write a data format like this :{"A":"LOCAL","B":"Local","C":[58,76,62,78,71,61,56,70,80,74,67,60,69,55,64,72,63,59,57,73,164,163,162,68,77,75],"endDateTime":"2022-06-02 12:29:04"} Into the file , It turns out that csv Writing cannot , Finally written in txt Inside .

The code is as follows :

import org.json.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
JSONObject data = new JSONObject();
data.put("A","LOCAL");
data.put("B","Local");
data.put("C","[58,76,62,78,71,61,56,70,80,74,67,60,69,55,64,72,63,59,57,73,164,163,162,68,77,75]");
data.put("endDateTime",vars.get("date")); //vars.get("date") date = ${__timeShift(YYYY-MM-dd HH:mm:ss,,,,)}  Take the current time 
JSONArray jsonArray = JSONArray.fromObject(data);
log.info("data:"+jsonArray.toString());
var idStr = (String)jsonArray.toString();
idStr = idStr.replace("[{","{");     //  Get rid of  "[{、}]"  Brackets at the beginning and end 
idStr = idStr.replace("}]","}");
log.info(" Final requested parameters :"+idStr);  // Log print current parameters 

import java.io.*;
var idFile = vars.get("blob");  //  Define storage blob File path  C:\\xx\\xx\\xx.txt
try{
    
    File f = new File(idFile);
    f.delete();     //  Delete the old idFile file 
}catch(Exception e){
    
    e.printStackTrace();
}

FileWriter fstream = new FileWriter(idFile);   //FileWriter("file01.txt",true)  Append mode 
BufferedWriter out = new BufferedWriter(fstream);

out.write(idStr);// Write the contents of the file 
out.close();// Exit file writing 
fstream.close();// Exit append 


Data is used here : About https File upload related pits can Poke it here see
 Insert picture description here

Four 、BeanShell Assertion

One 、

if("${returnStatus}"=="00"){
    
	Failure=false;
	FailureMessage=" Successful trade ";
	log.info(" Successful trade ");
	}
if("${returnStatus}"=="01"){
    
	Failure=true;
	FailureMessage="md5 error ";
	log.info("md5 error ");
	}

Two 、

 For query interface 

import org.apache.log4j.Logger;

String response_data = prev.getResponseDataAsString();// Get the... Returned by the interface response data 
log.info("## response_data="+response_data+" ##");
   if(response_data.contains(""total":"+${count})||response_data.contains(""total":null")){
    
    Failure=false; // Set to false  Indicates that the interface runs successfully , In the fruit tree sample It's green 
    }else{
    
        Failure=true; // Direct judgment fails   Indicates that the interface failed to run , In the fruit tree sample It's red 
        FailureMessage=" error message ";
        prev.setStopThread(true);// If the assertion fails , The back interface doesn't need to run anymore , Direct pause 
}

5、 ... and 、BeanShell Sampler :MD5 encryption

import org.apache.commons.codec.digest.DigestUtils;
//String md5str847="${merCode}${tranAmt}${key01}";
String md5Str = DigestUtils.md5Hex("${merCode}${tranAmt}${key01}");
vars.put("md5Str",md5Str.toUpperCase());
System.out.println(md5Str);
log.info(" After encryption :"+md5Str);

6、 ... and 、 obtain CSV Number of parameter file lines

One 、 Add user-defined variables :

path01 E:\ New folder \jmeter To build the data \ Delete the historical withdrawal data of the current day .csv
path02 E:\ New folder \jmeter To build the data \ Withdraw cash by swiping card .csv
path02 E:\ New folder \jmeter To build the data \ Withdraw cash by swiping card 1.csv

Two 、BeanShell Sampler : Get the number of lines in the parameter file

import java.io.BufferedReader;
import java.io.FileReader;
BufferedReader br =new BufferedReader(new FileReader("${path01}"));
String tmpStr=null;
Integer rowCount=0;
while((tmpStr=br.readLine())!=null){
    
	rowCount++;
}
rowCount=rowCount-1;
vars.putObject("rowCount",String.valueOf(rowCount));
log.info(" The first parameter file line number :"+String.valueOf(rowCount));


BufferedReader br1 =new BufferedReader(new FileReader("${path02}"));
String tmpStr=null;
Integer rowCount1=0;
while((tmpStr=br1.readLine())!=null){
    
	rowCount1++;
}
rowCount1=rowCount1-1;
vars.putObject("rowCount1",String.valueOf(rowCount1));
log.info(" The second parameter is the number of lines in the file :"+String.valueOf(rowCount1));


BufferedReader br2 =new BufferedReader(new FileReader("${path03}"));
String tmpStr=null;
Integer rowCount2=0;
while((tmpStr=br2.readLine())!=null){
    
	rowCount2++;
}
rowCount2=rowCount2-1;
vars.putObject("rowCount2",String.valueOf(rowCount2));
log.info(" The third parameter is the number of lines in the file :"+String.valueOf(rowCount2));

3、 ... and 、BeanShell Sampler : Set the number of rows as a global variable

${__setProperty(rowCount01,${rowCount})};
${__setProperty(rowCount02,${rowCount1})};
${__setProperty(rowCount03,${rowCount2})};

6、 ... and 、 If (lf) controller

give an example :${threadID}=="1"&&${returnStatus_1_g0}=="00"

原网站

版权声明
本文为[Koki can test a rookie]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070903019244.html