how to Create multiple json object & post in single request - json

I have my csv file as:
row 1 - 1000 uuids & row2 - 1000 names
i need to call each uuid & their corresponding name in below json structure and finally need to post in single request.
so far i have tried below json in jsr223 preprocessor & response is successful:
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
builder({
Data{
"${__UUID()}"{
name{
"${__RandomString(10,abcdefg)}"(1)
}
p([1,1])
m([1,2])
o([2,3])
}
}
E([])
S(${__time()})
})
println builder.toPrettyString()
vars.put("json", builder.toPrettyString());
Now the problem is i need to link line 6 ("${__UUID()}) & line 8 (${__RandomString(10,abcdefg)}) with csv file & need to call all the columns, which i haven't known how to proceed & finally post as single request.
Any help would be greatly appreciated. Thanks.

You can fetch the arbitrary cell from the CSV file using __CSVRead() function, check out How to Pick Different CSV Files at JMeter Runtime article for more details.
Not knowing the format of the JSON payload you're trying to generate it is not possible to come up with the comprehensive solution, but one thing is obvious, as per JSR223 Sampler documentation:
When using this feature, ensure your script code does not use JMeter variables directly in script code as caching would only cache first replacement. Instead use script parameters.
So don't ever inline JMeter Functions or Variables into JSR223 scripts as you do because it will update only once, on subsequent iterations the value will be cached and will not update.

Related

Jmeter JSR223 Assertion - How to compare fieldnames and values from csv with API response data

I am very new to Jmeter and was hoping to get some direction on how to achieve this task.
I am supposed to write a Jmeter which does following:
Read test data from csv file and calls a GraphQL API using the test data
Compares response from the API with values from the CSV file.
I have achieved #1 using CSV Data Set Config. But really need help with #2.
My csv file has following format:
fieldname 1,fieldname 2, fieldname 3
value1,value2, value3
I can have multiple csv files to compare the results with. I want to use JSR223 assertion to dynamically check fieldnames from csv and compare value for that fieldname with value returned in API response. fieldname in API response will be same as fieldname in the csv.
So, if I can write a generic code that picks fieldname from csv and then compares its value with fieldname from API response, it will work as long as fieldnames are set properly in the csv file.
Can anyone point me to a sample code that does this or Guide me on how to approach this.
Any help will be much appreciated.
We cannot give you the "sample" code because your question doesn't have any API response details.
So far I can only provide the following "samples"
CSV file can be read in Groovy into an array of lines like:
new File('/path/to/your/csv/file').readLines()
JavaDoc: File.readLines()
API response can be obtained within the JSR223 assertion as follows:
prev.getResponseDataAsString()
JavaDoc: SampleResult.getResponseDataAsString()
You may find Scripting JMeter Assertions in Groovy - A Tutorial article useful.

In Jmeter, How can we use JSR223 Preprocessor to parse a CSV and filter on a particular column value to pass it as a variable to a sampler

I'm new to JMeter and trying my best learn various things in JMeter especially regarding the CSV data processing as the application which I am working needs loads of parameterized data and I just can't create 100's of CSV filed as per the requirement and instead use a single CSV and filter the values based on specific conditions.
However, I'm finding it very difficult to write the code for this particular operatoin.
Name|Identity|Date
"001, A"|"3409ADD9"|05-01-2020
"002, B"|"BA47D76A"|05-01-2020
"003, C"|"2BC92A2D"|05-02-2020
"004, D"|"AB9AEEBE"|05-23-2020
"005, E"|"09FF417D"|05-29-2020
Note: Here I'm using | to parse as my data will contain as part of the Name as shown.
As you can see, The data is grouped by Date value. I want to use this CSV file to pass the Identity and Name value based on currentDate.
For Ex, Current Date is May-01-2020, I want to pass only those records whose date is May-01-2020 and pass it as a variable to my samplers in a loop. Once we reach the end of the file (I mean values which don't have date May-01-2020 associated with, I want to start the loop again ) and repeat from first till the time I mention in the RunTime Controller.
I went through different questions and trying to find a solution as I couldn't write one for myself in Groovy, Hence asking for help.
As per many suggestions in different questions regarding the use of JSR223 preprocessor with Groovy instead of a bean shell, I would like to seek some guidance to solve this problem to move further.
Add setUp Thread Group to your Test Plan
Add JSR223 Sampler to the setUp Thread Group
Put the following code into "Script" area:
SampleResult.setIgnore()
def original = new File('/path/to/original.csv').readLines()
def current = original.findAll() { line -> line.contains(new Date().format('MM-dd-yyyy')) }
def newFile = new File('/path/to/new.csv')
newFile.withWriter { out ->
out.println(original.get(0))
current.each { line ->
out.println(line)
}
}
the above code will filter the original CSV file and write only those lines which contain the current date to the new CSV file
Configure CSV Data Set Config in the main Thread Group to use the "new.csv" file from step 3

Jmeter use random string inside CSV file and resolve at runtime

I have CSV File where I have stored full JSON Request and using this variable in API RQ - ${Request}
inside each row of the CSV File I have added ${randomVariable}
In my test plan I use
randomVariable ${__RandomString(10,QWERTYUIOPASDFGHJKLZXCVBNM4563456345634_,)}
this generates the random variable but in the JSON instead of actual random value its passed as ${randomVariable}
I have tried using Beanshell PreProcessor with get and put but still doesn't work. Please help.
If you want JMeter to evaluate the variables which are coming from external data sources, i.e. CSV files, you need to wrap the variable reference name into __eval() function, to wit:
${variableFromCSV} - will return ${randomVariable}
${__eval(${variableFromCSV})} - will return the actual value of the ${randomVariable}
Demo:
More information: Here’s What to Do to Combine Multiple JMeter Variables

Using Jmeter, I need to add UUID extracted from JSON in CSV in same column (multiple values of UUID) So to pass in Delete Path

Using Jmeter, I need to add UUID extracted from JSON and add that in CSV in same column (multiple) to feed in Delete Request (REST). This is to test multiple delete calls which has unique UUID generated from POST call. Or is there any other way I can test multiple delete call after extracting from POST calls. Lets say 50 Post then 50 Delete calls.
I don't think you need to do anything as given threads reside in the same Thread Group you should be able to use the same variable for the Delete request.
JMeter Variables are local to a thread so different threads will have different variable values.
If you are still looking for a file-based solution be aware of fact that you can write an arbitrary JMeter Variable into a file using Groovy code like:
Add JSR223 PostProcessor after the JSON Extractor
Make sure you have groovy selected in the "Language" dropdown
Make sure you have Cache compiled script if available box ticked
Put the following code into "Script" area
def csvFile = new File('test.csv')
csvFile << vars.get('your_variable')
csvFile << System.getProperty('line.separator')
This way you will get any extracted UUID written into test.csv file in JMeter's "bin" folder, you can use it in the CSV Data Set Config for your Delete request.
More information:
Groovy Goodness: Working with Files
Apache Groovy - Why and How You Should Use It

Verify whole json response in jmeter by value or sort Json

I'm not using JMeter too often, and I've run into very specific issue.
My REST response is always "the same", but nodes are not in the same order due to various reasons. As well, I can't put here whole response due to sensitive data, but let's use these dummy one:
First time response might be:
{
"properties":{
"prop1":false,
"prop2":false,
"prop3":165,
"prop4":"Audi",
"prop5":true,
"prop6":true,
"prop7":false,
"prop8":"1",
"prop9":"2.0",
"prop10":0
}
}
Then other time it might be like this:
{
"properties":{
"prop2":false,
"prop1":false,
"prop10":0,
"prop3":165,
"prop7":false,
"prop5":true,
"prop6":true,
"prop8":"1",
"prop9":"2.0",
"prop4":"Audi"
}
}
As you can see, the content it self is the same, but order of nodes it's not. I have 160+ nodes and thousand of possible response orders.
Is there an easy way to compare two JSON responses comparing matching key - values, or at least to sort the response, and then compare it with sorted one in assertion patterns?
I'm not using any plugins, just basic Apache JMeter.
Thanks
I've checked using Jython, you need to download the Jython Library and save to your jmeter lib directory.
I've checked 2 JSONs with Sampler1 and Sampler2, on Sampler1 I've add a BeanShell PostProcessor with this code:
vars.put("jsonSampler1",prev.getResponseDataAsString());
On Sampler2 I've add a BSF Assertion, specifying jython as the language and with the following code:
import json
jsonSampler1 = vars.get("jsonSampler1")
jsonSampler2 = prev.getResponseDataAsString()
objectSampler1 = json.loads(jsonSampler1)
objectSampler2 = json.loads(jsonSampler2)
if ( objectSampler1 != objectSampler2 ):
AssertionResult.setFailure(True)
AssertionResult.setFailureMessage("JSON data didn't match")
Yoy can find the whole jmx in this GistHub
You will most probably have to do this with a JSR223 Assertion and Groovy.
http://jmeter.apache.org/usermanual/component_reference.html#JSR223_Assertion
http://docs.groovy-lang.org/latest/html/api/groovy/json/JsonSlurper.html
Note that if you know Python, you might look at using Jython + JSR223.
I would just set up 10 jp#gc - JSON Path Assertions. Documentation for figuring out JSON Path format is here and you can test how it would work here.
For your example you would the assertion (Add > Assertion > jp#gc - JSON Path Assertions), then to test the prop 1 put:
$.properties.prop1
in the JSON Path field, click the Validate Against Expected Value checkbox, and put
false
in the expected value field. Repeat those steps for the other 9 changing the last part of the path to each key and the value you expected back in the expected value field.
This extractor is jmeter add on found here.