Rerun getToken(authorization) requests only on expiry - Jmeter - jmeter

My testplan is as follows:
get token: requests to get access token
Setting a user defined variable to get the tokenGeneratedTime, let's say tokenGeneratedTime to ${__time(,)}
Check if token is expired(if controller) - {__jexl3((${__time(,)} - ${tokenGenerationTime}) > 3599000)}
if true, goes to get token sampler
if false, goes to subsequent requests
Some https requests
So if I run this test plan for the first time(only 1 iteration), request to get token is fired, the condition would be evaluated as false and the subsequent requests are fired. All is well and good. But as you can see, if I run the test plan again immediately(not iterating) for the second time, the get token(authorization) requests are fired again, which is not needed. I need to call the get token requests, only on expiry.
I'm thinking of setting a variable to false, if the token is not expired and putting the get token requests under an if controller. But how do I set a variable in if controller?
If you have any other ways of achieving this, please do suggest.
TIA

Use a flag to check the token expiry. e.g. isTokenExpired
Define the variable in the User Defiled Variables section and set the value to true. This will ensure token request is fired for the first time.
Add an IF Controller to the token request and check the condition ${tokenExpired}. Set the flag to false when a token is created successfully. vars.put("tokenExpired","false")
Add a JSR223 Postprocessor to the top level and check the response code 401 for the token expiry response. If the token is expired, set the flag isTokenExpired to true and redirect the thread to the next iteration immediately ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_THREAD .
String responseCode=prev.getResponseCode()
if (responseCode.equals("401")) {
log.info("Token is expired ")
vars.put("tokenExpired","true")
ctx.setTestLogicalAction(org.apache.jmeter.threads.JMeterContext.TestLogicalAction.START_NEXT_ITERATION_OF_THREAD )
}

if I run the test plan again immediately(not iterating)
If you run the test plan 2nd time it means that your tokenGenerationTime variable gets a new value of the current timestamp equal to the start time of 2nd execution.
If you want to be able to run your test plan 2nd time within 1 hour without firing the token generation request you can consider writing the tokenGenerationTime into a file using i.e. __StringToFile() function and read it from the file on 2nd and other test executions using __FileToString() function or if your logic is more complex you can go for __groovy() function and implement whatever you want there
More information on JMeter Functions concept: Apache JMeter Functions - An Introduction

Related

Validate token without login multiple times

In my script I am performing two steps,
Step 1: Login to the application
Step 2: Validate the coupon code from the CSV file.
Problem Statement: When I enter the coupon code on the URL it return me the following value, I want if the coupon code return me invalid then it should validate the next coupon code without switching back to login again.
{"Valid"} for Valid Token Code
{"InValid"} for Invalid Token Code
Test Plan:
CSV File:
Move your CSV Data Set Config to be a child of the Validate Coupon Code request. Amend Sharing Mode settings according to your test scenario
Put your Generate Bearer Token under the Once Only Controller, this way it will be executed only once per thread (virtual user), during the first iteration of the Thread Group and will be skipped for the subsequent iterations

JMeter - Pause the request if it gives an error

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)
}

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

TO check response of particular id should be diff through jmeter

MY response for api is:-
"data":{"shortId":"lu131559"}}
Now i wants to check short id is different for every virtual user.
mns if second hit gone response data is
lu131560
So i want to validate that after 1000 request from virtual user every time i am getting diff id.
If you know the "current" value of the shortId and expect it to be incremented by 1 each time you call your API you can go for Response Assertion and use __intSum() and __counter() functions combination in the pattern like:
lu${__intSum(131559,${__counter(,)},)}
Each time the Assertion will be called it will expect the value to be incremented by one, i.e.
lu131560 - for 1st user or iteration
lu131561 - for 2nd user or iteration
lu131562 - for 3rd user or iteration
etc.
More information: Apache JMeter Functions - An Introduction

How to conditionally exit in jmeter

I have few steps in my script. I am testing it for 1000 users.
1. Validate username
2. Validate Password
3. User Info
4. Settings
5. Payments
20. Logout
etc...
I would get a token on password call, if call is success and then I would extract token run all the steps..
But If this is failed, then I don't want run all the step on the thread because it will definitely fail. It should go to step 1 again rather than running all the steps.
Consider put your steps until token created inside While Controller
The While Controller runs its children until the condition is "false".
As a controller Condition field you can check last sampler failed (assert that token is extracted)
${JMeterThread.last_sample_ok}
And it will loop until token retrieve and continue flow

Resources