DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A General Overview of TCPCopy Architecture
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Handle HL7 MLLP Messages With Mule 4
  • How to Do API Testing?

Trending

  • Testing SingleStore's MCP Server
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Languages
  4. Modifying Cookies in JMeter With Groovy

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.

By 
Alejandro Berardinelli user avatar
Alejandro Berardinelli
·
Jul. 02, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
20.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Groovy (programming language) Testing Requests

Published at DZone with permission of Alejandro Berardinelli, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A General Overview of TCPCopy Architecture
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Handle HL7 MLLP Messages With Mule 4
  • How to Do API Testing?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: