How to validate JMeter user defined variables? - jmeter

I'm new to JMeter, I want to validate a JMeter test input variables defined as part of "User Defined Parameters". Let's say I have a variable "sessions" and my tester should pass input values in between 0 to 30 for sessions, if tester passes other than this range the test should not go further and should throw an error with appropriate message.
Is it possible with any kind of JMeter controllers/assertions/... without writing code for validation?

I am not sure is there any efficient/direct way of doing this. but I achieved your requirement as follows:
Add Setup Thread Group (before any other ThreadGroup). select radio button Stop Test Now in Action to be taken after a Sample error
Add Debug Sampler to the Setup Thread Group.
Add Response Assertion (RA) to the Debug Sampler.
In RA, Select JMeter Variable in Apply to section.
In RA, select Matches in Pattern Matching Rules section.
In RA, add the regex ^[0-9]$|^0[1-9]$|^1[0-9]$|^2[0-9]$|^30$ in Pattern to test text area.
Test will be stopped if you provide sessions value other than 0-30 in User Defined Variables, as Setup Thread Group is configured to Stop Test Now on Sample error.
Note1: Added View Results Tree Listener for confirmation whether the test is continued and also to check the error message. View Results Tree is added only for visual confirmation, must be removed during the load test, does not effect the actual logic.
Note2: I am not aware of any component, which can show custom message/alert to the user. so, used View Results Tree. We should remove this command during load testing. I added here for visual confirmation purpose. If not present also, Test will be stopped on wrong value for sessions, i.e., other than 0-30
Note3: We need a Sampler component in order to apply an Assertion. so, added Debug Sampler. Debug Sampler just reports all the JMeter variable values at the point of its execution.
Image references:
Setup Thread Group:
Response Assertion:
View Results Tree:

You cannot achieve such validation in GUI without amending JMeter source code but you can check the variable range using scripting.
For example, add a JSR223 Sampler as a child of the first request and put the following code into "Script" area:
import org.apache.commons.lang3.Range;
int sessions = Integer.parseInt(vars.get("sessions"));
String errorMessage = "Provided sessions number is not between 1 and 30, stopping test";
if (!Range.between(1, 30).contains(sessions)) {
log.info(errorMessage);
SampleResult.setSuccessful(false);
SampleResult.setResponseMessage(errorMessage);
SampleResult.setStopTest(true);
}
Demo:
Make sure you are using Groovy as a language (the option should be default as per JMeter 3.1, if you are using earlier JMeter version for some reason - you will have to choose groovy from the "Language" dropdown)

Related

Sampler name will be empty/blank in the second loop in "View Result Tree"

When I execute the script with Loop count = 2
The sampler's names in the first loop will be displayed correctly in the "View Result Tree".
But the names for the same sampler's in the second loop will be empty/blank in the "View Result Tree", please check the screenshot below.
Your question doesn't provide sufficient level of details in order to be troubleshooted/reproduced.
If you're generating your sampler labels dynamically using JMeter Functions or Variables (like I did in the above demo) - double check their values at every step using Debug Sampler and View Results Tree listener combination, it might be the case they're getting overwritten/emptied somewhere somehow
Inspect jmeter.log file for any suspicious entries, if something goes wrong most probably you will be able to figure out the root cause or get the idea from there
I faced with same issue. The cause of the error is when the name is changed in HTTP Header Manager plugins, sampler names start to come undefined. This is a bug of JMeter.
The solution is very simple. If the default value:
HTTP Header Manager
is assigned to all HTTP Header Manager plugins in Jmx, it will be resolved.

field name is getting changed in response data

