Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Groovy script is failing to remove the space from the result sampler in JMeter

So I have built a customized listener(using groovy script) to post my result to influxdb but the current script is failing when there is a white space in the sampler name or transaction controller name.

Tried to put a fail safe(this will remove the space from the sampler result) in my script but it is not working

groovy script sample in the listener,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.samplers.SampleResult;

try {

Metrics = new StringBuilder();
 String status = "Failure";
  if (sampleResult.isSuccessful())
      status = "Success";
 if (sampleResult.getSampleLabel().startsWith("/"))
      Metrics.append("Requests")
 else
 Metrics.append("JMeter_Result")
 Metrics.append(",requestName=")
 .append(escapeValue(sampleResult.getSampleLabel()))
 .append(",httpstatuscode=")
 .append(sampleResult.getResponseCode())
 .append(",status=")
 .append(status)
 .append(",ScenarioID=")
 .append('${__groovy(vars.get("uniqueScenario_Id"),)}')
 .append(" responseTime=")
 .append(sampleResult.getTime())
 .append(",responsecode=")
 .append("\"${(sampleResult.getResponseCode())}\"")
 .append(",sentBytes=")
 .append(sampleResult.getSentBytes())
 .append(",receivedBytes=")
 .append(sampleResult.getBytesAsLong())
 .append( ",responseMessage=")
 .append("\"${(sampleResult.getResponseMessage())}\"")
 .append(",samplecount=")
 .append(sampleResult.getSampleCount())
 .append(",errorCount=")
 .append(sampleResult.getErrorCount())
 .append(" ")
 .append(sampleResult.getTimeStamp())
 .append("000000");
     if(sampleResult.getSampleLabel().equals("UserIdleTime"))
        {
        }
    else {
        PostMeasurement(Metrics.toString());
        }
} catch (Exception e) {
     log.error("Error in Grafana Metrics Listener : " +e );
}
//Escape the string values before posting the data
String escapeValue(String val) {
 val = val.replaceAll(",", "\\\\,")
 .replaceAll(" ", "\\\\")
 .replaceAll("=", "\\\\=")
 .trim();
    if(val.matches(".*\\s.*")) {
        val = val.replaceAll("\\s","");
        return val;
    }
    else {
        return val;
    }
 // return val;

}

// Post the result to influxDB
void PostMeasurement(String Metrics) {
 def httpclient = new DefaultHttpClient(new BasicHttpParams());
 def httpPost = new HttpPost();
 httpPost.setURI(new URI(vars.get("InfluxDBAPI")));
 httpPost.setEntity(new StringEntity(Metrics));
 HttpResponse response = httpclient.execute(httpPost);
 EntityUtils.consumeQuietly(response.getEntity());
}

Transaction Controller Name [with space]:

enter image description here

Failing With Error:
enter image description here

Transaction Controller Name [without space]:
enter image description here

>Solution :

Try the following function:

static String removeWhiteSpaces(String input) {
    return input.replaceAll(~/\s/, '')
}

Demo:

enter image description here

Also be informed that

  1. JSR223 Listener is being executed after each Sampler in its scope so your approach will be resource intensive and might have an impact on your test results. You might want to consider using your own implementation of the AbstractBackendListenerClient. See How to Develop a JMeter Plugin: Intro & Best Practices article for more details.

  2. The functionality of storing test metrics into InfluxDB is there already, check out Real-time results JMeter documentation chapter

  3. I don’t like this construction: ${__groovy(vars.get("uniqueScenario_Id"),)}, as per JSR223 Sampler Documentation

    When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.

    so if your uniqueScenario_Id may change during script execution only first occurrence will be cached and returned on subsequent executions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading