Preface Groovy Script
Ngrinder's groovy script is a sequential structure that allows users to perform a variety of complex testing tasks by writing functions that are pre-programmed during script execution.
Ngrinder of processes and threads
Ngrinder uses processes and threads to simulate multiple users. For example, if you set up the following tests. Only one agent will be activated, 1 processes will be called, and then this process will consist of 2 running threads. Each thread behaves like a 1-user. As a result, 2 virtual users are running. If you increase the agent count to 2, there is a total of 4 virtual users (vusers).
concurrency = number of agents x number of processes x threads
If you enter the total number of virtual users in the VUser per agent, Ngrinder according to the internal algorithm, the appropriate calculation, such as input 100, when the number of agents is 1 o'clock, will become 99, the algorithm can be process_and_thread_ Policy.js this file to modify.
If the agent's memory 4G or less, the recommended process should not exceed 10, the number of threads should not exceed 200.
- Official Latest test: 4G memory agent can simulate up to 4000 virtual users.
?
Preset functions
The
is a good understanding of the
structure of the Ngrinder groovy script, based on the interpretation of the agent, process, and thread on the face. The
Controller sends the PIN to the agent and each agent initiates the corresponding number of processes according to the algorithm, and each process initiates the corresponding number of threads, performing the test task.
Annotations |
Description |
Number of executions |
Use Cases |
@BeforeProcess |
Functions executed before the process is called |
Once per process |
Load resource files shared by threads, define public variables, etc. |
@AfterProcess |
Execute the function before the process is terminated |
Once per process |
Close Resource File |
@BeforeThread |
Functions that are executed before each thread is called |
Once per thread |
Log in to the target system to establish some values within the thread, for example, Cookie processing |
@AfterThread |
Functions that are executed before each thread is terminated |
Once per thread |
Exit system |
@Before |
The function that should be executed before each method that is @Test annotated is executed |
The same number of virtual users |
Shared logic, variable settings for each method that is @Test annotated |
@After |
The function that should be executed after each method that is @Test annotation is executed |
The same number of virtual users |
Rarely used |
@Test |
The main test behavior, which will be executed multiple times |
The same number of virtual users |
Test body |
?
Groovy Script Instance
?
Example of pressure measurement
/* This script is a */import static net.grinder.script.Grinder.grinderimport static org.junit.assert.*import static for the test interface that needs to be checked Org.hamcrest.matchers.*import Net.grinder.plugin.http.HTTPRequestimport Net.grinder.plugin.http.HTTPPluginControlimport Net.grinder.script.GTestimport Net.grinder.script.Grinderimport Net.grinder.scriptengine.groovy.junit.GrinderRunnerimport Net.grinder.scriptengine.groovy.junit.annotation.BeforeProcessimport net.grinder.scriptengine.groovy.junit.annotation.beforethread//import static net.grinder.util.grinderutils.*// Can use the If you ' re using ngrinder after 3.2.3import org.junit.Beforeimport org.junit.BeforeClassimport org.junit.t Estimport org.junit.runner.RunWithimport java.util.Dateimport Java.util.Listimport java.util.ArrayListimport Org.slf4j.LoggerFactory; Import Ch.qos.logback.classic.level;import Httpclient.cookieimport Httpclient.cookiemoduleimport Httpclient.httpresponseimport Httpclient.nvpairimport Java.text.simpledateformat;import Org.apache.commons.codEc.binary.base64;import Java.security.spec.pkcs8encodedkeyspec;import Java.security.keyfactory;import Java.security.privatekey;import Java.security.signature;import Java.util.arrays;import Org.apache.commons.lang.stringutils;import Java.lang.StringBuilderimport java.io.unsupportedencodingexception;/* * * A Simple example using the HTTP plugin This shows the retrieval of a * single page via HTTP. * * This script was automatically generated by Ngrinder. * * @author Admin */@RunWith (Grinderrunner) class Testrunner {public static gtest test public static HttpRequest re Quest//define global variable public static nvpair[] params = [] public static cookie[] cookie = [] public static String PR Ivate_key public static string[] contents = [] @BeforeProcess public static void Beforeprocess () {Httpplu Gincontrol.getconnectiondefaults (). Timeout = 6000 test = new Gtest (1, "Test1") Request = new HttpRequest () Gets the encrypted private key content contents = new File ("./resourceS/rsa_private_key_pkcs8.pem ") as string[] StringBuilder private_str = new StringBuilder (); for (int i=0;i<contents.length;i++) {if (Contents[i].charat (0)! = '-' && contents[i]! = null) { Private_str.append (Contents[i]). Append ("\ n"); }} Private_key = Private_str.tostring ()//debug Output Grinder.logger.info ("before process."); } @BeforeThread public void Beforethread () {Test.record (this, "test") grinder.statistics.delayReport S=true; Grinder.logger.info ("before thread."); }//Custom function, modify HTTP header data Private nvpair[] headers (POST) {if (post! = null) {post= "&" +post }else{post= ""} def AppID = "1111111111111111111111" def appcode = "11111" Long cu Rrenttime = System.currenttimemillis () def JSON = "appid=" +appid+ "&appcode=" +appcode+ "&" + "+" timestamp= "+cu Rrenttime+post def sign = Getsign (jSon)//grinder.logger.info (currenttime.tostring ()) return [New Nvpair ("Content-type", "appli Cation/json;charset=utf-8 "), New Nvpair (" AppId "," 1013f9d4e97026cb07e3fdea1b560f2f "), New NV Pair ("sign", sign), new Nvpair ("Timestamp", currenttime.tostring ()), New Nvpair ("Appcode", " 11111 ")]; }//Custom function, generate YYYY-MM-DD HH:MM:SS format of the day date string def today () {String str = ""; SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Calendar lastdate = Calendar.getinstance (); str = Sdf.format (Lastdate.gettime ()); return str; }//Custom function plus sign private getsign (POST) {//Add-on algorithm slightly return sign} @Before public void before () { Request.setheaders (Headers ()) Cookies.each {Cookiemodule.addcookie (it, HTTPPLUGINCONTROL.GETTHREADHTTPCLIENTC Ontext ())} grinder.logger.info ("Before thread. init headers and cookies "); } @Test public void Test () {//parameter initialization def domain = "api.xxxx.com" Def Timestr=today () def J Son= ' {"EventCode": "1111111", "eventtime": "' +timestr+ '", "Channelcode": "1111111", eventtime ":" ' +timestr+ ' "}} '; Get the header information after the signature def head = headers ("bizcontent=" +json)//grinder.logger.info (head.tostring ()) httprespons e result = Request. POST (' http://' +domain+ '/channel/v1/mot/receive ', json.getbytes (), head)//httpresponse result = Request. GET ("http://106.14.8.248/phpapi.php", params) if (Result.text.equals (New String (Result.text.getBytes ("iso8859-1"), "Iso8859-1")) {result.text=new String (result.text.getBytes ("iso8859-1"), "Utf-8"); }//debug output header information Grinder.logger.info ("result=" +request.getheaders ())//debug output result data grinder.logger.info ("result=" +result.text) if (Result.statuscode = = 301 | | result.statuscode = 302) {Grinder.logger.warn ( "Warning. The response may is not COrrect. The response code was {}. ", Result.statuscode); } else {Assertthat (Result.statuscode, is (200)); } }}
Ngrinder (ii) Stress test script Groovy Combat