How to Use Groovy RegEx For Testing
August 24, 2020

How to Use Groovy RegEx For Testing

Open Source Automation

Using Groovy RegEx (Regular Expressions) creates greater flexibility and saves time for retrieving test data. 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 Groovy RegEx when performance testing an API response with JMeter.

Let’s get started.

Back to top

What is Groovy RegEx?

Regular Expressions in Groovy 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.

Back to top

Groovy RegEx Testing Example

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).

Back to top

Using Groovy RegEx 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 RegEx Thread Group

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

Adding dummy sampler to thread group

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"}
  ]
}

Adding data to Dummy sampler

4. Add a JSR223 Assertion to the Dummy Sampler.

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

JSR223 assertion

JSR223 Assertion -> Language Groovy

Choosing Groovy language in JSR223 assertion

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\"");
}

 

Adding code to JSR223 assertion

The code shown above does the following:
 

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

This 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(); 

This 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": "(.+)"'; 

This 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); 

This is 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); 

This 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()

This 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.

JMeter console

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

JSR223 Assertion Result

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.

Back to top

Using Groovy RegEx 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");
}

Adding code to JSR223 assertion

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

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

This 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()

This 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:

JSR223 assertion

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.

Back to top

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; 

This 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 listREGEX = new ArrayList<>();
listREGEX.add("category_name");
listREGEX.add("category_id");
listREGEX.add("category_goods"); 

This 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 listParametersFromAPI = new ArrayList<>();

 

This 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 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:

JSR223 assertion result

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.

Back to top

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.

START TESTING NOW

Related Resources:

This blog was originally published on October 10, 2018, and has since been updated for accuracy and relevance.

Back to top