当前位置:网站首页>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

Two , Choose the latest version of

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

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 
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"
边栏推荐
- Galaxy Kirin desktop operating system installation postgresql13 (source code installation)
- Add a self incrementing sequence number to the antd table component
- 关于在云服务器上(这里用腾讯云)安装mysql8.0并使本地可以远程连接的方法
- The opacity value becomes 1%
- [untitled]
- The fifth training assignment
- How to play video on unityui
- 网络协议 概念
- Bookmarking - common website navigation for programmers
- “梦想杯”2017 年江苏省信息与未来小学生夏令营 IT 小能手 PK 之程序设计试题
猜你喜欢

IDEA快捷键大全

2021 summary and 2022 outlook

Socket socket programming

Seata 1.3.0 four modes to solve distributed transactions (at, TCC, Saga, XA)

Avoid mutating a prop directly since the value will be overwritten whenever the parent component

"Dream Cup" 2017 Jiangsu information and future primary school summer camp it expert PK program design questions

July 10, 2022 "five heart public welfare" activity notice + registration entry (two-dimensional code)

自动化测试框架

What if copying is prohibited?

Opencv installation and environment configuration - vs2017
随机推荐
Long list performance optimization scheme memo
Go slice comparison
Unity websocket server
Shardingsphere sub database and table examples (logical table, real table, binding table, broadcast table, single table)
Mpx 插件
Transaction rolled back because it has been marked as rollback only
The sixth training assignment
[pytorch 07] hands on deep learning chapter_ Preliminaries/ndarray exercises hands-on version
uniapp 在onLaunch中跳转页面后,点击事件失效解决方法
【STM32】实战3.1—用STM32与TB6600驱动器驱动42步进电机(一)
[pyqt] the cellwidget in tablewidget uses signal and slot mechanism
常用sql语句整理:mysql
Bookmarking - common website navigation for programmers
Socket socket programming
Ping tool ICMP message learning
A case of compiling QT file qmake compiling script
MPX plug-in
從色情直播到直播電商
Kitex retry mechanism
seata 1.3.0 四种模式解决分布式事务(AT、TCC、SAGA、XA)