JMeter comes bundled with a Regular Expression Extractor component that gives you fine-grained control over what to extract from a server response using regular expression syntax. Readers familiar with regular expression syntax will feel right at home, but don't worry if you haven't used regular expressions before. Regular expressions are special characters that match portions of a field based on a set of rules defined by a regular expression pattern. More information about regular expressions can be found on http://en.wikipedia.org/wiki/Regular_expression or by searching on the Internet.
How to do it…
In this recipe, we will cover how to use the Regular Expression Extractor component in JMeter to extract server responses to make our test script dynamic in nature. Perform the following steps:
Launch JMeter.
Open the ch2_regex.jmx test script located in the scripts/ch2 directory.
Run the script.
Observe the errors in the View Results Tree listener. Notice the response code is 403, indicating a forbidden request. This is shown in the following code:
Add Regular Expression Extractor to the request labeled add_regex_here by navigating to add_regex_here | Add | Post Processors | Regular Expression Extractor.
Fill in the values as follows:
Response Field to check: Headers
Reference Name: token
Regular Expression: XSRF-TOKEN=(.+);
Template: $1$
Match No. (0 for Random): 0
Default Value: NOT_FOUND
Save and re-run the script.
Observe that the errors are now gone and the post is successful. This is shown in the following screenshot:
How it works…
The test script is recorded for a site that uses Cross-Site Request Forger (CSRF) to prevent against malicious attacks that prey on user vulnerability. As such, a token is attached to each user's session that is then sent along with every request from that user. Each user gets their own unique token, and therefore, using the same token for two users flags an error on the server and the request is denied. That is exactly what happened in step 4.
In steps 5 and 6, we extracted the CSRF token with the aid of Regular Expression Extractor, and correctly sent the unique token for the rest of the requests for that user in the test script. Doing so allowed each request to be completed successfully.
There's more…
This is only one way Regular Expression Extractor can be used. There are several more cases where it could come to the rescue. These include the following:
Extracting URL paths
Extracting HTML responses
Extracting XML responses
Extracting JSON responses
You will find yourself using Regular Expression Extractor quite a lot in your testing scenarios.
Tip
To get the most out of Regular Expression Extractor, read more on regular expressions. Understanding regular expressions is critical to defining the correct pattern matches in your test script.