Ngrinder's Groovy Script usage guide (HTTP request details)

Source: Internet
Author: User
Tags http redirect http request response code set cookie groovy script

Make sure you understand Ngrinder's groovy scripting structure: Ngrinder's Groovy Scripting Usage Guide (groovy scripting structure)

When you create a Groovy script on Ngrinder, it automatically generates a basic script that lets us split the description

Import Httpclient.cookie Import httpclient.cookiemodule import httpclient.httpresponse import httpclient.nvpair Import Net.grinder.plugin.http.HTTPPluginControl Import net.grinder.plugin.http.HTTPRequest Import Net.grinder.script.GTest Import Net.grinder.scriptengine.groovy.junit.GrinderRunner Import Net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess Import Net.grinder.scriptengine.groovy.junit.annotation.BeforeThread Import org.junit.Before Import org.junit.Test Import
Org.junit.runner.RunWith import static Net.grinder.script.Grinder.grinder import static org.hamcrest.Matchers.is Import static Org.junit.Assert.assertThat/** * * @author AUB */@RunWith (Grinderrunner) class Testrunner {Publi C Static gtest test public static HttpRequest request public static nvpair[] headers = [] public static Nvpair
        [] params = [] public static cookie[] cookie = [] @BeforeProcess public static void Beforeprocess () { Httpplugincontrol.getconnectionDefaults (). Timeout = 6000 test = new Gtest (1, "www.aub.com") Request = new HttpRequest ()//Set request header Data list<nvpair> headerlist = new arraylist<nvpair> () Headerlist.add (New Nvpair ("Test_header",  "Test_header_value")) headers = Headerlist.toarray ()//Set request parameter list<nvpair> paramlist = new

        Arraylist<nvpair> () Paramlist.add (New Nvpair ("WD", "ngrinder") params = Paramlist.toarray () Set cookie information list<cookie> cookielist = new arraylist<cookie> () Cookielist.add (New cookie
        ("username", "Aub", "www.aub.com", "/", New Date (32503647599000L), false))
    cookies = Cookielist.toarray ()//Log Grinder.logger.info ("before process.") } @BeforeThread public void Beforethread () {Test.record (this, "test")//Configure delay report statistic results grin Der.statistics.delayReports = TRUE//log grinder.logger.info ("before Thread. ")}
        @Before public void before () {//Set this request header Request.setheaders (headers)//Set cookies for this request Cookies.each {Cookiemodule.addcookie (it, Httpplugincontrol.getthreadhttpclientcontext ())}//Logging GRI Nder.logger.info ("Before thread. init headers and Cookies} @Test public void Test () {HttpResponse result = Request. GET ("http://www.baidu.com/s", params) if (Result.statuscode = = 301 | | result.statuscode = = 302) {GRI Nder.logger.warn ("Warning. The response may is not correct.
        The response code was {}. ", Result.statuscode)}-else {assertthat (Result.statuscode, is (200)) }
    }
}
Static Variable Description
public static gtest test public
static HttpRequest request public
static nvpair[] headers = [] public
static N vpair[] params = [] public
static cookie[] cookies = []
Defines the gtest static variable test definition httprequest static variable request, which is used to send an HTTP request definition Nvpair array headers, which holds the generic request header data definition Nvpair array params, for storing requests Parameter data definition cookie array cookies for storing common cookie data initializing process-level data

A method that uses @BeforeProcess annotations defines the behavior that should be performed before a process is called

 @BeforeProcess public static void Beforeprocess () {//HTTP request time-out, unit milliseconds Httpplugincontrol. Getconnectiondefaults (). Timeout = 6000 test = new Gtest (1, "www.aub.com") Request = new HttpRequest ()//Set Request Header data list<nvpair> headerlist = new arraylist<nvpair> () Headerlist.add (New Nvpair ("Test_header", "Test_h Eader_value ")) headers = Headerlist.toarray ()//Set request parameters list<nvpair> Paramlist = new Arraylist<nvpai R> () Paramlist.add (New Nvpair ("WD", "Ngrinder")) params = Paramlist.toarray ()//Set cookie information list<  cookie> cookielist = new arraylist<cookie> () Cookielist.add (New Cookie ("username", "Aub", "www.aub.com", "/", New Date (32503647599000L), false)) cookies = Cookielist.toarray ()//record log grinder.logger.info ("Before Proces S. ")} 
The HTTP request time-out is set first, in milliseconds gtest is the unit that counts the test records, within the script, each Gtest object uses a unique numbering definition, can have descriptive information, uses the Gtest constructor method gtest (int number, String Description) created. If you create more than one numbered object, only the first one is selected. Use new HttpRequest () to create an HttpRequest object that initiates an HTTP request request header and a request parameter, all of which are key-value pairs of object Nvpair-type arrays that can be passed by Cookie (string name, string value, S Tring domain, String path, Date expires, Boolean secure) constructs a cookie object and then stores it in the appropriate array for later use to print the execution log initializing thread-level data

A method that uses @BeforeThread annotations defines the behavior that should be performed before a thread is called

@BeforeThread public
void Beforethread () {
    Test.record (this, "test")
    //Configure delay Report statistics results
    Grinder.statistics.delayReports = True
    //log
    grinder.logger.info ("before thread.")
}
Use Gtest's record (object target, String methodName) to configure the method that needs to be counted for Gtest, target only Script object, here is this, MethodName is the method name to be counted, usually is @Test the method of the annotation. If not configured, the method executes normally, but there is no statistical data, and each method that is @Test annotation is a whole transaction, and when the test is run, even if there is multiple HTTP requests are only counted once.Configure Latency Report Statistics results finally print the execution log initializing test-level data

Use the method of @Before annotations to define the behavior that should be performed before each method of the @Test annotation is executed

@Before public
Void before () {
    //Set this request header
    request.setheaders (headers)
    //Set Cookies
    for this request Cookies.each {Cookiemodule.addcookie (it, Httpplugincontrol.getthreadhttpclientcontext ())}
    //Logging
    Grinder.logger.info ("Before thread. init headers and Cookies ")
}
Set this request header set the cookie for this request finally print the execution log Defining test Behavior

Use @Test annotation method to define test behavior and be executed multiple times

@Test public
void Test () {
    //initiating GET request
    HttpResponse result = Request. GET ("http://www.baidu.com/s", params)

    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 ())
    }
}
Through request. The Get method initiates an HTTP GET request, or it can use its overloaded method, which executes the request header according to the request's return result separately, and if it is the return status code of HTTP redirect, then the log is played, of course you can do other processing, otherwise, use assertion Assertthat The results are verified by the method and are automatically entered into the statistical results. The HttpRequest object also has other request methods: Post,put,delete and so on. ThinkingIf the request header of the test script is the same, can it be put into @BeforeThread or @BeforeProcess, is it helpful to test the performance of the script itself?

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.