Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Modifying Cookies in JMeter With Groovy

DZone's Guide to

Modifying Cookies in JMeter With Groovy

In this post, we will go through cookies usage in JMeter's JSR223/Beanshell samplers, by turning cookie managers into variables in the script.

· Web Dev Zone ·
Free Resource

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

HTTP Cookies are widely used nowadays, providing a way to store information that is exchanged between the agent and the server in the request headers. Cookies can be understood as small pieces of information where site preferences are stored. For example, cookies can store information about your location and provide more accurate advertising based on it.

A really friendly introduction to cookies and how to use them on Apache JMeter™ can be found at the blog post "Using JMeter´s HTTP Cookie Manager." Then, the blog "HTTP Cookie Manager Advanced Usage - A Guide" provides a more in-depth view with several examples.

In this post, we will go through cookies usage in JMeter's JSR223/Beanshell samplers, by turning cookie managers into variables in the script. This will allow us to modify cookies throughout the script during runtime. Several examples are included.

First, we need to add the HTTP Cookie Manager to our script. JMeter's cookie manager element is a useful tool that really alleviates cookie handling by storing and managing cookies. All of our cookie-related actions in the Groovy script will be performed by the Cookie Manager.

The JMeter HTTP Cookie manager implements the CookieManager class. Please check CookieManager for a full reference on this class.

Let's add an HTTP Cookie Manager to your JMeter test plan:

Set it to use the "standard" cookie policy as shown in this example:

A full description of the cookie policies can be read on Apache HTTP state. The "standard" policy is the most common one.

Now, let's get the Cookie manager element through a JSR223 preprocessor. The following sentences allow you to retrieve the Cookie manager into a variable:

import org.apache.jmeter.protocol.http.control.*

//Get cookie manager
CookieManager cm = sampler.getCookieManager()

The first sentence imports the package "org.apache.jmeter.protocol.http.control." Then we activate the Cookie Manager from the Test Manager into the cm variable by invoking the getCookieManager() method.

In this first example, we will create a cookie file and add it to the cookie manager. This action can enable us, for example, to set the preferences for our website through a cookie. Let's look at an example.

We will create a cookie.txt file placing it on the same directory where the script is. The content of this file is as follows:

opencart.abstracta.ustrue/false1557578515currencyEUR

Each of the seven values is separated by a tab and explained next:

  • Domain value where the cookie is valid. Set to opencart.abstracta.us in the example.
  • Flag: A boolean value indicating whether the cookie can be accessed by all the machines on the specified domain. Set to true.
  • Path: The path within the domain where the cookie is valid. Set to /.
  • Secure: A boolean value indicating if a secure connection is needed to access the cookie. Set to false.
  • Expiration: The epoch time value when the cookie will expire.
  • Name: Name of the cookie variable set to currency.
  • Value: The value assigned to the cookie. Set to EUR.

Now add an HTTP request sampler with a JSR223 preprocessor in JMeter:

Going through the Preprocessor script:

import org.apache.jmeter.protocol.http.control.*

//Get cookie manager
CookieManager cm = sampler.getCookieManager()

//Set cookie currency to EUR
cm.addFile("C:/work/jmeter-scripts-samples/cookie.txt")

The method CookieManager.addFile(String cookieFile) adds the cookie defined in the cookieFile parameter (cookie.txt in this example) to the cookie manager.

Viewing the Results Tree after running the test will show that the request performed includes the cookie defined in the file:

This could be a way of performing tests with different values. By setting the cookie values before issuing the HTTP requests, you can perform different application tests. If, for example, the currency value varies depending on the number of users from different regions, we can perform a specific number of tests using each of the distinct currencies.

A sample preprocessor script to do this could read the user region from a CSV with usernames and their regions and set the cookie value accordingly.

//Set cookie currency accordingly based on user region
if (vars.get("region") == "US")
cm.addFile("C:/work/jmeter-scripts-samples/cookieUS.txt")
else if (vars.get("region") == "EURO")
cm.addFile("C:/work/jmeter-scripts-samples/cookieEURO.txt")

We can also create and add cookies during any part of the test. Going further with the previous example, we can perform a second request and add a specific cookie.

In this occasion, the Cookie class will be used to create a new cookie. Please refer to Cookie for the full class specification.

We will create a cookie by adding the following line to the PreProcessor script:

Cookie c = new Cookie("sampleCookie", "sample", "opencart.abstracta.us", "/", false, 1557578515)

JMeter´s results tree will display two different cookies sent during the request:

The CookieManager class also provides a method to clean up all the cookies of the test by invoking clear(). In the following example, I added a new HTTP request sampler, where we scripted the following on the JSR223 preprocessor:

log.info("******************** Cookies count: " + cm.getCookieCount())
cm.clear()
log.info("******************** Cookies count after cleanup: " + cm.getCookieCount())

The method getCookieCount() is used in order to count the cookies the CookieManager collection has. First, set the JMeter log level to DEBUG so the method invocation is logged.

In the following screenshot, a sample run is shown where the Log Viewer Panel is enabled. It can be observed how the cookies are cleared:

In the last example, we will cover how to get a specific cookie and update any desired cookie value. Since several cookies are handled by the cookie manager, a collection is used to store them. The cookie manager implements a method to retrieve any specific cookie by its index on the collection by invoking get(int i). i is the desired cookie index.

The Cookie manager cookies collection starts at index 0.

The script content for this purpose is as follows:

import org.apache.jmeter.protocol.http.control.*

//Get cookie manager
CookieManager cm = sampler.getCookieManager()

Cookie c = cm.get(1)
log.info("******************** Cookies #1: " + c.getName() + "cookie Value: " + c.getValue())
c.setValue("newSampleValue")
log.info("******************** Cookies #1: " + c.getName() + "new cookie Value: " + c.getValue())

The execution output is shown next. It can be observed on the Log panel how the cookie value is modified.

Also, the results tree shows the new cookie value used on the second request:

That's it! You now know how to access and manage cookies with JSR223 and BeanShell elements.

Code something amazing with the IBM library of open source blockchain patterns. Content provided by IBM.

Topics:
http cookie manager ,groovy language ,jmeter ,cookies ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}