Compare extracted variable across threads in JMeter - jmeter

My goal is to POST to some URL from every thread in my thread group, which will create an asset somewhere. If all goes right, the first request will create the asset, then subsequent requests will see that the asset is already created (or in the process of being created), and will reuse that same asset.
The test plan:
Create N threads
HTTP Request - POST to some URL
Regular Expression Extractor - extract part of the response (the assetId generated by the POST request)
Verify that every thread extracted the same string from the response
My question:
What I don't have a clue how to do is the last step - verify that the value extracted from each thread is the same. How can this be done in JMeter?

To achieve your requirement, we need to share the value among all the threads.
Properties:
We can use properties to share a value. Lets assume a prop 'shared' is created with default value as blank "". Add the below code in the beanshell assertion. If it is blank, then a thread will add the value extracted from the RegEx. All other threads will just compare the value and if it does not match, it will fail it.
if(props.get("shared")==""){
props.put("shared") = "extracted";
}else{
if(!props.get("shared").equals("extracted")){
Failure = true;
}
}
Bsh.shared:
We can use the bsh.shared shared namespace to share the value among the threads and compare if the all the threads have the same value.
1.setup threadgroup will contain beanshell code like this to create a hashset.
import java.util.*;
if (bsh.shared.hashSet == void){
bsh.shared.hashSet=new HashSet();
}
bsh.shared.hashSet.clear();
2.The regular thread group will contain the code for extracting the value. Once the value is extracted, add it to the hashset which stores only the unique values. Any duplicate values are simply ignored.
bsh.shared.hashSet.add("value extracted");
3.teardown threadgroup will group will check the hashset for the size. If the size is more than 1, then it failed.
log.info(String.valueOf(bsh.shared.hashSet.size()));

I guess you can use Response Assertion.
The test plan:
Create N threads
HTTP Request - POST to some URL
Verify that every request has the same string in the response with Response Assertion
When you place this assertion on the Test plan level it applies to all the threads.

Related

How to capture dynamics values which will be generated from loop in JMeter

I have one scenario to test in which one transaction needs to be iterated for several times and then submit the request. For each iteration, I will get one detID (e.g: for 20 iterations - 20 unique detID). The problem is while submitting the request all the detID are been passing in the request parameters (example: if loop ran for 10 iterations then 10 detID are passing inside the request). I have put regular expression extractor to the transaction which is in loop which will capture all the mathces but it is capturing only the last one. (e.g: if loop ran for 10 iteration, regex capturing the 10th iteration value).
Please help me.I want to include these detID inside the submit request.
Add a Counter before the request with the regex.
Add a BeanShell PostProcessor as a child of the request after the regex with the below code:
String ID = vars.get("ID");// ID is the reference name of your regex
String Counter = vars.get("Counter");// Counter is the reference name of your regex
vars.put("ID_"+ Counter, ID);
You will have 20 different variables each one holds a different ID value and you can use them as ${ID_1} for the first ID and ${ID_2} for the second and so on.

Manipulating the request body of HTTP thread based on the data extracted from the previous HTTP response

I want to manipulate the request body of HTTP thread based on the data extracted (using 'Regular Expression Extractor') from the previous HTTP response.
Here is the scenario:-
I have extracted the statusFlag and statusId from 'HTTP request 1' as:
Ref name: status
Reg. Exp: "statusFlag":"(\w+)","statusId":"(\w+)"
So, first I want to check that the value of statusFlag is 'New' or not.
If it is New then I have to proceed and feed statusId in next HTTP request or else display statusFlag mismatch.
Need help. Got stuck badly.
I believe Response Assertion is what you're looking for. Add it after the Regular Expression Extractor and configure it as follows:
Apply to: JMeter Variable -> statusFlag (or your reference name)
Pattern Matching Rules: Equals
Add New as a "Pattern to Test"
The assertion will check whether "statusFlag" is "New" and if not - it will fail the sampler and report the expected and the actual value.
Optionally you can add If Controller after the Response Assertion, use ${JMeterThread.last_sample_ok} as a condition and place 2nd request as a child of the If Controller - it will be executed only if "statusFlag" is new.
See How to Use JMeter Assertions in Three Easy Steps guide for more information on conditionally setting pass or fail criteria to requests in your JMeter test.
That's how your Jmeter project should look like.
Regular Expression Extractor stores extracted value in ct variable that can be accessed in If Controller as "${ct}" == "yourvalue" and, if true, can be also sent as a part of Request 2 body using the same ${ct} reference.
Jmeter project structure

How to Handle Dynamic Requests in JMeter - Which may/may not occur with each run

