JMeter - Pause the request if it gives an error - jmeter

I'm using Apache JMeter to send thousands of HTTP requests with 3 seconds of delay in between. The response body is json and starts with {"errors":[ ], ...}. If there is an error it will be in the [ ]. If there is no error than [ ] will be empty.
I want JMeter to pause for a short period of time if it receives an error, and try the request again. So that it'll add in additional buffer when needed.
Do I need a script for this? How can I achieve this?

You can get the number of errors by adding a JSON JMESPath Extractor as a child of the Sampler which returns the JSON and configuring it like:
It will extract the number of entries in errors JSON Array and store it into errors JMeter Variable
Then you can use If Controller to check if the number of errors is above zero, it can be done using __jexl3() function like:
${__jexl3(${errors} > 0,)}
and finally you can introduce a delay using Flow Control Action sampler:

Solution 1
Add a JSR223 Post Processor to the Test Plan level, Thread Group or to a sampler based on your requirement.
Add following code into the script area to check the error and introduce a delay after error if any.
int delayOnErrorInMillis = 5000
if (prev.getResponseDataAsString().startsWith('{"errors":')){
log.info("ERROR !")
sleep(delayOnErrorInMillis)
}

Related

JMETER - How can I pass 2 condition in a while loop on Jmeter

How can I pass 2 condition in a while loop on Jmeter. The conditions are
The request should run in loop till "Pass" response comes.
While loop should run only for 1 minute.
Condition 1 is working fine. However condition 2 is unable to implement.
I have tried running the While Loop inside a Runtime Controller. But the issue is, if the response "Pass" comes before 1 min, the rest of the test stops.
Tried other way round (Runtime inside While Loop) leading to numerous execution of the request, even after receiving "Pass" response.
Will appreciate any leads on this. Thanks
Add a JSR223 Sampler just before the While Controller and store the current time into a JMeter Variable using the following code:
SampleResult.setIgnore()
vars.putObject('whileLoopStart', System.currentTimeMillis())
Use the following __groovy() function as the While Controller's condition:
${__groovy(!vars.get('your_variable').equals('Pass') && ((System.currentTimeMillis() - vars.getObject('whileLoopStart')) < 60000),)}
This way the While Controller will run until:
either your_variable is not equal to Pass
or 60 seconds pass
whatever comes the first
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
This could be another solution.
You can achieve the desired outcome with the following components.
Runtime Controller
If Controller
Flow Control Action
Set the Runtime (duration) in the Runtime Controller
Set the first condition you already have in While Controller in the If Controller
Click the Break Current Loop to exist from the Run Time controller

How to pass response body values from one thread to different threads by incrementing the values in the response body in JMETER

I just wanted to extract value from the response body of thread1(1st thread am running once by passing number of threads and loop count 1 each) and need to pass same for the 2nd thread(2nd thread am running multiple times by passing number of threads 10).
This is my response body from Thread1.
{"availablePhoneNumbers":["3052191421","3052192726","3052192566","3052195123","3052194493","3052199654","3052194684","3052199164","3052190020","3052190352"]}
i just wanted to pick the first data 3052191421 and wanted to run in thread2 for all the HTTP requests.
then 2nd data 3052192726
then 3rd data and so on.
Could you please get the solution for this?
Thanks in advance..
Extract first number from the response. This can be done using JSON Extractor configured like:
Names of created variables: number
JSON Path Expressions: $.availablePhoneNumbers[0]
Later on you will be able to use __longSum() function in order to:
add 1 to ${number} variable
return the value
save the result back into the ${number} variable
Demo:

Jmeter how to simulate a failure based on results of a condition fro Post Processor

I have a situation where I check the response data and if there is a specific variable exist then I like to simulate a test failure even though that HTTP req code was 200. For example in Bean Post Processor I have:
if ( (prev.getResponseDataAsString().indexOf(Z2) >= 0) || (matches > 1) ){
System.out.println(ctx.getCurrentSampler().getName() +" --> Failed ....")
}
I know how to do it when I want to set the result to success (prev.setResponseOK();) how do I do it if I want to set it to fail? so the GUI shows red and not green?
Thank you
See in JSR223 Sampler
Unlike the BeanShell Sampler, the JSR223 Sampler does not set the ResponseCode, ResponseMessage and sample status via script variables. Currently the only way to changes these is via the SampleResult methods:
SampleResult.setSuccessful(true/false)
prev is a SampleResult object so you can mark it as failed:
prev.setSuccessful(false)
prev - (SampleResult) - gives access to the previous SampleResult
Sounds like a use case for a Response Assertion which you can use in order to conditionally set pass/fail criteria for a Sample basing on presence/absence of certain patterns in the response data.
Here is an example of failed HTTP Request sampler with 200 status code due to absence of the anticipated data in the response:
See How to Use JMeter Assertions in Three Easy Steps for more details.
With regards to JMeter Best Practices which you're violating by the way by using Beanshell PostProcessor:
You should be using built-in JMeter test elements where possible
If you have to go for scripting make sure to choose the most performing option which is unfortunately not Beanshell

Running JMeter in Command mode is not creating any log for anything under while loop in .jmx file

