How to deal with randomly generated post request parameters in Jmeter Scripts? - jmeter

I am writing jmeter scripts for my web-based application. I am using firefox-firebug to watch POST request parameters. I could successfully write login page scripts because it had only "username" and "password" parameters.
But, after logging into the web application, I realized that, there are randomly generated required parameters which are sent along with the post request.
So, I am trying to find out the way to deal with these parameters.
Please let me know, if you have dealt with this situation.
Example: These are my post request parameters:
externalId=971&submit.go=Go&submit.go=&013f57c77c2a%3A6eed%3A1b320be7=105f230e-9f86-40f8-9473-215975812128
Where **013f57c77c2a%3A6eed%3A1b320be7** parameter and it's value are generated differently each time.
I don't know how to define this parameter.

I found an answer. You can use List Extractor(Regular Expression Extractor).
You can define any pattern as per your criteria.
for example regex patter is : input type="hidden" name="([^"]+?)" value="([^"]+?)"
Step2) Use Beanshell pre processor with this script.
log.info("=====================");
count = Integer.valueOf (vars.getObject("hiddenList_matchNr") ) ;
log.info("Number of hidden fields in previous sampler: " + count);
for (i=1; i <= count; i++) {
paramName = vars.getObject("hiddenList_"+ i + "_g1");
paramVal = vars.getObject("hiddenList_"+ i + "_g2");
log.info("Adding request parameter: " + paramName + " = " + paramVal);
sampler.addArgument(paramName, paramVal);
}
log.info("=====================");

Related

how can i write jmeter map test case scenario with input and output result input is csv file out put should also csv file

I need to map my test case with the input data that is present in a csv file and compare it with rest response and generate a responce csv file with that perticular test scenerio in Jmeter.
So I am providing the deviceID as input and validating the json response and writing it into a csv file. for for single occurrence I can get the value as well as I can tag my test case in the response csv file. but when I try with multiple input with multiple test case my response came up returning the last value. like:
Validate  County ETR available with No Ticket April16PM Hurricane Event
lets say my input is:
Test Case Device ID Execution
Validate if Active Event 40122480 Yes
Validate if Valid Device ID 277136436 Yes
Validate  City ETR available with No Ticket 268698851
Validate  County ETR available with No Ticket 18515907
bean shell code is:
scenario = vars.get("ScenarioName");
eventname = vars.get("C_EventName");
eventtype = vars.get("C_EventType");
areaName = vars.get("C_AreaName");
areaType = vars.get("C_AreaType");
f = new FileOutputStream("C:\\RestService\\Result.csv", true); //specify true if you want to overwrite file. Keep blank otherwise.
p = new Print`enter code here`Stream(f);
this.interpreter.setOut(p);
print( scenario + ", " + eventname + ", " + eventtype + ", " + areaName + ", " + areaType);
f.close();
I have increse the number of threads to 4 but the loop count is 1.
can you please help me out. in this JMeter issue
I would not recommend going for Beanshell-based approach as if more than one thread (virtual user) will be writing into the same file the result will be unpredictable and most probably wrong as you are creating the race condition there.
The best option would be adding your variables to .jtl results file directly. To do this:
Add the next line to user.properties file (located in "bin" folder of your JMeter installation
sample_variables=ScenarioName,C_EventName,C_EventType,C_AreaName,C_AreaType
Restart JMeter to pick up the change
Next time you run your JMeter test in command-line non-GUI mode like:
jmeter -n -t test.jmx -l result.jtl
the resulting .jtl file will have 5 extra columns holding the values of the aforementioned variables for each request.
References:
Sample Variables
Configuring JMeter
Results file configuration

How to get print the value of a variable which is extracted by regural expression extractor in JMeter

I am trying to track the value by printing it to the log but getting void as an answer.enter image description here
The easiest way to see the variable names along with values is using Debug Sampler
However if you need to print all the extracted values to JMeter log for some reason you need to slightly change your script to look like:
log.info("Detected " + vars.get("urls_matchNr") + " URLs");
for (int i=1; i<= Integer.parseInt(vars.get("urls_matchNr")); i++) {
log.info("URL # " + i + ": " + vars.get("urls_" + i));
}
vars stands for JMeterVariables class instance so this way you get read/write access to all Jmeter Variables in scope.
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter
There are 2 problems in your script.
1) You are extracting Match No: -1, which is not right (Check your regular expression extractor). You can either chose 0 for random match or any positive number for the respective match.
2) In BeanShell assertion, you are trying to retrieve the value as
logs.info("the" +urls);- which is not the right way to do.
To get the value of a variable in BeanShell we have to use "vars.get" method.
So change your assertion to logs.info("the" +vars.get("urls")); and try once.

