I want to check if a response attribute of one http request exits in another http request as well. How can I do that? - jmeter

HTTP request
.. regular expression to pick up a token "PostID"
HTTP request
..Beanshell assertion to verify if ${PostID} exists in the response
I am using the while controller to loop the request till PostID is found
while condition being ${__javaScript("${count}" != 1)}
Beanshell assertion is failing though I see the PostID in the response of "FetchSentPost" request
I need the while loop to end on the first encounter of Post ID in the HTTP request "FetchSentPost"
Where Am I going wrong?

You have a syntax error in your Beanshell script:
String ID = vars.get(PostID);
^^^^^^
should be
String ID = vars.get("PostID");
Going forward you can add debug(); directive to the beginning of your JMeter script for troubleshooting. I would also recommend switching to JSR223 Assertion and Groovy language, Groovy performs much better and more Java-compliant.

There are several mistakes made in the script.
Condition must be changed to ${__javaScript(${count} != 1)}. No double quotes.
In BeanShell Assertion, instead of count += 1, you must assign count value using vars.put as follows vars.put("count", 1);
As Dmitri mentioned, other mistake is:
String ID = vars.get("PostID");
Related to contains vs regex matching, try both after making above changes. I tried with contains, it is working.
Using contains:
while(!str.contains(ID)){
vars.put("count", 1);
}

created a user defined variable 'PostIdFound' with value 'False' outside the while loop.
Changed the while condition to ${__javaScript(${PostIdFound} != true)}
and then changed the BeanShell script as follows
import java.util.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String ID = vars.get("PostID");
String str= SampleResult.getResponseDataAsString();
vars.get("PostIdFound");
if(str.contains(ID)){
vars.put("PostIdFound","true");
}
Issue Resolved. Thankyou #Dmitri T and #Naveen for the help

Related

Jmeter values mapping

How to achieve a kind of mapping between string and numeric values that can be used for comparison in assertion? Example:
MAP "DELIVERED"=0
"PENDING"=1
"WAITING"=2
sampler1 - extracted numeric_value=0
sampler2 - assert string value="DELIVERED" is equal to its numeric value
Please check the below test plan:-
I have used variable name from regular expression of 1st sampler in the switch controller like ${regVar}..Then used the second request 3 times i.e. 0,1,2 and used response assertion with the desired value like "DELIVERED"=0 for first sampler under switch i.e "0" then in second "PENDING"=1 i.e "1"..so on.
With this, based on the regEx value from 1st http sample, only one http request will be send for 2nd sampler and that request have it own assertion. I have tried with both positive and negative cases. Please change the assertion value based on your requirements.
Please check if it helps.
Be aware of JSR223 Assertion which allows you to use arbitrary Groovy code to define pass/fail criteria.
You can access the numeric_value using vars shorthand for JMeterVariables class like:
def numericValue = vars.get('numeric_value')
Example code:
def myMap = ['0':'DELIVERED', '1':'PENDING', '2':'WAITING']
def numericValue = vars.get('numeric_value')
log.info('Numeric value is: ' + numericValue)
log.info('Status is: ' + myMap.get(numericValue))
Demo:
More information: Scripting JMeter Assertions in Groovy - A Tutorial
Thanks Dmitri, implemented solution based on your suggestion and it suites fine.

In JMeter, How do i loop until a result is found

