当前位置:网站首页>Variable usage method of BeanShell of JMeter
Variable usage method of BeanShell of JMeter
2022-07-21 23:44:00 【The test is super standard】
BeanShell Variables supported by components 、 Method
Failure/FailureMessage/ Set response assertion
Preface
This article is to sort out the knowledge of predecessors in the process of daily use , And the results of daily use and output , Due to the collection of too many articles 、 Time is too long , It's impossible to list which predecessors have been cited , I'm sorry . Also limited to personal level , If there is anything wrong, you are also welcome to correct .
This paper mainly introduces beanshell Common method classes and use cases in .
Friendship tips : For starters , It is suggested to clarify the execution sequence and scope of each original .
BeanShell brief introduction
- What is? BeanShell Official website / Official documents
BeanShell By java Compiling , Is a lightweight scripting language , It is also equivalent to a small free JAVA Source interpreter , Support for object-oriented scripting language features , It can also be embedded in JAVA In the source code , Can dynamically execute JAVA Source code and extends some features of scripting language .
Simple understanding :beanshell Is a person who can write java Code - JMeter China and BeanShell The relationship between
First ,JMeter Also by java Compiling , and java The runtime needs to compile , Then you can run ; and BeanShell It is an interpreter , It is possible to run the source code directly ;
therefore , There is no necessary connection between the two , It's just a beanshell Embedded in jmeter Inside this tool , And then through jmeter The method of definition and beanshell Interact ; - We can go through BeanShell What do you do ?
- Read write request 、 Respond to relevant information ( Include request headers 、 Request information 、 Response head 、 Response code 、 Responder, etc )
- perform Java The code realizes certain logical calculation ( Request encryption 、 Complex assertions )
BeanShell Variables supported by components 、 Method
Why say this ? Because it's different Beanshell The supported variables are different , Direct use will report an error . Here's the picture , You can know what variables are supported through components .
- BeanShell Sampler
SampleResult、ResponseCode、ResponseMessage、IsSuccess、Label、FileName、ctx、vars、props、log - BeanShell Preprocessor
ctx、vars、props、prev、sampler、log - Post Processors :BeanShell PostProcessor
ctx、vars、props,prev、log - BeanShell Assertion
Read/Write: Failure、FailureMessage、SampleResult、vars、props、log
ReadOnly: ResponseData、ResponseCode、ResponseMessage、ResponseHeaders、RequestHeaders、SampleLabel、SamplerData、ctx - BeanShell Timer
ctx、vars、props、log、prev - BeanShell Monitor
ctx、vars、props
The component to which the method class applies :
Method name | Applicable components | explain |
SampleResult | BeanShell Sampler 、BeanShell Assertion | need import object |
ResponseCode | BeanShell Sampler 、BeanShell Assertion | |
ResponseMessage | BeanShell Sampler 、BeanShell Assertion | |
IsSuccess | BeanShell Sampler | |
Label | BeanShell Sampler | |
FileName | BeanShell Sampler | |
ctx | All components | |
vars | All components | |
props | All components | |
log | Except for the monitor | |
prev | BeanShell Preprocessor 、 Post Processors 、 Timer | |
sampler | BeanShell Preprocessor | |
Failure | BeanShell Assertion | |
FailureMessage | BeanShell Assertion | |
ResponseData | BeanShell Assertion | |
ResponseHeaders | BeanShell Assertion | |
RequestHeaders | BeanShell Assertion | |
SampleLabel | BeanShell Assertion | |
SamplerData | BeanShell Assertion |
Beanshell Method
beanshell Commonly used API - link
Each method has its corresponding API, Applicable components 、 Applicable examples , The applicable examples are all self debugged , You can directly copy and paste .
log
JavaDoc
Applicable components : Except for the monitor , Other components can be used .
log Express org.apache.log.Logger class , Log information is written to jmeter.log file .
- log.info(" Response status code " + ResponseCode);
- log.debu(" Debugging information ");
- log.warn(" Warning message ");
- log.error(" Error message ");
log.info(" The information here will be saved in jmeter.log In file , And print and display on jmeter Real time running log ");
System.out.println(" The information here will be output to jmeter In the console ( In the black box )");
Log display location :
vars
JavaDoc
Applicable components : All components
vars It is for operation Jmeter Variable , It is org.apache.jmeter.threads.JMeterVariables Class , Provide reading and writing of current variables .
be-all JMeter The variables are java character string , If you need to store some variables in a JMeter variable , You need to convert it into a string first .
Common methods :
- vars.get(String key); from jmeter Get the value of the variable , Such as :vars.get("key"); Be careful , Need double quotes , You can't do that vars.get("${key}");
- vars.put(String key,String value); Data stored in jmeter variable , Such as vars.put("key","123456"); // Variable names need double quotation marks
vars.putObject("SAVED_ARRAY",[]); Assign an object
- vars.getObject(String key); Read object,
- Use scenarios : Read JDBC request Inside result variable names
- Such as :vars.getObject("sql_order_ids").get(2).get("id"));
Be careful :vars The received value must be of string type , If you pass other types , Include null, All will report wrong. ; If you want to use numbers , Number and so on , The method is to do type conversion ; for example :
vars.put("key1", "" + 1);
vars.put("key2", (String)1);
vars.put("key3", [2, 3, 4].toString());
vars.put("key4", (String)[1,2]);
vars.put("key4", "" + [2, 3, 4]);
vars.put("key5", "" + true);
vars.put("key6", true.toString());
props
JavaDoc
Applicable components : All components
1、props yes java.util.Properties Example , And vars The effect is roughly the same , The difference is vars Is to read and write variables , and props It is mainly used to read and write attributes .ps: The attribute of chivalry refers to jmeter.properties、user.properties、jmeter.properties Variables in the file .
2、vars Can only be used within the current thread group ,props Can be used across thread groups , Because attributes can cross thread groups, but variables don't ;
3、vars Save only String perhaps Object,props Inherited Hashtable Class , So have and vars Allied get and put Method , Also inherited Hashtable Other methods ;
// Determine whether an attribute exists , Returns a Boolean value
props.containsKey("PROPERTY_NAME")
// Determine whether a certain value exists , Returns a Boolean value
props.contains("PROPERTY_VALUE")
// Delete a value
props.remove("PROPERTY_NAME")
// All attributes are represented as strings
props.toString()
Common methods :
- props.get(String) Can get Jmeter Properties that have been generated in ( Static variables );
- Such as :props.get("START.HMS"); notes :START.HMS For the property name , In the file jmeter.properties In the definition of ;
- combination : test plan > Non test originals > Property display , View the current jmeter Attribute variables existing in the environment ;
- props.put(String,String) You can create and update JMeter attribute
- Such as :props.put("PROP1","1234");
- Use __P() Call attribute value , Such as :
${__P(PROP1,)}
Get the value of the global attribute .
ctx
JavaDoc
Applicable components : All components
ctx yes JMeter The most powerful of the built-in variables . It represents org.apache.jmeter.threads.JMeterContext class , The actual is JMeter In itself , It provides a pair of samplers 、 Execution results 、 Variable / Read and write properties .
- ctx A variable is JMeter JSR223 One of the most powerful built-in variables , It can easily access the context of the current thread ;
- stay JMeter Inside ,ctx It maps to org.apache.jmeter.threads Of JMeterContext class ;
- because JMeterContext No thread safety , Therefore, it is only applicable to use in single thread ;
Common methods :
- ctx.getVariables(" Variable name "): Get the value of the variable ( Same as vars.get()), Space time , Get all variables of the current thread ??
- ctx.setVariables(" Variable name ", " A variable's value "): Set a variable ( Same as vars.put())
- ctx.getProperties(" Property name "): Get attribute value ( Same as props.get())
- ctx.setProperties(" Property name "," Property value "): Set properties ( Same as props.put())
- ctx.getPreviousResult(): Get the request result of the current request ( Same as prev) The return is SampleResult type
- ctx.getCurrentSampler(): Get the request information of the current sampler , The return is Sampler type
- ctx.getPreviousSampler(): Get the previous sampler request information , The return is Sampler type
- ctx.getThreadNum(): Gets the current number of threads , from 0 Start
- ctx.getThreadGroup(): Get the current thread group
- ctx. getThread(): Get the current thread
- ctx.getEngine(): Get engine
- ctx.isSamplingStarted(): Judge whether the sampler is started
- ctx.isRecording(): Determine whether recording is on
- ctx.getSamplerContext(): Get sampler context data
Examples of use 1:
import org.apache.jmeter.samplers.SampleResult;
// You can see JavaDoc,ctx.getPreviousResult() The return value is SampleResult type ;
SampleResult result = ctx.getPreviousResult();// Get sampler results
String responseString = result.getResponseDataAsString();// Get response data
String responseCode = result.getResponseCode();// Get response code
String RequestHeaders = result.getRequestHeaders();// Get request header
String ResponseHeaders = result.getResponseHeaders();// Get response header
String request = ctx.getCurrentSampler().getPath(); // Request path
String request = ctx.getCurrentSampler().getArguments().getArgument(0).getValue(); // obtain json Format request parameters
log.info(" Get sampler results :"+responseString);
log.info(" Get response data :"+responseCode);
log.info(" Get response code :"+RequestHeaders);
log.info(" Get request header :"+RequestHeaders);
log.info(" Get response header :"+ResponseHeaders);
Examples of use 2:
import org.json.*;
import org.json.JSONArray; // Needed Json jar The net disk wrapped at the end of the text
import org.json.JSONObject;
import java.util.*;
import org.apache.jmeter.samplers.SampleResult;
SampleResult resultSampleResult = ctx.getPreviousResult();// Get sampler results
String responseString = resultSampleResult.getResponseDataAsString();// Get response data
JSONObject responseJson = new JSONObject(responseString); // take String Of response To JSON object
String now_follow_by = responseJson.getJSONArray("data").getJSONObject(0).getString("follow_by"); // Get current follow-up planners
SamplerData
Applicable components :BeanShell Assertion
data and SamplerData Namely sampler data( Request data ), The type of byte[ ]
// byte And String Type conversion String s = new String(bytes);
String samplerData = new String(data);
//String samplerData = new String(data,"UTF-8"); // There is Chinese garbled code processing
Label / SampleLabel
Label Applicable components :BeanShell Sampler
SampleLabel Applicable components :BeanShell Assertion
Label and SampleLabel yes sampler The title of the , The type is String.
//Label
String Label_title=Label;
log.info(""+Label_title);
//SampleLabel
String sampleLabel_title=SampleLabel;
log.info("Label_title:"+sampleLabel_title);
IsSuccess
Applicable components :BeanShell Sampler
IsSuccess It is a reflection of whether the sampler is successful java.lang.Boolean. If set to true,, otherwise , Then for " Failure ".
IsSuccess Express sampler Success or failure of , The type of boolean.
IsSuccess=true; // Make sampler " adopt "
IsSuccess=false;// Make sampler " Failure "
prev / SampleResult
JavaDoc
prev Applicable components :BeanShell Preprocessor 、 Post Processors 、 Timer
SampleResult Applicable components :BeanShell Sampler 、BeanShell Assertion
prev and SampleResult It is the present. sampler Result , The type of SampleResult, It can read and write sampler Information and control sampler act .
prev Common methods
String RequestHeaders = prev.getRequestHeaders(); // Get request header
String ResponseHeaders = prev.getResponseHeaders(); // Get response header
String responseCode = prev.getResponseCode(); // Get response code
String responseData = prev.getResponseDataAsString(); // Get response data
String ContentType = prev.getContentType() // Get the sampler response Content-Type The value field of the first field ( Include parameters )
log.info(RequestHeaders);
log.info(ResponseHeaders);
log.info(responseData);
import org.apache.jmeter.samplers.SampleResult;
String samplerData= prev.getSamplerData(); // Get request content
log.info("getSamplerData=======:"+samplerData);
// Stop thread
prev.setStopThread(true);// Use scenarios : If the assertion fails , The back interface doesn't need to run anymore , The script stops directly
SampleResult Common methods
import org.apache.jmeter.samplers.SampleResult;
SampleResult resultSampleResult = ctx.getPreviousResult();// Get sampler results
String responseData = SampleResult.getResponseDataAsString(); // Get response data
String responseCode = SampleResult.getResponseCode(); // Get response code HTTP: 200 、502、404 etc.
String sampleLabel = SampleResult.getSampleLabel(); // The name of the interface
String url = SampleResult.getUrlAsString() ; // request url
String samplerData = SampleResult.getSamplerData() ; // Request data ; request url、 request body
String requestHeaders= SampleResult.getRequestHeaders() ; // request header
boolean status = SampleResult.isResponseCodeOK(); // HTTP return 200 When is true
SampleResult.setSuccessful(false); // Fail the request
ResponseData
Applicable components :BeanShell Assertion
ResponseData Namely sampler response data( The response data ), The type of byte []:
// String samplerData = new String(ResponseData); //byte And String Type conversion String s = new String(bytes);
String samplerData = new String(ResponseData,"UTF-8");// Chinese scrambling
log.info("ResponseData"+samplerData);
ResponseCode/ResponseMessage
Applicable components :BeanShell Sampler 、BeanShell Assertion
ResponseCode、ResponseMessage Is the response code and response information of the response message , The type of String, Can read but write ;
log.info(" Response code :"+ResponseCode);
log.info(" Request header :"+ResponseHeaders);
Failure/FailureMessage/ Set response assertion
Applicable components :BeanShell Assertion
Failure and FailureMessage yes BeanShell Assertion Built in variables unique to components , Its function is to set the current sampler Test results ( Success or failure ),Failure The type is boolean,FailureMessage The type is String.
combination if Judge through variables Failure=false or Failure=true To set whether the assertion passes , When setting Failure=true when , You can also set FailureMessage To set the failure reason .
Variable description :
- Failure = false; // Assert success - The expected results are consistent with the actual results
- Failure = true; // Assertion failed - The expected results are inconsistent with the actual results
- FailureMessage = " Assertion failure description ";
Examples of use 1: Assert the status code
// State code assertion
log.info(" Status code :" + ResponseCode);
if(ResponseCode.equals("200")){
Failure=false;
}
else{
Failure=true;
FailureMessage=" The response status code is not 200"; // Specify the failure reason
}
Example 2: The response body contains specific characters
// Get response data
String response = prev.getResponseDataAsString();
log.info(" Response body :" + response);
// The response data contains
if(response.contains(" Login successful ")){
Failure=false;
}
else{
Failure=true;
FailureMessage=" The response data does not contain login success ";
}
Example 3:JSON Response body field extraction and assertion
take String The response body of type is changed to JSON Objects and operations require additional jar package , have access to org.json or gson, With json.jar For example , Download it and put it in JMeter/lib Under the table of contents , restart JMeter, add to BeanShell Assertion , as follows :
//JSON Response assertion
import org.json.*; // Import org.json package // Needed Json jar The net disk wrapped at the end of the text
String response = prev.getResponseDataAsString(); // Get response data
JSONObject responseJson = new JSONObject(response); // To JSON object
String message = responseJson.getString("message");
log.info(" Respond to message Field :" + message);
if(message.equals(" success ")){
Failure=false;
}
else{
Failure=true;
FailureMessage=" Respond to message Field not successful ";
}
FileName
Applicable components :BeanShell Sampler
FileName It's a java.lang.String, It contains a BeanShell Script name ( stay BeanShell Design of sampler " Script files " Section ).
Arguments object
Due to limited personal knowledge , I didn't understand the principle of this object , Here we mainly show the usage scenarios : Reading of request data .
Get request information :
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.Argument;
// Obtain requested url
String url = sampler.getPath();
//json Request data in format
Arguments arguments = sampler.getArguments(); // When calling, pay attention to sampler A lowercase letter
String requestBody = arguments.getArgument(0).getValue();
// Request data in form format
Arguments arguments = sampler.getArguments();
String fileType =arguments.getArgument(0).getValue();
String fileName = arguments.getArgument(1).getValue();
Abbreviation :
// No need to import Arguments
String requestBody = sampler.getArguments().getArgument(0).getValue();; // When calling, pay attention to sampler A lowercase letter
// The request is a form
String fileType = sampler.getArguments().getArgument(0).getValue();
String fileName = sampler.getArguments().getArgument(1).getValue();
Form request method , Obtain requested key and Value:
import org.apache.jmeter.config.Arguments;
import java.util.Map.Entry;
Arguments args = sampler.getArguments();
Map map = args.getArgumentsAsMap();
log.info("==============:"+args.getClass().toString());
Iterator itor = map.entrySet().iterator();
while(itor.hasNext()){
Entry entry = (Entry) itor.next();
log.info("==========key:"+entry.getKey());
log.info("========Value:"+entry.getValue());
}
Loop read request parameters ( Form requested )
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String a = arg.getValue();
log.info("Value:"+a);
vars.put("EMAIL",a);
}
jmeter jar package
link :https://pan.baidu.com/s/1LC6yP004tiYLt-zwhK202A
Extraction code :gard
边栏推荐
- DataGrip 2021 使用设置,让你使用起来更丝滑
- 知秋
- 测试用例管理工具推荐
- Matching strategies and methods: known detection, the ratio of nearest neighbors to next nearest neighbors, fast matching methods, etc. (3D reconstruction task1-6)
- How to choose the model for remote real machine test?
- What to do if the research and development quality is poor
- 根据进程名一键批量结束进程(chromedriver.exe)
- . Common commands for jar system service maintenance
- 【初识Jmeter和线程组】
- How to do app installation test?
猜你喜欢
10061 unknown error error is reported when connecting to the previously available MySQL database
postman接口测试和压力测试
ms17_ 010 invading win7
“cannot get hvm parameter CONSOLE_EVTCHN (18): -22!”的解决方法
JMeter之响应断言
【Jmeter配置元件之csv数据文件配置】
Problems related to writing files and linked list pointers
Day02 test case knowledge summary (Part 1)
实现页面与页面之间的信息交换
Test case exercise 2 - vendor account information
随机推荐
快速解决电脑无线网络无法连接问题
About char str[20]= "" and char str[20]=““
页面重定向
Class inheritance experiment report
JMeter之以页面形式保存测试过程数据
Solve the essential matrix from the basic matrix to obtain the parameters of the camera (3D reconstruction task1-5)
[common interview questions of network protocol]
loadrunner清除浏览器缓存
charles常用功能
整数变换问题
Day03 测试用例知识点总结(下)
Notes on generation model (I): basic knowledge of probability
How to write the use case of APP login function?
Postman's solution to "failed to obtain token through data.token in tests"
动态规划求解(添+号求最小值和问题)
Raptor visualization tool
Jenkins build
2022年最新软件测试工程师笔试真题及答案(搜狐、华为、蓝港在线)
【软件测试模型进化】
2021-06-22