Field name is getting changed after executing the script.
A. After executing the script,the field name is not getting displayed in response data but the parameters are displayed with slight changes.
In sampler below details are getting displayed.
Name : aura.token
Parameters : HCQAHBgEMTAwMBQCGAcxMDAwMjA5GAcxMDAwMjA5ABQCGfMQscHV8XF654tDbfY0XD3yRxaSwbvRh1oAGfMgzIG_YaBrAZdWB-IAMP_0iAQiYMHheBA3BA0SoXzWh4kA
but after execution of a script below details are getting displayed in response data.
*/{"event":{"descriptor":"markup://aura:invalidSession","attributes":{"values":{"newToken":"HCQAHBgEMTAwMBQCGAcxMDAwMjA5GAcxMDAwMjA5ABQCGfMQkaKR6n5r5QqE7gz5Qk1l1Rb67KOtiFoAGfMgtKaMHHWJZiXEOt8pU6zs1edK_Q4dQo5VL2ea8y2qi3gA"}}},"exceptionEvent":true}/*ERROR*/
It's name is "newToken". So why do you think this should not be changed?
Most probably you need to perform correlation of this field, to wit you will not be able just to record and replay the script as this "token" is being generated dynamically and has new value each time you access the application.
The main idea of the correlation is
Identifying dynamic elements. The easiest way is to record your test scenario one more time using HTTP(S) Test Script Recorder and compare the recorded scripts. All parameters which are different needs to be handled properly.
Wherever you detect a dynamic parameter look into previous sampler response data (body, headers, Cookies, URL) - the value should be there
Apply a relevant Post-Processor to the previous sampler in order to extract the dynamic value and store it into a JMeter Variable
Replace recorded value with the JMeter Variable from the previous step
You should be good to go now.

Automate sending a request and saving the response

There is a URL which I want to hit and save the response. The URL id needs to be incremented each time and save the response. For example -
First Get Request - http://google.com/getdata/?Id=1
First Response - one
Second Request - http://google.com/getdata/?Id=2
Second Response - two
and so on...
I want to hit the request with increment the id each time and save the response
I have tried using fiddler but unable to figure how to increment the id and save the response.
P.S. - I have to make around 6,00,000 hits
Since the 'Postman' tag is mentioned, I can help you regarding how to implement this in Postman.
Postman has a nice feature of using 'variables'.
You can use environment variables or globals.
Read more about these on their docs:
https://www.getpostman.com/docs/v6/postman/environments_and_globals/variables
You can use a global variable such as 'counter' and set it to 1 / whatever starting point you want.
Then you can modify your request like so :
http://google.com/getdata/?Id={{iteration}}
Now, in the Tests script of the request you can write the following script
let i = parseInt(pm.globals.get('iteration')) + 1;
pm.globals.set('iteration', i);
Also, to access the response you can use the following command in Test script:
console.log(pm.response); // Use pm.response as per your needs
Save the request in a collection.
Now load the Postman's Runner and select the collection.
Now you can put an iteration count of 6,00,000 and hit run!
Remember, heavy iterations will cause performance degradation.
In JMeter you need to click , Ctrl+0 and Ctrl+1 to create , Thread Group and HTTP Request
In Thread Group put the number of hits you need in Number of Threads (users)
In HTTP Request Put in Server Name or IP www.google.com and in Path /getdata/?Id=${__threadNum}
__threadNum will create increasing number from thread 1 to number of hits.
For small number of hits or debugging you can add View Results Tree to view request/response by clicking Ctrl+9 in Test Plan/Thread Group level.
To save the response use Post Processor, especially by adding Regular Expression Extractor below HTTP Request by clicking Ctrl+2.
Allows the user to extract values from a server response using a Perl-type regular expression. As a post-processor, this element will execute after each Sample request in its scope, applying the regular expression, extracting the requested values, generate the template string, and store the result into the given variable name.
Import to notice that for load testing you need to work with non GUI mode, which means call jmeter using command line as jmeter -n -t myTest.jmx
you will use Command-line mode (called Non-GUI mode) to run it for the Load Test.
Don't run load test using GUI mode !
For saving all responses to a one file see save response data or if you want to save file per thread/user you can add Save Responses to a file
Fiddler:
Open script editor (Control + r ) then add the following code inside OnBeforeResponse
static function OnBeforeResponse(oSession: Session) {
if(oSession.oRequest["X-SAVE-ME"] != "")
{
oSession.SaveResponseBody("C:\\tempfiddler\\" + oSession.SuggestedFilename);
}
}
Go to the "Composer" tab and include the header X-SAVE-ME with any value, in the URL, replace your ID with # (just like this: http://google.com/getdata/?Id=#) fiddler will now ask for the starting and ending value of ID before executing;
Please find the snapshot below for your scenario.
Scenario_Testplan
First, go to user properties and put "sample_variables = ID, Response_File_Name" or whatever the name you choose for the variables. Restart jmeter.
Create the below plan:-
CSV data set config to have incremental values and response file name
HTTP request will use ${ID}
Save response to a file will use ${Response_File_Name}
Hope this will help.
I would do this by command line, using a while loop with a curl to the URL, storing the body result on the standard output to a file. It would look something like this:
for i in {1..600000}; do curl "http://google.com/getdata/?id=$i" > body-result-id-$i; done
I couldn't test the line above because I don't have any access to a console right now, but I think it should work.
In Burp you can do this using the Intruder tool. First, capture a sample request in Burp. If you're unsure how to do this, please consult the getting started documentation.
Then right-click the request and selected "Send to Intruder".
In the Positions tab within Intruder, first click "Clear" then select the section you want to vary, and click "Add"
In the Payloads tab select the Payload type as "Numbers" and configure the range.
Click "Start attack"
For more information, consult the documentation.
One Another solution is that you can use Counter in jmeter. That you can find from below path
Thread Group > configElement > Counter.
Configure the Counter as per your need.
Give the Reference Name i for counter.
Use the variable in your request
For more information.