I have a request in Jmeter that I need to loop until I find the result I am looking for. I have read a few bits about a while controller but found them unhelpful as they seem to glance over vital information or are using an older version of Jmeter
I'm currently using Jmeter 5.0, and I have attempted to implement a while controller but failed as I think I do not understand how to properly handle the response, or even grab it, and then use it as a comparison to assert if the item exists.
I get a response from the HTTP request call response that looks a little somthing like this:
{"data":{"getIDs":{"Page": 1,"PageSize": 25,"PageCount": 1,"isFirstPage": true,"batches":[{"id":"b601a257-13fe-4de3-b779-a5922e89765a"},{"id":"b601a257-13fe-4de3-b779-a5922e89765b"},{"id":"b601a257-13fe-4de3-b779-a5922e89765c"}]}}
I need to recall the endpoint until I have found the ID I am looking for or cancel after 10 attempts
So after a bit of fumbling around I, I figured on my own answer that seems to work well. But I would suggest looking at other sources before taking mine as gospel.
The basic structure looks as follows:
Within a thread I set the variables then create the while loop as the next step. Within the While loop I created a counter then added the request I wanted to loop after. To make the loop work for me, I have three items sat under the request.
A Response Assertion: this check for a 200 status as the call should never fail
A Constant Timer: There is a delay between polls of the end point
A JSR223 Assertion: groovy code used ensure the while loop logic is handled
User Defined Variables:
Here i have setup two variables:
DONE: Done is a string value I alter if my JSR223 Assertion finds the values I'm looking for in the HTTP request
MyValue (this is dynamically driven in my actual test, for demo purpose, I’m just declaring a value to look for i.e. 12345)
While Controller:
I still feel i may not understand this correctly, however after some googling I came across the following code that works for me despite some errors in the JMeter console:
${__javaScript(("${DONE}" != "yep" && ${Counter} < 10),)}
This code is saying that the while loop will continue until either of these two conditions are met:
DONE, the variable created earlier, is equal to the value yep
Counter is less than 10 (Counter is declared beneath the while loop)
Counter:
this was a simple configuration step that just worked once I understood it needed to be within the while loop, i configured the following:
Starting value = 1
Increment = 1
Exported Variable Name = Counter
Ticked 'Track Counter independently for each user'
Ticked 'Reset counter on each thread group iteration'
(Exported Variable Name: you can call this whatever you want, I’ve named it counter for the purpose of this demo)
JSR223 Assertion:
This is a simple script assertion that just uses a Boolean and a couple of if statements to assert the state of the test.
import org.apache.commons.lang3.StringUtils;
def done = vars.get("DONE");
String response = prev.getResponseDataAsString(); //retrieves the http request response as text
String MyValue = vars.get("MyValue");
def counter = vars.get("Counter");
//Find Substring within response string and stor result as boolean
String container = response;
String content = MyValue;
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
//Check if the true condition is met and change the value so the loop exits
if (containerContainsContent == true){
log.info("------------------------Got Here");
vars.put("DONE", "yep");
}
//Force test to fail after 10 loops
if (Counter.toString() == "10"){
assert 1 == 2
}

Retrieving certain values from a variable jMeter beanshell script

Currently developing a script in jMeter, I need to retrieve x amount of values from a response then push those values into another HTTP request, here is the tricky part the response is a table which always changes (e.g. rows increase or decrease each time the test is run) so far I've created a Regex extractor which retrieves anything between the table now I need to create a beanshell post processor which retrieves the certain values from the variable retrieved by the Regex extractor and applies them to the HTTP request. I'm not to sure if this is the best way to do this so I am open to suggestions on doing this another way.
You need Beanshell PreProcessor applied to 2nd request, not PostProcessor applied to 1st request
I don't think that using Regular Expressions is a very good idea to parse HTML, I would suggest going for CSS/JQuery Extractor or XPath Extractor instead
Once you have required values in form of
var_1=foo
var_2=bar
var_MatchNr=2
You will be able to add these values to the 2nd HTTP Request like:
import java.util.Iterator;
import java.util.Map;
Iterator iter = vars.getIterator();
int counter = 1;
while (iter.hasNext())
{
Map.Entry e = (Map.Entry)iter.next();
if (e.getValue() != null)
{
if (e.getKey().toString().startsWith("var_") && e.getValue().toString().length() >0)
{
sampler.addArgument("param" + counter, e.getValue().toString());
counter++;
}
}
}

JMeter Regular Expression Extractor I am not getting the value out of a variable from the url

In Jmeter I am trying to get a value out of a variable from the url using the Regular Expression Extractor. I am also using the BeanShell Sampler to get the value out of the variable and print it out to the log file. I can then see in the log file what value I am getting.
I don't think my Regular Expression Extractor setting is correct I am getting the following error from my BeanShell Script:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``String session_ID = vars.get("sessionID"); log.info("session_ID = " + session_I . . . '' Encountered "vars" at line 4, column 1.
An example URL I have is:
http://localhost:8080/test1/gp/gw/ajax/desktop/herotator/record-impressions.html?ie=UTF8&aPTID=16001&cmpnId=205103067&cnttId=1&h=1A52D1&pIdent=desktop&rId=0DA6FXQ35E8JDNVES8C59&sid=14&slotName=PS4-some-testdata
I would like to get the value from the variable PTID and output it to the log file. I can then use the value in other Http requests when i need to.
My BeanShell Sampler script is:
String session_ID = vars.get("sessionID");
log.info("session_ID = " + session_ID)
vars.put("sessionID", session_ID);
My Regular Expression Extractor is:
Field to check = URL is ticked
Reference Name = sessionID
Regular Expression = PTID="(.+?)"
Template = $1$
Match No. (0 for Random): 1
Default value = session id not found
My Test Plan set up is as follows:
Test Plan
--Thread Group
----Http Request Default
----Http Header Manager
----Recording Controller
------Http Request
------Regular Expression Extractor
------BeanShell Sampler
------more Http Requests
----Access Log Sampler
----View Results Tree
Also nothing is being written to the log file when i run the script.
Access Log Sampler the log file location is to:
E:\RL Fusion\projects\JMeter\apache-jmeter-2.13\jmeter.log
In the View Results Tree for the Http Request I can see there is a PTID value in the Response data Tab.
My regular expression extractor is not getting this value out.
I am new to JMeter, If i have anything in the wrong order please do let me know.
Thanks,
Riaz
My expectation is that something is wrong with your Beanshell script. Most likely you're missing a semicolon at the end of statement on 3rd line.
To get to the bottom of a problem in Beanshell script you can use the following approaches:
Add debug(); directive to your Beanshell script (make it first line). It will trigger debug output to console window where you launched JMeter from
Put your Beanshell code into "try" block like:
try {
// your code here
}
catch (Throwable ex) {
log.error("Problem in Beanshell", ex);
throw ex;
}
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter.

how to extract value from request in Jmeter

Hi I am passing an email which is a time function like below
email = ${__time(MMddyy)}_${__time(HMS)}#yopmail.com
The value of this function changes eveytime I call the variable email.
I would like to store this value that is generated from this function into a variable and use that in other requests.
So currently I am getting two different emails in two different http requests since there is some time lag between my two http requests.
what I would like to do is .. store the email that is being sent in first http request by extracting the value from the request and pass it in the second http request.
POST data:
email=062915_160738%40yopmail.com
I know the way to extract from html response.. but is there any way to extract from request in jmeter?
If so can someone pls tell me how to achieve this?
thank you
Add a Beanshell PostProcessor as a child of the request which sends that POST request
Put the following code into the PostProcessor's "Script" area
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
if (arg.getName().equals("email")) {
vars.put("EMAIL", arg.getValue());
break;
}
}
Refer generated value as ${EMAIL} where required.
Clarification:
above code will extract the value of email request parameter (if any) and store it to EMAIL JMeter Variable
ctx - shorthand to JMeterContext class instance
vars = shorthand to JMeterVariables class instance
Arguments and Argument - you can figure that out from JMeterContext JavaDoc
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter.
Instead of the entire email, you can store the timestamp value in a variable and then use this timestamp variable to create email anywhere you want.
This way you will can have same email every where.
Add a Beanshell PostProcessor & Add following script:
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String req_body = arg.getValue();
vars.put("req_Json",req_body);
}
here we get the output in json format:
${req_Json}=
"email":"062915_160738%40yopmail.com",
"name":"abc xyz"
Now using jp#gc Json Path Extractor extract the value of email
Json expression = $['email']
and store the value in email_value_extacted
now use the variable ${email_value_extacted} anywhere you want to use.
finally,
${email_value_extacted} = 062915_160738%40yopmail.com
Is it HTTP Sampler? If so, just put into beanshell postprocessor:
String prevQuery = prev.getQueryString(); //your request text
System.out.println(prevQuery );
Also works for any samplers:
String prevQuery = prev.getSamplerData();
You can use Regular Expression extractor to extract the e-mail address from the request URL.
Add Regular Expression Extractor as a child of sampler which sends the post request.
In the Regular Expression Extractor select URL in Response Filed to check instead of Body.
You should be able to extract e-mail id from the request in this way.

Resources