Run massively scalable performance tests on web, mobile, and APIs

Request a Demo
Oct. 10th, 2018

Using Regular Expressions and Groovy for Testing in JMeter

Regular Expressions are special text strings that are used as templates for finding other strings that match them. They are a very powerful mechanism for retrieving data (substrings) from a string. In Apache JMeter™, Regular Expressions can be used from a built-in component, the Regular Expression Extractor, or they can be written in Groovy.

 

Using Regular Expressions with Groovy creates greater flexibility and saves time. For example, if you need to extract several different parameters, you can write just one script, instead of adding a Regular Expression Extractor for each request. In this article, I will show you how to use Regular Expressions in Groovy, when performance testing an API response with JMeter.

 

Let’s get started.

 

Suppose we have an online store's API. This API response returns a list of goods belonging to a specific group, as shown below:

 

{"category_id": "1", 
 "category_name": "Computers and accessories",
 "category_goods": [
	{"id": "100", "name": "monitor","price": "125"},
	{"id": "101", "name": "usb wire ","price": "10"}
  ]
}

 

In our test, we need to verify the following in the API response:

  1. The value of the category_id parameter is 1
  2. There are two goods in the list
  3. The following parameters appear in the list: category_id, category_name, category_goods

 

In the first verification, we will learn the most common use of Regular Expressions - verifying the value of a parameter from the API response (1). The second one will teach us how to count multiple values with a Regular Expression (two values). From the third we will learn how to verify multiple values through regular expressions (category_id, category_name, category_goods).

 

Using a Regular Expression to Get a Parameter Value

 

We will now verify that in the API response, the value of the category_id = 1.

 

1. Add a Thread Group

 

Right Click -> Threads -> Thread Group

 

groovy, regular expressions, jmeter

 

2. Preinstall the Dummy Sampler from the JMeter Plugins Manager and add it to your Thread Group:

 

Thread Group -> Add -> Sampler -> jp@gc - Dummy Sampler

 

using regular expressions with groovy in jmeter

 

The Dummy Sampler will simulate a response from the API for our demo purposes. For your testing, you can configure the machine you will be getting an API response from, in a sampler.

 

3. Add the following data to the Dummy Sampler:

 

{"category_id": "1", 
 "category_name": "Computers and accessories",
 "category_goods": [
	{"id": "100", "name": "monitor","price": "125"},
	{"id": "101", "name": "usb wire ","price": "10"}
  ]
}

 

groovy regular expressions, open source

 

4. Add a JSR223 Assertion to the Dummy Sampler.

 

Dummy Sampler-> Right Click -> Add ->  Assertions-> JSR223 Assertion

 

jmeter, regular expressions, apache groovy

 

JSR223 Assertion -> Language Groovy

 

how do i write regular expressions in groovy?

 

5. In the JSR223 Assertion, add the following code.

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String response = SampleResult.getResponseDataAsString();
String REGEX = '"category_id": "(.+)"';

Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(response);

if (matcher.find() && matcher.group(1).equals("1")) {
	
	log.info("The value of the \"category ID\" parameter is \"1\"");
	
} else {
	
	log.info("The value of the \"Category ID\" parameter was not found or is not equal to \"1\"");
}

 

load testing with groovy, regular expressions

 

The code shown above does the following:
 

import java.util.regex.Matcher;
import java.util.regex.Pattern;
- Imports Matcher and Pattern classes from the java.util.regex package, which are necessary for working with regular expressions. These classes are imported from JAR files in JMeter.

 

String response = SampleResult.getResponseDataAsString(); - Gets and converts a response from an API to a string. Assigns the received value to the "response" variable with the "String" data type.

 

String REGEX = '"category_id": "(.+)"'; - Creates a variable "REGEX" with data type "String" and assigns a value that is a regular expression. The regular expression will search for a match in an API response. In our case, the regular expression will return the value of the parameter "category_id".

 

