Jmeter - Set status after few request have been sent - jmeter

Can I resolve the following scenario by JMeter?:
Send request1
Insert response of request1 to request2
Send request2
Send request3
Compare response3 with responce1
If response3 = responce1 -> setResponseOK() for request2 ELSE Failed
Thanks in advance.

Suggestion to Resolve this situatuion
Send request 1
Capture the response of request 1 in var1(Using correlation-->depending up on your requirement)
Send request 3 first (as you don't need response of request 2 for input of req 3)
Capture response of request 3 in var2
Now hit Request 2 by passing the response of request 1 as an input which is store in var1
Apply beanshell post processor as a child of request 2
Now compare Respose of request 1 and 3 inside if condition:
if matches make the previous request (i.e. Request 2) pass, else fail
if(vars.get("var1").equals(vars.get("var2")))
{
prev.setSuccessful(true);
}
else
{
prev.setSuccessful(false);
}

Design your test as follows:
Request 1
Regular Expression Extractor to extract the whole response into a JMeter Variable configured as:
Reference Name: anything meaningful, i.e. response1
Regular Expression: (?s)(^.*)
Template: $1$
Request 2: use ${response1} where required
Request 3
Response Assertion configured like:
Pattern Matching Rules: Equals
Patterns to Test -> ${response1}
Reference material:
Regular Expressions
How to Use JMeter Assertions in Three Easy Steps

Related

JMeter - Hide failed requests on successful retry

I make retry logic with while loop. It will to be retry when response code is not 200.
Retry times is 3 times, if after 3 times still failure, give up.
However, even request is success after retry. The failed request does show in result tree and summary report.
Is it possible don't show failed request when success after retry in report. Only show request when after 3 time retry but still failure .
Now Situation
Request:
request(fail) -> request(fail) -> request(success)
Result tree:
request(fail)
request(fail)
request(success)
This is image I want.
Request:
request(fail) -> request(fail) -> request(success)
Result tree:
request(success)
Request:
request(fail) -> request(fail) -> request(fail)
Result tree:
request(fail)
Put your request under Loop Controller and give the number of loops as 3
Add JSR223 PostProcessor as a child of your request and put the following code into "Script" area
if (prev.getResponseCode() == '200') {
ctx.setTestLogicalAction(ctx.TestLogicalAction.BREAK_CURRENT_LOOP)
}
else {
if (vars.get('__jm__Loop Controller__idx') as int < 2) {
prev.setIgnore()
}
}
where:
prev stands for the previous response SampleResult
ctx stands for JMeterContext
and vars for JMeterVariables
More information on these JMeter API shorthands: Top 8 JMeter Java Classes You Should Be Using with Groovy

How to set http status code 200, 400, 422, 202 set as success in JMeter

In my test plan I want to mark all the response with, http status code 200, 400, 422, 202 set as success.
Is there any way I can achieve this in a single assertion ?
You should also include what you have tried so far, to resolve this it is very simple,
Need to include a JSR223 assertion with the following script,
if("400".equals(SampleResult.getResponseCode()) || "200".equals(SampleResult.getResponseCode()) || "202".equals(SampleResult.getResponseCode()) || "422".equals(SampleResult.getResponseCode())) {
SampleResult.setSuccessful(true);
AssertionResult.setFailure(false);
}
else {
AssertionResult.setFailure(true);
}
Another solution could be with a Response Assertion
Add the Response Assertion into the Test Plan. This will ensure the Assertion is applied to all the Samplers (Responses)
Then configure the Response Assertion
Field to Test as Response Code
Pattern matching rules to Equals and Or
Click the Add button and add the response codes
In addition to the above configuration, you may check the Ignore Status if you want to Instructs JMeter to set the status to success initially.
Here is another solution based on the previous answer.
//Expected Response codes
def lstExpectedResponseCodes= ["400", "200", "202","422"]
//Actual Response code
String actualResponseCode=SampleResult.getResponseCode()
boolean hasResponseCode = lstExpectedResponseCodes.contains(actualResponseCode)
AssertionResult.setFailure(!hasResponseCode)
SampleResult.setSuccessful(hasResponseCode);

Jmeter log only HTTPSampler with JSR223 Listener

Trying to have a JSR223 Listener on Test Plan level so it listens to all thread groups. What I like to achieve is that it only logs every HTTP Request's methods (GET, POST, HEAD, OPTIONS, PUT, DELETE and TRACE) and print every Method, URL, Response Code, Value and Response Data.
Having looked around, found some snippets left right and center and have come up with this:
try{
if (sampler.getUrl().toString().contains("http")){
log.warn('Method: ' + sampler.getMethod() + ' URL: ' + sampler.getUrl().toString());
sampler.getArguments().each {arg ->
log.warn('CODE: ' + prev.getResponseCode() + ' Value: ' + arg.getStringValue())
}
log.warn('CODE: ' + prev.getResponseCode() + ' ResponseData: ' + prev.getResponseDataAsString());
}else{
log.warn('Not a HTTPRequest')
}
}
catch (Throwable ex)
{
log.warn('Something went wrong', ex);
throw ex;
}
And I get the results in my log viewer as desired.
The challenge I am facing is if any other sampler type is active, it logs an error because that sampler is not an HTTP request but a dummy sampler, so it cannot return the requested values.
groovy.lang.MissingMethodException: No signature of method: kg.apc.jmeter.samplers.DummySampler.getUrl()
Now my example shows only two samplers in the Thread Group, but imagine a couple of 100 various samplers
Figuring I need to change my 'if' statement to not check for the sampler argument, but for the sampler type instead (HTTPRequest), but good old google returns not much to go on. So, is it even possible to have an if statement that checks for sampler type, and what would that syntax be?
if (sampler==HTTPRequest) ???
You can use sampler.getClass() and compare it to check if HTTP Request:
if("HTTPSamplerProxy".equals(sampler.getClass().getSimpleName())) {
You can check class name using log:
log.info(sampler.getClass().getSimpleName());

Handle negative cases in JMETER, for example my expected output response is 400

How to handle negative cases in JMETER, for example my expected output response is 400("There are no records") for an GET API?
In JMETER response is coming as failure or warning.
Is JMeter only handle positive scenarios like for all GET API response code should be 200 ?
Add Response Assertion as a child of the HTTP Request sampler which returns HTTP Status Code 400
Configure it as follows:
Tick Ignore status box
Set "Field to test" to Response code
Set "Pattern matching rules" to Equals
Add 400 as a "Pattern to test"
This way JMeter will pass only if the parent HTTP Request sampler returns 400 status code, otherwise it will fail.
You can add to HTTP Request Response Assertion with Ignore status checked
HTTP Responses with statuses in the 4xx and 5xx ranges are normally regarded as unsuccessful. The "Ignore status" checkbox can be used to set the status successful before performing further checks. Note that this will have the effect of clearing any previous assertion failures, so make sure that this is only set on the first assertion.
I tried with this, by adding a BeanShell Assertion with following code.
import org.apache.jmeter.assertions.AssertionResult;
String failureMessage = "";
String ResCode = SampleResult.getResponseCode();
if (!ResCode.equals("400")) {
failureMessage = "Got Response Code" + ResCode;
AssertionResult result = new AssertionResult("Expected Response 400");
result.setFailure(true);
result.setFailureMessage(failureMessage);
prev.addAssertionResult(result);
prev.setSuccessful(false);
SampleResult.setStartNextThreadLoop(true);
} else {
//failure criteria
}

Jmeter 4 | HTTP Request sampler JAVA implementation bytes sent not captured

We are using JAVA implementation for one of the requests.In the request we are uploading a file. Request doesn't work when HTTPCLIENT4 implementation is selected.The request works fine with previous Jmeter version with HTTPCLIENT3.1 implementation. We need to capture bytes sent in results. How to capture bytes sent through JAVA implementation in HTTP Request sampler
Sent bytes is basically a combination of URL + headers + body so you can calculate it yourself using JSR223 PostProcessor and code like:
def url = sampler.getUrl().toString().length()
def headers = prev.getHeadersSize()
def body = 0;
sampler.getHTTPFiles().each {file ->
body += new File(file.getPath()).length()
}
prev.setSentBytes(url + headers + body)
Where:
sampler is an instance of HTTPSamplerProxy where you can get all files which you're sending with the request
prev is an instance of HTTPSampleResult where you can get URL and Headers and also override Sent Bytes field.
See The Groovy Templates Cheat Sheet for JMeter to see what else you can do with Groovy and how.

Resources