In Web Application :
There is Single Page having Different Sections/Partitions
Each section Retrieves the Data with the Help of Filter Query.
If there is no matching Result, Section will Send below Request only :
Request 1: domain/search/jobs/csuser__search2_1413357426.1559
If the Query returns any matching Result, Section will Send below Two Requests:
Request 1: domain/search/jobs/csuser__search2_1413357426.1559
Request 2: domain/search/jobs/csuser__search2_1413357426.1559/results_preview
How can I manage Request 2, which may or may not occur with each run.
Currently I am manually Recording entire Network calls, Removing unnecessary ones & running it for 'N' Loop Count. How can I make sure while test is runing if any section has matching results Request 2 Should also be taken care which I might not have benn recorded on my first execution.
You can use combination of Beanshell PostProcessor and If Controller to work it around as follows:
Add a Beanshell PostProcessor as a child of the Query request
Put the following code into the PostProcessor's "Script" area:
int length = prev.getSubResults().length;
if (length > 1) {
String path = prev.getSubResults()[length - 1].getURL().getPath();
if (path.contains("results_preview")) {
vars.put("resultPresent", "true");
}
} else {
vars.put("resultPresent", "false");
}
Add an If Controller after the request
Depending on your scenario put on of the following conditions to If Controller's "Condition" input
${resultPresent}==true - children will be executed if the query returns results
${resultPresent}==false - children will be executed if the query doesn't return anything matching
Beanshell code does the following:
check how many requests were executed
if there were more than 1 requests, path of the last request is extracted
if path contains "results_preview" variable resultPresent is being set with the value of "true"
if there was only 1 request then resultPresent variable is false
References:
How to use BeanShell: JMeter's favorite built-in component
JMeter “if controller” with parameters
SampleResult class JavaDoc
As Dimitri said. The processor should run after (post) request 1. The if controller will then act on the results of the processor. Section two is only run when the condition is not "false".

JMeter: how to vary request inside Thread Group

I have to write load tests for web application using JMeter. The application has items available for booking, each item has a 'Book' button. If some user clicks this button for item, it becomes unavailable for other users. My question is:
Is it possible to make JMeter threads to book different items (to make different requests) and how to implement it?
You should be able to determine what parameter is being posted by different "Book" buttons and modify nested requests as needed. Test plan structure should be something like:
Open Booking Page - HTTP Request
Get all Booking IDs - Post Processor
Book - HTTP Request
Where "Post Processor" can be
Regular Expression Extractor
CSS/JQuery Extractor
XPath Extractor
In case of multiple matches Post Processor will return multiple variables like
BookindID_1=some value
BookindID_2=some other value
BookindID_3=some other value 2
....
BookindID_matchNr=10
There are at least 2 options on how to proceed with these values:
Iterate all the values using ForEach Controller
Stick to current virtual thread number via __threadNum function so thread #1 will take BookindID_1 variable, thread #2 - BookingID_2 variable value, etc.
It is also possible to take random value using __Random function but it may result in request failure if item is not available.
The correct way of 2 variables combination looks like:
${__V(VAR1${VAR2})}
So combining BookingID_N and __threadNum will look like
${__V(BookingID_${__threadNum})}
See How to use JMeter Functions post series for more on what can be done via functions.
yes, If every item has static(predefined) unique id,descriptor,identifier then that can be parameterized using a csv config file or random no. generator and selector
Random no generator and selector will work only for integers but csv config is better/standard practice. If you need more help please paste your test plan here with explaination of your need.

Variables in httprequest post body

I'm trying to generate a jmeter script where a unique folder is created each time the script is run - adding a variable of some sort to the folder name, such as a username+timestamp, should be enough to guarantee uniqueness. However, jmeter is not resolving the variable to its value - although it is when the variable is read out of a csv file (which isn't suitable).
Basically, I'm editing the PostBody in the http request, as follows:
{"alf_destination":"workspace://SpacesStore/90368635-78a1-4dc5-be9e-33458f09c3f6","prop_cm_name":"Test
Folder - ${variable}","prop_cm_title":"Test
Folder","prop_cm_description":"Test Folder"}
where variable is basically any variable I've tried so far (such as a random string, timestamp, etc.)
Can anyone suggest how to get the variable resolved?
You can use jmeter (since 2.9 version) uuid feature -> http://jmeter.apache.org/usermanual/functions.html#__UUID
${__UUID}
and
1) If you want just 1 value for the whole test, add a "User Defined
Variables" Config Element to your test. This will be evaluated when
you load the test script the first time.
2) If you want to have the value change for every thread execution,
but stay the same during each thread instance: under your 'Thread
Group', add a 'Pre Processors -> User Parameters' to your thread group
- and add the variable there.
Also, if you want the value to change each time the thread starts over
(each 'iteration' of the script within the thread group), you can
check the "Update Once Per Iteration" box on the User Parameters - and
it will get a new value each time it starts the thread over at the
beginning of th test script (within that thread group).
http://mail-archives.apache.org/mod_mbox/jmeter-user/201208.mbox/%3C004301cd853e$0c4a60c0$24df2240$#gmail.com%3E
With JMeter 2.9, the following works:
In HTTP Request Sampler, Tab "Post Body" add for example your JSON data and include the variables in it:
{"uuid":"${new-uuid}"}
new-uuid is a user defined variable.
This will send (from View Results Tree, Tab "Request"/"Raw"):
POST data:
{"uuid":"a1b2c3d4e5f6"}
I did this by referencing a variable in the http request post body - ${formvalues} - created using a beanshell preprocessor which is appended to the http request sampler. Beanshell contents:
double random = Math.random();
String formvalues ="{\"alf_destination\":\"workspace://SpacesStore/90368635-78a1-4dc5-be9e-33458f09c3f6\",\"prop_cm_name\":\"Test Folder - ${uname}_" + random + "\",\"prop_cm_title\":\"Test Folder\",\"prop_cm_description\":\"Test Folder\"}";
vars.put("formvalues",formvalues);
So this creates a folder with the username (${uname}, taken from the csv) plus a random number - it's crude as there could potentially still be cases where the script tries to create a folder with the same name as an existing one, but it will work for my case.
suppose you have the value "NewYork" in jmeter variable "Location".
Use it like this in HTTP POST BODY DATA:
{location:"${Location}"} => which gets interpreted as {location:"NewYork"}

Resources