I am new to jmeter and I am trying run http request 10 times to create 10 categories in a loop
Creating loop to run http request within it
http request
Every time, I store the response(category id) in Json Extractor in a loop.
extract value from response
At the end of the loop, how can I store all the responses (i.e. category IDs) in an array object?
Since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting
Here is some form of Groovy solution:
def ids = vars.get('categoryIDs') ?: []
if (ids instanceof String) {
ids = new groovy.json.JsonSlurper().parseText(ids)
}
ids.add(new groovy.json.JsonSlurper().parse(prev.getResponseData()).id)
vars.put('categoryIDs', new groovy.json.JsonBuilder(ids).toPrettyString())
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Related
From Database I am getting Date value as "2011-03-31 00:00:00.0"
From JSON response I am getting value as "2011-03-31"
How can I trim "00:00:00" from Database result and compare it with JSON response in JMeter using JSR223 assertion.
I don't think "trimming" is good option, I would rather go for "parsing"
Here is an example of converting 2 dates in different formats to Date object and comparing them
The code is supposed to be used in the JSR223 Assertion
def valueFromDB = Date.parse('yyyy-MM-dd hh:mm:ss.S', vars.get('valueFromDB'))
def valueFromJSON = Date.parse('yyyy-MM-dd', vars.get('valueFromJSON'))
if (!valueFromDB.equals(valueFromJSON)) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Dates mismatch')
}
Replace valueFromDB and valueFromJSON with your own JMeter Variables names holding these values from the database and from JSON.
More information: Scripting JMeter Assertions in Groovy - A Tutorial
I want to test an endpoint using jmeter, that has a copule of query string parameters, one of which is optional, loading the values from a CSV file. The problem is, can I avoid sending the query string parameter if I don't have a value for it?
It is but it will require some Groovy coding
Add JSR223 PreProcessor as a child of the request which query string you want to modify (or according to JMeter Scoping Rules if you want to apply the approach to more than one request)
Put the following code into "Script" area:
def newData = new org.apache.jmeter.config.Arguments()
0.upto(sampler.getArguments().size() - 1, { idx ->
def arg = sampler.getArguments().getArgument(idx)
if (!arg.getValue().equals('')) {
newData.addArgument(arg)
}
})
sampler.setArguments(newData)
That's it, the PreProcessor will be executed before the HTTP Request sampler and will remove all arguments which don't have their respective values
I have thread group with single sampler.I have a scenario with 10 users to run for 1 hour duration. in view results tree showing different response data in every sampler's response data.can it possible to count how many times samplers get same response data.
{"success":false,"code":"104","message":"xx","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
{"success":false,"code":"104","message":"yyy","status":412,"MessageType":"120","ResponseCode":"100","rilreplyDetails":"121"}
can I get a count of how many samplers get"xx" response,and how many for "yyy"?
One solution would be to define two variables in the Test Plan section, i.e: counter_xx and counter_yyy.
Then on the sampler request add one Regular Expression Extractor to extract the message value and finally use If Controller to specify which counter to increment.
The below image shows the structure for above solution.
Finally, you would be able to access the variable values by using ${counter_xx} or ${counter_yyy}.
The easiest would be doing this outside of JMeter, i.e. configure it to save response data by adding the next 2 lines to user.properties file:
jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
JMeter restart will be required to pick the properties up. Once your test is done inspect the resulting .jtl result file using your favorite XML editor.
See Configuring JMeter for more information on the approach.
Another option is using JSR223 Listener and the script like:
import org.apache.jmeter.engine.util.CompoundVariable
import org.apache.jmeter.functions.IterationCounter
def xxcounter = props.get("xxcounter")
if (xxcounter == null) {
xxcounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
xxcounter.setParameters(params);
}
def yycounter = props.get('yycounter')
if (yycounter == null) {
yycounter = new IterationCounter();
List<CompoundVariable> params = new ArrayList<>();
params.add(new CompoundVariable("false"));
yycounter.setParameters(params);
}
if (prev.getResponseDataAsString().contains('xx')) {
log.info('XX count: ' + xxcounter.execute(prev, sampler))
props.put('xxcounter', xxcounter)
}
if (prev.getResponseDataAsString().contains('yyy')) {
log.info('YYY count: ' + yycounter.execute(prev, sampler))
props.put('yycounter', yycounter)
}
The listener will scan current sampler response data and increment either this or that counter printing the current value to jmeter.log file.
Demo:
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
I am using Jmeter for performance testing and stuck at following point:
I am getting a JSON response from Webapi as follows:
PersonInfoList:
Person
[0]
{
id: 1
name: Steve
}
[1]
Person
{
id: 2
name: Mark
}
I need to get the ids based on the count of this JSON array and create a comma separated string as ("Expected value" = 1,2)
I know how to read a particular element using JSON Post processor or Regex processor but am unable to loop through the array and create a string as explained so that I can use this value in my next sampler request.
Please help me out with this: I am using Jmeter 3.0 and if this could be achieved without using external third party libs that would be great. Sorry for the JSON syntax above
Actually similar functionality comes with JSON Path PostProcessor which appeared in JMeter 3.0. In order to get all the values in a single variable configure JSON Path PostProcessor as follows:
Variable Names: anything meaningful, i.e. id
JSON Path Expressions: $..id or whatever you use to extract the ids
Match Numbers: -1
Compute concatenation var (suffix _ALL): check
As a result you'll get id_ALL variable which will contain all JSON Path expression matches (comma-separated)
More "universal" answer which will be applicable for any other extractor types and in fact will allow to concatenate any arbitrary JMeter Variables is using scripting (besides if you need this "expected value and parentheses)
In order to concatenate all variables which names start with "id" into a single string add Beanshell PostProcessor somewhere after JSON Path PostProcessor and put the following code into "Script" area
StringBuilder result = new StringBuilder();
result.append("(\"Expected value\" = ");
Iterator iterator = vars.getIterator();
while (iterator.hasNext()) {
Map.Entry e = (Map.Entry) iterator.next();
if (e.getKey().matches("id_(\\d+)")) {
result.append(e.getValue());
result.append(",");
}
}
result.append(")");
vars.put("expected_value", result.toString());
Above code will store the resulting string into ${expected value} JMeter Variable. See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information regarding bypassing JMeter limitations using scripting and using JMeter and Java API from Beanshell test elements.
Demo:
Currently developing a script in jMeter, I need to retrieve x amount of values from a response then push those values into another HTTP request, here is the tricky part the response is a table which always changes (e.g. rows increase or decrease each time the test is run) so far I've created a Regex extractor which retrieves anything between the table now I need to create a beanshell post processor which retrieves the certain values from the variable retrieved by the Regex extractor and applies them to the HTTP request. I'm not to sure if this is the best way to do this so I am open to suggestions on doing this another way.
You need Beanshell PreProcessor applied to 2nd request, not PostProcessor applied to 1st request
I don't think that using Regular Expressions is a very good idea to parse HTML, I would suggest going for CSS/JQuery Extractor or XPath Extractor instead
Once you have required values in form of
var_1=foo
var_2=bar
var_MatchNr=2
You will be able to add these values to the 2nd HTTP Request like:
import java.util.Iterator;
import java.util.Map;
Iterator iter = vars.getIterator();
int counter = 1;
while (iter.hasNext())
{
Map.Entry e = (Map.Entry)iter.next();
if (e.getValue() != null)
{
if (e.getKey().toString().startsWith("var_") && e.getValue().toString().length() >0)
{
sampler.addArgument("param" + counter, e.getValue().toString());
counter++;
}
}
}