Search code examples
groovyjmeterjsr223

Jmeter JSR223 Groovy read file line by line and do http POST


  • I am trying to iterate files in the folder. each file has multiple json strings delimited by newline. Once the json is retrieved, will have to get the specific node of the json and POST it to http server.

  • Initially i thought will use the csv data set config, but i was able to get nested json from the files. After some of the reading tutorials of jmeter i finally went ahead with JSR223 to have a custom script which reads the file and puts in ctx, which will be used by sampler to send the data.

Here is what i have done till now.

Test plan
    -> Thread group
        -> JSR223 PreProcessor : This is where i am reading file and adding it to vars, its like "json_{number}" and "GETfileLength"
    -> ForEach Controller : This is sibling of Thread group
        -> HTTP Request : Inside for Each controller has a configuration of host, port and the path and in the body i have mentioned ${json_out}
        -> View Results Tree 
        -> Summary Report    

Groovy script present in pre-processor

    log.info("------ start ----------");
    File file = new File("/data/sample1.json")
    def line;
    def noOfLines=0
    file.withReader { reader ->
        while ((line = reader.readLine()) != null) {
            noOfLines++
            vars.put("json_"+noOfLines, line)
        }
    }
    vars.put("GETfileLength",noOfLines.toString()) ;
    log.info("------ end ----------");

enter image description here enter image description here enter image description here

  • In this above hierarchy of test plan i dont see the script is being called ( checked logs) . If i remove forEach controller the script gets called but i dont know how to give the variable name in the http POST body for dynamic variables.

Solution

  • According to documentation

    A Pre-Processor executes some action prior to a Sampler Request being made.

    Check the Execution order

    Please note that Timers, Assertions, Pre- and Post-Processors are only processed if there is a sampler to which they apply. Logic Controllers and Samplers are processed in the order in which they appear in the tree. Other test elements are processed according to the scope in which they are found, and the type of test element. [Within a type, elements are processed in the order in which they appear in the tree]

    This is the reason your script isn't working for the forEach controller.

    Try using JSR223 Sampler instead of JSR223 pre-processor. You can ignore the sample result also.