BeanShell Usage Summary (partial excerpt to Network) "Go"

Source: Internet
Author: User
Tags encode string prev response code vars

Note: Some of the information in this article is excerpt to

    • Source: http://www.cnblogs.com/puresoul/p/4915350.html
    • Source: http://www.cnblogs.com/puresoul/p/4949889.html
    • Source: http://blog.csdn.net/silencemylove/article/details/51373873

First, what is the bean Shell

    • BeanShell is a scripting language that conforms fully to the Java syntax specification and has its own syntax and methods.
    • BeanShell is a loosely typed scripting language (this is similar to JS);
    • BeanShell is written in Java, a small, free, downloadable, embedded Java source code interpreter with object scripting language features and a very streamlined interpreter jar file size of 175k.
    • BeanShell executes standard Java statements and expressions, plus some scripting commands and syntax.

Official website: http://www.BeanShell.org/

Ii. What Bean Shell does JMeter have?

    • Timer: BeanShell Timer

    • Front Processor: BeanShell preprocessor

    • Sampler: BeanShell Sampler

    • Post Processor: BeanShell postprocessor

    • Assertion: BeanShell Assertion

    • Listener: BeanShell Listener

Third, the use of BeanShell

In this introduction, the use of BeanShell preprocessor, other beahshell can be analogous. In this we use the Beahshell call ourselves to write the tool class, the tool class implements the password encryption, decryption function:

1, write the code in Eclipse, and then make the class into a jar package (right-click on the class->export->jar file) AR package put into jmeter directory \apache-jmeter-2.13\lib\ext

3. Open JMeter, add an HTTP sampler (call Login interface), add a BeanShell preprocessor under sampler ( if JMeter is already open, the jar package in step 2 takes effect, Must restart JMeter)

4, in BeanShell Preprocessor import our jar package, call inside the Add, solve the password method, the results are stored in the JMeter variable, the following two methods are the most commonly used in BeanShell:

    • Vars.get (String paramstr): Get variable Value
    • Vars.put (String key,string value): To save the data to the JMeter variable

Import com.pingan.ff.account.user.utils.*;//Encryption System.out.println ("* * * * * * * * * * * * * *); String password = "123123"; String encode = securityutils.getkey (password);//Invoke the method in the tool class to encrypt System.out.println ("Set my Encode"); Vars.put ("Encode" , encode);//Save the value to the JMeter variable encode string getencode=vars.get ("encode"); System.out.println ("Get my Encode:" + getencode);

5, the encrypted password is stored in the JMeter variable, and then in the HTTP sampler can be used through ${encode}:

6. Execute script:

Four, Bean shell common built-in variables

  JMeter has built-in variables in its BeanShell that allow users to interact with JMeter, the main variables and how to use them as follows:

    • Log: Write information to Jmeber.log file, using method: Log.info ("This is log info!");

    • CTX: This variable refers to the context of the current thread and is used in the following way: Org.apache.jmeter.threads.JMeterContext.

    • VARs -(jmetervariables): Manipulate the JMeter variable, which actually refers to the local variable container in the JMeter thread (essentially map), which is a bridge between test cases and BeanShell interaction, common methods:

A) Vars.get (String key): Gets the value of the variable from the JMeter

b) Vars.put (String key,string value): Data is stored in the JMeter variable

More ways to see: org.apache.jmeter.threads.JMeterVariables

    • Props -(Jmeterproperties-class java.util.Properties): Manipulate the JMeter property, which references the configuration information of JMeter, can get the properties of JMeter, It is used in a similar way to VARs, but it can only be put in a string type value, not an object. Corresponds to Java.util.Properties.

A) Props.get ("START.  HMS "); Note: Start.hms is a property name, defined in file jmeter.properties

b) Props.put ("PROP1", "1234");

    • prev -(Sampleresult): Gets the information returned by the previous sample, common methods:

A) getresponsedataasstring (): Get response information

b) Getresponsecode (): Get Response code

More ways to see: Org.apache.jmeter.samplers.SampleResult

    • Sampler-(Sampler): Gives access to the current sampler

Five, custom functions

In BeanShell, we can use the Java language Custom function to handle the specific logic, combining the BeanShell built-in objects for variable access, so that we test to improve the flexibility of the script.

Example:

1. Add a variable to the test plan: Hello = Kitty