Pattern pattern = Pattern.compile(REGEX); - a call from the Pattern class of the "compile (REGEX)" method. On the basis of the REGEX variable, it creates a Pattern class object. After creating a Pattern object, the resulting value is assigned to the variable "pattern". A Pattern object is required to create a Matcher object and match it in an API response. In other words, the Pattern object is our template (regular expression) on the basis of which the match will be searched in the API response.

 

Matcher matcher = pattern.matcher(response); -  Creates a Matcher object and assigns the resulting value to the "matcher" variable. An object of the Matcher class will be used to find matches, according to the created template ("pattern" variable), and also to work with the matches found.

 

if (matcher.find() && matcher.group(1).equals("1")) {
log.info("The value of the \"category ID\" parameter is \"1\"");
} else {
log.info("The value of the \"Category ID\" parameter was not found or is not equal to \"1\"");
} -  matcher.find()
- searches for a match according to the template created (“pattern” variable) and returns a boolean value of "true" if a match is found or returns a logical value of "false" if no match is found.

 

matcher.group(1) - Gets the value that was found when calling matcher.find (). In our case, matcher.group (1) returns the value "1".

 

log.info() - The method that prints information to the JMeter console.

 

If a match is found and the match value is "1", the message "The value of the  category ID parameter is "1" will be displayed in the JMeter console. Otherwise: “The value of the Category ID parameter was not found or is not equal to "1"”.

 

6. Open the JMeter console.

 

load testing regular expressions in groovy

 

7. After starting the test, we will see a result similar to the one in the image below:

 

running a test with regular expressions

 

In the image above, you can see that the message "The value of the category ID parameter is "1" is printed in the JMeter console. This means that the "category_id" parameter in the API response is "1". Check the response, to make sure your code is working correctly.

 

Success! Now let’s move on to counting multiple values from Regular Expressions.

 

Using a Regular Expression to Count Multiple Parameter Values

 

We will now verify that there are only two products in the API response. If you only want to check this type of response, go through steps 1-3, and then continue to step 8.

 

8. Add a JSR223 Assertion to the Dummy Sampler.

 

Dummy Sampler-> Right Click -> Add ->  Assertions-> JSR223 Assertion

 

JSR223 Assertion -> Language Groovy

 

9. In the JSR223 Assertion, add the following code.

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String response = SampleResult.getResponseDataAsString();
String REGEX = '"id": "(.+)", "name"';

Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(response);

if (matcher.results().count() == 2) {
	
	log.info("There are 2 goods in the response of the API");
	
} else {
	
	log.info("Number of goods in the response of the API is not equal 2");
}

 

checking variable values with groovy regular expressions

 

The first part of the code is the same as in step 5.

 

String REGEX = '"id": "(.+)", "name"'; -  Creates a variable "REGEX" with the data type "String" and assigns a value that is a regular expression, which will search for a match in an API response. In our case, the regular expression will return the value of the "id" parameter for each product.

 

if (matcher.results().count() == 2) {
log.info("There are 2 goods in the response of the API");
} else {
log.info("Number of goods in the response of the API is not equal 2");
} - matcher.results().count()
- Counts the number of matches that correspond to the number defined in the regular expression.

 

If a match is found and the number of matches is "2", then the message "There are 2 goods in the response of the API" will be displayed in the JMeter console. Otherwise: "Number of goods in the response of the API is not equal 2”. The main difference between the previous test and this one, is that before we were searching for a certain value, and now we’re counting the number of values.

 

10. After starting the test we will see a result like in the image below:

 

using multiple regular expressions

 

In the image above, you can see that the message "There are 2 goods in the response of the API" is printed in the JMeter console. Check the response, to make sure your code is working correctly.

 

Now let’s learn how to use multiple regular expressions.

 

Using Multiple Regular Expressions

 

We need to verify that the API response contains the following parameters: category_id, category_name, category_goods. If you only want to check this type of response, go through steps 1-3, and then continue to step 11.

 

