Search code examples
jsoncookiesjmeterbackslashbeanshell

JMeter Beanshell adds backslash to cookies values


The application for which I am preparing performance script is implemented on Sails and uses cookies for validating authentication for API calls. Using the HTTP Cookie Manager from JMeter did not help as it did not record all the cookie values. I was able to add them manually using beanshell preprocessor

The snippet of beanshell code:

CookieManager manager = sampler.getCookieManager();
Cookie cookie1 = new Cookie("cookie1","someValue","localhost","/",false,0);
manager.add(cookie1);

This code successfully added cookie1 into cookies in JMeter.

I also need to add another cookie which has value similar to JSON.

CookieManager manager = sampler.getCookieManager();
Cookie jsonCookie = new Cookie("cookie1","{\"Element\":{\"child1\":\"child1value\",\"child2\":\"child2value\"}","localhost","/",false,0);
manager.add(jsonCookie);

The value of this new cookie (jsonCookie) looks fine in the Debug Sampler. When I look for this same cookie in the Request, the Cookie variable has additional escape characters added to the doublequote.

Http Request Cookie Data:
cookie1=somevalue;jsonCookie="{\"Element\":{\"child1\":\"child1value\",\"child2\":\"child2value\"}"
Debug Sampler value
COOKIE_cookie1=somevalue
COOKIE_jsonCookie="{\"Element\":{\"child1\":\"child1value\",\"child2\":\"child2value\"}" 

The addition of extra escape characters in the cookie data caused the authentication to fail. How do I make sure that the cookie values do not have these additional escape characters?

I have tried fetching these json values from User defined variables as well as passing them directly in Beanshell preprocessor. In both approach the resulting cookie value is the same.


Solution

  • You can change "Cookie Policy" dropdown to netscape in order to remove these "extra slashes"

    JMeter Cookie Manager Policy Netscape

    And actually I don't see any need for scripting here as you can add a custom cookie via User-Defined Cookies section like:

    JMeter Define Cookie

    A couple more recommendations:

    1. Don't run JMeter and application under test on the same machine as JMeter can be very resource intensive and you might get into situation when JMeter and application under test will be struggling for the OS resources
    2. If you have to do scripting consider switching to JSR223 PreProcessor and Groovy language as when it comes to high loads Beanshell performance might be a big question mark