2, Debug sampler-1 and debug Sampler-2 Nothing to deal with, used to query comparison Beahshell processing results before and after

3. The script in BeanShell Sampler is as follows:

4. Operation Result:

    • Debug sampler-1 Display: Hello=kitty
    • The result returned in BeanShell Sampler is: Success
    • Debug sampler-1 Display: hello=world,jmeter=111111

Is there any way to think that the custom function in the above (c) is too cumbersome and not beautiful? And if we already have a ready-made Java source file or class file, is there any way we can reference it directly in Jemter? This is what this section is going to cover, directly on the example:

1, if I have a Java source file, named: Myclass.java, the code is as follows:

Package Test;public class myclass{public    int Add (int a, int b)    {        return a + b;    }    }

2. The Bean shell uses the following code:

Introduce Java into the bean Shel by means of the source ("code path") method, and then call the method like Java, new class, and then call the Add method inside.

3. Operation Result:

Vii. referencing an external class file

Now you know how to reference external files, sometimes what if we only have class files? In fact, you can also refer to the class file directly in JMeter, for example:

1, directly to the example of the Java file compiled into a class file, how to compile please self-Baidu.

2. The Bean shell uses the following code:

Using the Addclasspath ("d:\\") method to introduce the class file, import the package and class with import, and then you can call it like Java

3. Operation Result:

Viii. referencing external jar packages

The above four or five describes how to reference external Java and class files, if the file is a long way we can make them into a jar package and then call in Jemter, how to use can be seen in my previous article has introduced: JMeter Bean Shell Use (a).

One thing to add here is the way the jar is introduced in JMeter:

1, the previous article has been used: put the jar package in the JMeter directory \apache-jmeter-2.13\lib\ext

2. Add the jar packages that need to be referenced directly at the bottom of the test plan's right panel, such as:

Ix. Other uses

1. Define the following three variables in test plan:

2. The Bean shell can be scripted as follows:

A, bean shell can accept incoming parameters, such as: ${u1} ${U2} ${u3}

b, parameters can be extracted by bsh.args[] sequentially

c, the bean shell provides a built-in variable parameters to hold the collection of parameters

3. Operation Result:

In 1, enter these two sentence settings:

Responsecode = 500;
Responsemessage = "This is a test";

In 2, enter these two sentence settings:

Log.info (Parameters);

Log.info (Label);

X. Extracting JSON data

Requirements: Extract sample Returns the value of all the name fields in the JSON data, returning the following JSON format:

{"Body": {"apps": [{"Name": "111"},{"name": "222"}]}}

JMeter Add the Post processor BeanShell Postprocessor

Note: The imported JSON package in the script needs to be downloaded to the \lib\ext on the network, please be aware


Import org.json.*; String response_data = prev.getresponsedataasstring (); Jsonobject data_obj = new Jsonobject (response_data); String apps_str = Data_obj.get ("Body"). Get ("apps"). ToString (); Jsonarray Apps_array = new Jsonarray (APPS_STR); String[] result = new String[apps_array.length ()];for (int i=0;i<apps_array.length (); i++) {    Jsonobject app_obj = New Jsonobject (Apps_array.get (i). toString ());    String name = App_obj.get ("name"). toString ();    Result[i] = name;} Vars.put ("Result", arrays.tostring (result));

Xi. assertions

Import txtwrite.*; String response_data = prev.getresponsedataasstring (); String assert_data= "account ${num}"; Txtwrite writedata=new txtwrite (); if (Response_data.indexof (assert_data)!=-1)//The response of the request contains custom characters, the assertion result is false{    Failure=false;    String message= "${__time (Yyyy-mm-dd HH:mm:ss,)}   New Account" "+assert_data+" "Success";    Failuremessage=message;    Writedata.contenttotxt ("D:/xykyinterfaceautotest.log", message);    } else{    failure=true;    String message= "${__time (Yyyy-mm-dd HH:mm:ss,)}   New Account" "+assert_data+" "Failed----------";    String response= "This request response data:" +prev.getresponsedataasstring () + "----------";    String need_assert= "Data to assert:" +assert_data;    Failuremessage=message+response+need_assert;    Writedata.contenttotxt ("D:/xykyinterfaceautotest.log", Message+response+need_assert);}

BeanShell Usage Summary (partial excerpt to Network) "Go"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.