11. In the Dummy Sampler add JSR223 Assertion.

 

Dummy Sampler-> Right Click -> Add ->  Assertions-> JSR223 Assertion

 

JSR223 Assertion -> Language Groovy

 

12. In the JSR223 Assertion, add the following code.

 

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.stream.Stream;

String response = SampleResult.getResponseDataAsString();

List<String> listREGEX = new ArrayList<>();
listREGEX.add("category_name");
listREGEX.add("category_id");
listREGEX.add("category_goods");

List<String> listParametersFromAPI = new ArrayList<>();

listREGEX.stream().forEach{elementFromListREGEX ->
	Stream<MatchResult> result = Pattern.compile(elementFromListREGEX).matcher(response).results();
     result.forEach{element -> listParametersFromAPI.add(element.group(0))}
};

if (listParametersFromAPI.size() == listREGEX.size()) {
	log.info("All parameters are present in the API response");
} else {
	log.info("There are no parameters in the API response or some parameters are missing");
}

 

finding multiple values in jmeter, groovy

 

The code shown above does the following:

 

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.stream.Stream;  -
Imports the Pattern, MatchResult classes from the java.util.regex package and imports the Stream class from the java.util.stream package needed to work with regular expressions. These classes are imported from JAR files that are in JMeter.

 

List<String> listREGEX = new ArrayList<>();
listREGEX.add("category_name");
listREGEX.add("category_id");
listREGEX.add("category_goods");
- Creates a list of parameters to be checked in the API response: category_name, category_id & category_goods. Each element from this list will be a regular expression, and matches will be sought to them in the API response. Before we were using one REGEX with its value, and now we're using multiple REGEXs, each with its own value to verify.

 

List<String> listParametersFromAPI = new ArrayList<>();  -  Creates an empty list. All the matches found using regular expressions from the "listREGEX"  list, will be written in this list. This additional list is created to verify that there is no duplication of parameters (two identical parameter names) in the API response. If there are duplicate parameters in the API response, then the regular expression will find two matches instead of one and the match found will be written in "listParametersFromAPI". Furthermore, by comparing the size of "listREGEX" and "listParametersFromAPI", we will be able to understand that there are two duplicate parameters in the API response instead of one.

 

listREGEX.stream().forEach{elementFromListREGEX ->
Stream<MatchResult> result = Pattern.compile(elementFromListREGEX).matcher(response).results();
     result.forEach{element -> listParametersFromAPI.add(element.group(0))}
};
- The Regular Expression searches for each item on the listREGEX list, and the result is added to listParametersFromAPI. listParametersFromAPI will contain the parameters that are actually contained in the API response.

 

if (listParametersFromAPI.size() == listREGEX.size()) {
log.info("All parameters are present in the API response");
} else {
log.info("There are no parameters in the API response or some parameters are missing");
}
- The size () method returns the size of the list (the number of items in the list). If the listParametersFromAPI (the list of actual parameters in the API response) is equal to the size of the listREGEX list (the list of expected parameters in the API response), then the message "All parameters are present in the API response" will be printed in the JMeter console. Otherwise: "There are no parameters in the API response or some parameters are missing".

 

After starting the test we will see a result like the one in the image below:

 

api response, regular expressions, groovy, jmeter

 

In the image above, the message "All parameters are present in the API response" is printed to the JMeter console. This message means that the API response contains the parameters category_id, category_name, category_goods. Check the response, to make sure your code is working correctly.

 

Running Your JMeter Test in BlazeMeter

 

After creating your JMeter script, you can upload it to BlazeMeter and run it in the cloud or from behind a firewall. You will be able to share your tests and results, run from multiple locations and get advanced reporting.

 

Try out BlazeMeter by putting your URL in the box below and your test will start in minutes. Or, request a free demo from one of our performance engineers.

     
arrow Please enter a valid URL

Interested in writing for our Blog? Send us a pitch!