I am trying to test my API response using JSON assertion in JMeter, but couldn't find out on how to achieve it. The API returns 2 values, and I need to check if the difference between these two value are consistent
API response:
{
"start": "12759898",
"end": "12759907"
}
I've tried like the above, but it seems to be wrong, as its a JSONPath variable.
Could anyone guide on how to evaluate these values? is it possible to achieve this?
It looks like a job for JSR223 Assertion
Add JSR223 Assertion as a child of the request which returns the above JSON
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def start = response.start as long
def end = response.end as long
def delta = end - start
if (delta != 10) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Expected: 10, got: ' + delta)
}
If the difference between start and end will not be equal to 10 - the request will be marked as failed.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial
Related
Sample Request1:
id=abcd&payment=paymentinitiate&ENCID=xyz&TOKENID=1234&APPTYPE=908&Mobile=ext
Sample Response1:
{
"RESPONSECODE": "100",
"TESTID": "200",
"ERRORDESC": "Success",
"DOMAINNAME": "TEST",
"TOTALCOUNT": "4"
}
Like above i need to give 100 requests and will be getting 100 separate responses(separate debug samplers) in Jmeter. I want to extract the value for ERRORDESC and DOMAINNAME available in each response in a separate common output file.
Kindly suggest a solution for this.
You can do it by adding a JSR223 PostProcessor and using the following code:
def counter = ctx.getThreadNum() // if you run 100 requests with 100 users
//def counter = vars.getIteration() if you run 100 requests with 1 user and 100 iterations
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
new File('response-' + counter + '.txt') << response.ERRORDESC << ',' << response.DOMAINNAME
it will generate files response-0.txt, response-1.txt etc. with the data extracted from each response
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?
Hi I want to store the value return by below code in JMeter webDriver Sampler . but i am getting error.
String access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
OR
var access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
Both above ways are not working?
In order to be able to help we need to know the details of the error "you are getting". Also it's unclear what localStorage.key(2) object stands for.
Here is an example of getting se:fkey value from https://stackoverflow.com website:
I used default language for WebDriver Sampler: javascript and the following piece of code:
WDS.sampleResult.sampleStart()
WDS.browser.get('https://stackoverflow.com')
var access_token = WDS.browser.executeScript('return window.localStorage.getItem("se:fkey")')
WDS.log.info('Got the following value from local storage: ' + access_token)
WDS.sampleResult.sampleEnd()
And it works just fine:
If you additionally need to store the value into a JMeter Variable add the following line:
WDS.vars.put('access_token', access_token)
and you will be able to access the extracted value as ${access_token} where required.
More information: The WebDriver Sampler: Your Top 10 Questions Answered
I am setting up a jmeter test plan for http requests and I want to create a table capturing some details from http request and response. I read http request from a file using CSV Data Set Config. My request and response formats are as follows
Http Request Format: {"TYPE":"<type>", "PAYLOAD": [<Array of data>]}
Http Response Format: {"RESPONSE":[<Array of data>]}
Things I want to capture for each request, response are TYPE from HTTP Request, Array Size of RESPONSE (or Array size of PAYLOAD) and Time Taken.
The jmeter version I am using is v5.2.1. Any inputs on how can I set this up?
Edit: My HTTP request is a POST request. I am looking to capture details from Request Body.
If you don't mind using JMeter Plugins you can:
Declare the variables from the CSV file as Sample Variables
Extract the number of matches from the response using JSON Extractor configured like:
Name of created variables: responsarray
JSON Path expressions: $.RESPONSE.*
Match Nr.: -1
the variable value you need to declare in the Sample Variables will be responsearray_matchNr
The above Sample Variables can be saved into a file using Flexible File Writer
If you cannot use the plugin you still can achieve the same using JSR223 Listener and the following Groovy code:
def result = new File('result.txt')
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def requestType = request.TYPE
def requestArray = request.PAYLOAD.size()
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def responseArray = response.RESPONSE.size()
def timeTaken = prev.getTime()
result << requestType << ',' << requestArray << ',' << responseArray << ',' << timeTaken << System.getProperty('line.separator')
My test plan looks like,
I am running some Http requests with assertion .
I need to check assertion is passed or failed (any built-in variable is available?) .
Need to call/extract assertion result and use it for my next API .
Any one help me on this.
I solved this case using BeanShell Listener by adding the following code and you can call assertion result on jmeter like ${results}
try
{
int results;
if (sampleResult.isSuccessful()) {
log.info("Response Assertion PASSED");
results = 1;
vars.put("results","1");}
else {
log.info("Response Assertion FAILED" );
results = 2;
vars.put("results","2");}
}
catch (Throwable ex) {
log.error("Error in Beanshell", ex);
throw ex;
}
I would suggest adding JSR223 Assertion where you can get parent sampler AssertionResult instance(s) and extract the required information from it like:
def assertionResult = SampleResult.getAssertionResults()[0]
if (assertionResult.isFailure()) {
log.info("Assertion " + assertionResult.getName() + " failed")
log.info(assertionResult.getFailureMessage())
}
Demo:
See How to Use JMeter Assertions in Three Easy Steps article for more information on using assertions. Also avoid using Beanshell as it may cause performance problems, if you need to go for scripting - stick to JSR223 Test Elements
1.Use "Regular Expression Extractor" to extract assertion result.
2.Use BeanShell Sampler to get assertion result,then,use it for your next API.
I created a script in jmeter, few positive cases and few are negative cases.
For Positive Cases - Response Code will come as 200
For Negative Cases - Response Code will come as 412.
As per Jmeter if Response Code 4xx or 5xx will be considered as Fail but in my case i am expecting result as 412 in negative cases and i want to consider that as Pass.
I tried with BeanShell Assertion but i didn't get the expected.
Code is as below:
String ErrorValue = "${ExpectedError}";
if((ErrorValue.equals("ERROR")) && (ResponseCode.equals("412")))
{
Failure = false;
}
else if(ErrorValue.equals("NO ERROR") && ResponseCode.equals("200"))
{
Failure = false;
}
else
{
Failure=true;
}
with about code i am able to check the expected error and response is same but if that is same how to change the status to pass i didn't get.
Please anyone help me.
Thanks
Sarada
Your Failure = false bit sets only Beanshell Assertion success. As far as I understand you need to change status of the parent sampler. In order to do so you need to invoke SampleResult.setSuccessful() method and set it to "true" as follows:
SampleResult.setSuccessful(true);
Full code:
String ErrorValue = "${ExpectedError}";
if((ErrorValue.equals("ERROR")) && (ResponseCode.equals("412")))
{
Failure = false;
SampleResult.setSuccessful(true);
}
else if(ErrorValue.equals("NO ERROR") && ResponseCode.equals("200"))
{
Failure = false;
SampleResult.setSuccessful(true);
}
else
{
Failure=true;
}
References:
SampleResult class JavaDoc
How to Use JMeter Assertions in 3 Easy Steps
If you are expecting a HTTP Response Code "failure" in JMeter but wish to flag the sample as successful this can be accomplished by a response assertion:
For example:
When validating a DELETE call works, we might want to re-try a GET and validate 404 as expected. Normally JMeter would consider this a failure, but in the context of our test it is not.
Add A Response Assertion to the after-delete GET call.
Apply To: Main Sample
Response Field to Test: Response Code
Check off "Ignore Status"
Pattern Matching Rules: Equals
Pattern to Test: 404
The status of failed or not is always ignored. However, only if the assertion of 404 matches will the request be a success.
For example, if the call returned a 500 jmeter would still ignore the "failed" status, but mark the sample as a failure because 500 != 404.
-Addled