Actually i am creating a test plan using jmeter.In that test plan i have put
many assertions like response assertion,xpath assertion and html assertion.
Now i want to show all assertion result in a single view result tree along with other results...for that i am using the custom code..but its not working.its showing only one assertion result that is last assertion result.so please tell how can i show all assertion in same result tree.My code is
import org.apache.jmeter.assertions.AssertionResult;
AssertionResult[] results = sampleResult.getAssertionResults() ;
for(int i =0,j=1 ; i<results.length;i++) {
AssertionResult result = results[i];
if(result.isFailure() || result.isError()) {
vars.put("assertionResult_" +j, result.getFailureMessage());
j++;
}
}
There is an Out Of The Box component to do this called Assertion Results
Find a tutorial on assertions showing it at:
http://www.guru99.com/assertions-in-jmeter.html
Related
I have a request in Jmeter that I need to loop until I find the result I am looking for. I have read a few bits about a while controller but found them unhelpful as they seem to glance over vital information or are using an older version of Jmeter
I'm currently using Jmeter 5.0, and I have attempted to implement a while controller but failed as I think I do not understand how to properly handle the response, or even grab it, and then use it as a comparison to assert if the item exists.
I get a response from the HTTP request call response that looks a little somthing like this:
{"data":{"getIDs":{"Page": 1,"PageSize": 25,"PageCount": 1,"isFirstPage": true,"batches":[{"id":"b601a257-13fe-4de3-b779-a5922e89765a"},{"id":"b601a257-13fe-4de3-b779-a5922e89765b"},{"id":"b601a257-13fe-4de3-b779-a5922e89765c"}]}}
I need to recall the endpoint until I have found the ID I am looking for or cancel after 10 attempts
So after a bit of fumbling around I, I figured on my own answer that seems to work well. But I would suggest looking at other sources before taking mine as gospel.
The basic structure looks as follows:
Within a thread I set the variables then create the while loop as the next step. Within the While loop I created a counter then added the request I wanted to loop after. To make the loop work for me, I have three items sat under the request.
A Response Assertion: this check for a 200 status as the call should never fail
A Constant Timer: There is a delay between polls of the end point
A JSR223 Assertion: groovy code used ensure the while loop logic is handled
User Defined Variables:
Here i have setup two variables:
DONE: Done is a string value I alter if my JSR223 Assertion finds the values I'm looking for in the HTTP request
MyValue (this is dynamically driven in my actual test, for demo purpose, I’m just declaring a value to look for i.e. 12345)
While Controller:
I still feel i may not understand this correctly, however after some googling I came across the following code that works for me despite some errors in the JMeter console:
${__javaScript(("${DONE}" != "yep" && ${Counter} < 10),)}
This code is saying that the while loop will continue until either of these two conditions are met:
DONE, the variable created earlier, is equal to the value yep
Counter is less than 10 (Counter is declared beneath the while loop)
Counter:
this was a simple configuration step that just worked once I understood it needed to be within the while loop, i configured the following:
Starting value = 1
Increment = 1
Exported Variable Name = Counter
Ticked 'Track Counter independently for each user'
Ticked 'Reset counter on each thread group iteration'
(Exported Variable Name: you can call this whatever you want, I’ve named it counter for the purpose of this demo)
JSR223 Assertion:
This is a simple script assertion that just uses a Boolean and a couple of if statements to assert the state of the test.
import org.apache.commons.lang3.StringUtils;
def done = vars.get("DONE");
String response = prev.getResponseDataAsString(); //retrieves the http request response as text
String MyValue = vars.get("MyValue");
def counter = vars.get("Counter");
//Find Substring within response string and stor result as boolean
String container = response;
String content = MyValue;
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
//Check if the true condition is met and change the value so the loop exits
if (containerContainsContent == true){
log.info("------------------------Got Here");
vars.put("DONE", "yep");
}
//Force test to fail after 10 loops
if (Counter.toString() == "10"){
assert 1 == 2
}
My JMeter test plan looks like this:
HTTP Request
- Assertion
HTTP Request
- Assertion
HTTP Request
- Assertion
Assertion Result Listener
I'd like to define all assertion results from the listener as a variable and use that variable in a POST call to JIRA, so the description contains an overview of all assertions and failure and pass of each assertion.
Assertion Result Listener
I know I can save the assertion results to a file and upload that, but I need the assertion results as text in the JIRA. Any ideas how I can do that?
edit: this is for a functional test suite.
Add JSR223 Listener to your Thread Group
Put the following code into "Script" area
def result = vars.get('result')
StringBuilder builder = new StringBuilder()
if (result != null) {
builder.append(result).append(System.getProperty('line.separator'))
}
prev.getAssertionResults().each { assertionResult ->
builder.append(prev.getSampleLabel()).append(System.getProperty('line.separator'))
if (assertionResult.isFailure()) {
builder.append('\t').append(assertionResult.getFailureMessage()).append(System.getProperty('line.separator'))
}
}
vars.put('result', builder.toString())
props.put('result', builder.toString())
Add tearDown Thread Group to your Test Plan
Refer the generated string holding the assertion results using __P() function as ${__P(result,)}
Demo:
See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in JMeter.
I have caught up in a situation, where in i need to verify the response of the Previous Sampler for one of the value and if the Value for that is [], then i need to trigger the below request or else then switch to another Sampler.
Flow:
Check Response of Sampler for One of the attribute
IF(attribute value==[])
Execute the Sampler under IF Conditions.
ELSE
New Sampler
Sample Response:
{"id":8,"merchant_id":"39","title":"Shirts-XtraLarge","subtitle":null,"price":110,"description":null,"images":"image_thumbs":[[]],"options":[],"options_available":[],"custom_options":[]}
I need to check if the attribute custom_options is empty or not! If Empty do some actions and if not empty do some other action !
Need if condition to simulate this!
Help is useful!
A nice to have feature in JMeter would be Else statement, but until then you will have to use 2 If Controllers
If Controller allows the user to control whether the test elements below it (its children) are run or not.
Assuming you hold your attribute value using regex/json/css/other post processor extractor add two condition, first is positive and under it the Sampler:
${__groovy("${attributeValue}" == "[]")}
Second is negative and under it add the New Sampler
${__groovy("${attributeValue}" != "[]")}
__groovy is encourage to use over default Javascript
Checking this and using __jexl3 or __groovy function in Condition is advised for performances
Go for Switch Controller
Add JSR223 PostProcessor as a child of the request which returns your JSON
Put the following code into "Script" area:
def size = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..custom_options')[0].size()
if (size == 0) {
vars.put('size', 'empty')
} else {
vars.put('size', 'notempty')
}
Add Switch Controller to your Test Plan and use ${size} as "Switch Value"
Add Simple Controller as a child of the Switch Controller and give empty name to it. Put request(s) related to empty "custom_options" under that empty Simple Controller
Add another Simple Controller as a child of the Switch Controller and give notempty name to it. Put request(s) related to not empty "custom_options" under that notempty Simple Controller.
More information: Selection Statements in JMeter Made Easy
I've made login process with the help of jmeter. In of of request samplers I'm expecting to get response code "401". I've added BeanShell Assertion
if (ResponseCode.equals("401") == true) {
SampleResult.setResponseOK();
SampleResult.setSuccessful(true);
}
And my Results Tree is looking like this now.
My question is - what i need to add to BeanShell in order to make child of the second sample green (passed) as well as it's parent sample?
The easiest way is using Response Assertion configured like:
If you are still looking for Beanshell solution - you need to process all sub-results along with the main result so you should amend your code like:
import org.apache.jmeter.samplers.SampleResult;
//process main sample
if (SampleResult.getResponseCode().equals("401")) {
SampleResult.setResponseCodeOK();
SampleResult.setSuccessful(true);
}
//process all subsamples
for (SampleResult subResult : SampleResult.getSubResults()){
if (subResult.getResponseCode().equals("401")){
subResult.setResponseCodeOK();
subResult.setSuccessful(true);
}
}
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Beanshell in JMeter test scripts.
I am new to groovy and soapui pro. I have below sample response that displays 2 or more array elements with dynamic data. I am wondering how to write a script assertion or xpath match to check if script passes as long as one of the elements has value 1.
<ns1:SampleTests>
<ns1:SampleTest1>
<ns1:Test>1</ns1:Test>
</ns1:SampleTest1>
<ns1:SampleTest2>
<ns1:Test>2</ns1:Test>
</ns1:SampleTest2>
</ns1:SampleTests>
I have written this in script assertion but its failing.
Supposing that you've a response like:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<ns1:SampleTests xmlns:ns1="hola">
<ns1:SampleTest1>
<ns1:Test>1</ns1:Test>
</ns1:SampleTest1>
<ns1:SampleTest2>
<ns1:Test>2</ns1:Test>
</ns1:SampleTest2>
</ns1:SampleTests>
</Body>
</Envelope>
You can perform the follow XPath: exists(//*:Test[.=1]) to check that exists at least one <ns1:Test> element with 1 as value.
Inside an XPath Match it looks like:
If instead you prefer to use an Script assertion you can use the XmlSlurper to parse your Xml, then get all <ns1:Test> values an assert that at least one has 1 as value. Look into the follow code:
// get the response
def responseStr = messageExchange.getResponseContent()
// parse the response as slurper
def response = new XmlSlurper().parseText(responseStr)
// get all <ns1:Test> values
def results = response.'**'.findAll { it.name() == 'Test' }
// now in results list we've NodeChild class instances we will convert it to
// string in order to perform the assert
results = results.collect { it.toString() }
// check that at least one element has '1' value
assert results.contains('1'),'RESPONSE NOT CONTAINS ANY <ns1:Test>1</ns1:Test>'