How to post the exact number of values which are retrieved from post processor?

I'm landing into a page where some Customers listed out. I'm retriving all the Customer Ids by Regular Expression Extractor Post-Processor.
Now, in a subsequent request I need to pass those Ids. It's being passed as a 'Body Data' by the following format:
[19327,15947,14421,18813,20942]
Let say, there are 5 Customer Ids retrived, then I can use the variables for each record as follows:
Passing Variables: [${CustomerId_1},${CustomerId_2},${CustomerId_3},${CustomerId_5}]
Posting Variable Values: [19327,15947,14421,18813,20942]
But let say, there are only 3 Customer Ids retrived, and if I pass the variables as above then the sampler will fail because currently it just retrived 3 Customer Id records.
Passing Variables: [${CustomerId_1},${CustomerId_2},${CustomerId_3},${CustomerId_5}]
Posting Variable Values: [19327,15947,14421,${CustomerId_4},${CustomerId_5}]
How to deal with this issue, plz. do help.
Thanks in advance
Add Beanshell PreProcessor as a child of your 2nd request
Put the following code into the Pre-Processor's "Script" area
int customers = Integer.parseInt(vars.get("CustomerId_matchNr"));
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.append("[");
for (int i = 1; i <= customers; i++) {
requestBuilder.append(vars.get("CustomerId_" + i));
if (i != customers) {
requestBuilder.append(",");
}
}
requestBuilder.append("]");
sampler.getArguments().getArgument(0).setValue(requestBuilder.toString());
The above code will build required request line depending on number of matches and automatically set request body.
Referenced classes:
vars - shorthand to JMeterVariables
sampler - provides access to the parent sampler, in case of HTTP Request it will be HTTPSamplerProxy
StringBuilder - comes with Java SDK
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on Beanshell scripting, explanation of pre-defined variables and some useful examples.
refName_matchNr will return the number of matches. So in your case CustomerId_matchNr will give you number of customerIDs.
Use a beanshell pre-processor to run a loop and construct the BodyData string and save it to a new variable, use that variable in your subsequent sampler.

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.

How can I search for a text and fill/click on a link with Selenium?

Here's the deal:
Is there a way to search for an input name or type witch is not precise and fill it?
For example, I want to fill any input with the name email with my email, but I maybe have some inputs named email-123, emailemail, emails etc... Is there a way to do something like * email * ?
And how can I click on a link verifying some text that could be on the link, or above the link, or close, or at class etc ?
ps: I'm using selenium ide with firefox
You can use Xpath to find it with something like //input[contains(#name,'email'). If you have multiple instances like that on the page it will be worth moving your test to your favourite programming language and then doing
emailInstances = sel.get_xpath_count("//input[contains(#name,'email')]")
for i in range(int(emailInstances)):
sel.type("//input[contains(#name,'email')]["+ i + 1 +"]","email#address.tld")
Xpath works well and the solution above is good. If you are trying to test old verions of IE you could also use JavaScript injection. I find it is very fast, although can be a bit trickier to debug. I didn't actually check if the below works but hopefully it gives you an idea of what you can do:
String javaScript = "_sl_enterEmailStr = function(parentObj,str) { "+
" var allTags = parentObj.getElementsByTagName('input'); "+
" for (var i = 0; i < allTags.length; ++i) { "+
" var tag = allTags[i]; "+
" if (tag.name && tag.type && tag.type === 'text' "+
" && tag.name.match(/email/)) { "+
" tag.value = str; "+
" } "+
" } "+
"}; "+
"_sl_enterEmailStr(this.browserbot.getCurrentWindow().document "+
" ,'myemail#mydomain.org'); ";
mySelenium.getEval(javaScript);
I find JavaScript injection with regular expressions allows me to do great things to dynamic input fields. Note you can use findElement() to be more specific about where you look for tags.
Regarding clicking a link and getting text, those are simple click() and getText() operations that can be done given the proper locator. I would check out the selenium API. for example, here is the link to the Java one for 1.0b2.

Resources