jmeter how to replay recorded unique id from application

I am very new to Jmeter and trying to use it for doing load testing my application.
In my application, every time we click on a template, application will allocate a unique id which to the template...when I recorded the steps using jmeter, a particular unique id was recorded...but when I tried to play the recorded case...it is looking for the same unique id....how do I tell jmeter to get the new id from the application?
Here are the steps
Login as a user,
click on a particular link,
click on a button which will then popup a window asking to select a template,
After selecting a template, my application will create a unique id for that template
It very much depends on whether that template ID is created on the client (i.e. by JavaScript), or on the server (i.e. you can actually record a template ID returned by the server).
If second is your case, then server returns template ID in the response to template selection, so you can use one of the post-processors - a supporting element invoked after the parent request; it usually extracts data from the response and saves it as a variable(s). In your case you'd extract template ID and save it as variable. Later samplers can use the variable in format ${your_name} instead of the recorded hard-coded string. So in that case your plan could look like this:
Which post-processor to use and how to use it depends on the response you are receiving form the server, so cannot be more specific here.
If the first option is your case (JavaScript on the client generates template ID; and your recording only contains usage of said ID), then you can simulate what JavaScript is doing by generating a similar ID using one of the JMeter script-related features: it could be random function, an inline piece of JavaScript code, a scriptable sampler, such as JSR223 Sampler, or... There are many options really, depending on concrete needs of that generated template ID. Again, a more specific question would help to narrow down your choices.
Classic "correlation" example.
Look for that generated ID in the previous responses (you can do it with the View Results Tree listener)
Once you detect it you need to extract it and convert into a JMeter Variable with a PostProcessor (the most commonly used is Regular Expression Extractor, however depending on the nature of your request you may consider to use others
Once you get the ID extracted and stored in the variable - substitute hard-coded value obtained via recording with the JMeter Variable
Repeat steps 1-3 for any other dynamic parameters or values. Or, consider a faster way of creating a JMeter test via alternative recording solution which performs the above steps automatically so you won't have to worry about detecting and handling dynamic elements. See How to Cut Your JMeter Scripting Time by 80% article for details.
You need to check response of the previous request. Normally ID will be created and can be found in the response of previous request and you can use that ID for next request.
You need to first find in which response the ID is being generated and the format of the ID. You can use firebug to see the response in HTML format and find where the id is.
Once you have the format of the id, create regular expression around it. Test it using regex tester that comes with JMeter. Or you can use rubular.com to check the correctness of your regex.
Once you have correct regex, use regular expression postprocessor on the request which returns the id and then use that variable in actual request that uses unique id.

Jmeter If controller condition statement

I am trying to built a test plan in jmeter where i want to run test for specific HTTP request based on their names. I used if controller but I dont know what condition to write.
I am writing ${__samplerName()}=="HTTPRequestName" in the condition but it isn't executing.
kindly help me as soon as possible.
You need to surround ${__samplerName()} with quotation marks as follows:
"${__samplerName()}"=="HTTPRequestName"
See How to use JMeter's 'IF' Controller and get Pie. guide for more details on If Controller use cases and clauses.
In case if you need to run samplers basing on some condition, you can use JMeter Properties as follows:
Launch JMeter providing sampler name property like jmeter -Jrunsomesampler=true
Add If Controller with the following condition: ${__P(runsomesampler,)} == true
Add desired HTTP Requests as a children of the IF Controller

Resources