I have a .jmx file with two thread groups. The first thread group is for data comparison (DB Vs API) and has a JDBC request where I plugin my SQL script and saves it to a tab delimited file. Then I have a while loop under which I have an HTTP request.
Second thread group for negative scenarios validation.
Below is the structure of the .jmx file
-- Thread Group Name - FX-Rates
-- JDBC Request Name - FX-SQL
-- While loop
-- HTTP Request - FX Rates - API
-- Thread Group Name - Negative Testing
-- Error Codes
I am running JMeter in Non GUI mode using below command.
jmeter -n -t "F:\MY DOCUMENTS\PSM\PSM_Automation\bin\Non_GUI_FX_Rates_Validation.jmx" -l "F:\MY DOCUMENTS\PSM\PSM_Automation\log\Non_GUI_FX_Rates_Validation.jtl"
I see that it is creating log for each individual sampler i.e; SQL and negative scenarios but not for anything under while loop. Below is the log that it created.
Logfile:
timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect
1492185939615,12140,FX - SQL,200,OK,FX Rates 1-1,text,true,,18549,0,1,1,12017,0,1566
1492185951933,0,Error 400: Invalid Date Format,Non HTTP response code: java.net.URISyntaxException,Non HTTP response message: Illegal character in query at index 80: https://sys-fxrt-v0.apps.system.pcf.ntrs.com/foreign-exchange-rates?as-of-date=${D_EXCH_RT_EFF},Negative Testing - Error Codes 2-1,text,false,,1105,0,1,1,0,0,0
1492185951935,190,Error 404: No Account,404,Not Found,Negative Testing - Error Codes 2-1,text,true,,354,232,1,1,189,0,170
1492185952127,20,Error 404: Incorrect URL,404,Not Found,Negative Testing - Error Codes 2-1,text,false,,354,241,1,1,19,0,12
1492185952147,19,Error 204: No Data ,404,Not Found,Negative Testing - Error Codes 2-1,text,true,,354,260,1,1,19,0,12
Obviously, the kind of sampler result is there:
Error 400: Invalid Date Format,Non HTTP response code: java.net.URISyntaxException,Non HTTP response message: Illegal
character in query at index 80:
https://sys-fxrt-v0.apps.system.pcf.ntrs.com/foreign-exchange-rates?as-of-date=${D_EXCH_RT_EFF}
Obviously that is because the D_EXCH_RT_EFF is not set/resolved in your URL.
That's the problem you're gonna debug.
Obviously.
If you're already doing that (debugging), and run into a problem during it - then describe it please.
And show two things: how you set (initialize) the variable; how you use it, means, literally, show your HTTP sampler (yes, screenshot, at least).
The reasons of not entering the "While Loop" can be in:
While condition is returning false
While condition is wrong
If your While Condition depends on a variable coming from JDBC Request Name - FX-SQL sampler - double check this variable value using Debug Sampler and View Results Tree listener combination.
General "good practice" is running your test with 1-2 virtual users in GUI mode and inspect requests and responses details in the View Results Tree listener. Also pay attention to any suspicious entries in jmeter.log file. Don't run your JMeter test with the full load until you are totally sure that it is doing what it is supposed to be doing. See How to Debug your Apache JMeter Script article for more information on JMeter tests troubleshooting techniques.

Beanshell script launched once (start and end of test plan) in JMeter

Good afternoon !
I will try to explain you clearly my problem.
The context
I have a JMeter TestPlan which send HTTP requests to a server. I have a Beanshell script to assert each different case of error returned.
302 response code -> OK
200 response code -> ?
In each error 200, I check the response data string to see if it is an error or a correct case. (User error like User don't have correct rights is OK, but Server is unavailable is ERROR and both have 200 as response code.)
Here is my test plan :
The goal
As I have several errors returned by only one assertion script, I am not able to differenciate each error, except by uncollaspe the assertion in a ViewResultTree. But I disable it when launching my test, and I will launch my TestPlan remotely.
I had the idea to manually count each error. All my samples goes in my Assertion script, and goes to the correct if block according to their content. I increment some variables (JMeter.properties in fact) in each block.
int test = Integer.parseInt(props.getProperty("302"));
test++;
props.setProperty("302", ""+test);
I want to display all those variables in a JFrame at the end of my testplan like this :
The problem
My problem is that I don't know how to launch a Beanshell script before and after the TestPlan.
I want a first script to be started before any sample is send, just to initialize all my properties variables to 0 (else, they keep the value of the last TestPlan).
And, I want a second one to display my Frame with all the variables after the test plan is finished. (Currently it is a JFrame but it will not stay like this.)
Tested solutions
1) For my first script, I set a Counter (JMeter > Config Element > Counter) in the beginning of my test plan to 0.
I use it to check if my test already started of not with an If Controller :
I have a Pre-Processor Beanshell with props.set("302","0"); where "302" is my property to count all 302 response code.
It correctly works but I want to know if there is a proper way to do this.
2) Then, for my second script, I tried to use ${JMeterThread.last_sample_ok} in an If Controller aswell but it doesn't work like I expected. If I put it after my sample, it start after all OK assertion, and if I put it at the end of the test plan, it is never called.
How can I run my beanshell script once, after all my threads are stopped (i.e. all sample finished) ?
Thank you in advance, I hope you understood everything !
JMeter SetUp thread group and TearDown thread group are meant for exactly this.
Add your beanshell component to the setUp thread group to do some setup activities before your actual test starts. Similarly the tearDown thread group runs after your test execution is complete.

Resources