Jmeter Groovy replacing JSON file - groovy

In Jmeter JSR223Preprocessor with Groovy I load a generic JSON file xyz looking like this:
{
"name": "dummy",
"block1": {
"var1": 1,
"var2": {
"value": 1,
"unit": "Miles",
},
"var3": {
"value": 3,
"unit": "Seconds",
},
"myList": [{"Id": 0}]
}
I like to come up with an elegant way to replace the var2 "Value" with a configurable value sayconfVal. This works:
String path = vars.get("basePath")+"xyz.json" ;
xyz = new File(path).getText("UTF-8");
xyz = xyz.replaceAll ('"value": 1', '"value": ${confVal}');
However I am not comfortable with this because it is vulnerable with spaces, and moreover I have another Value on var3 and someone could accidentally change 1 to 3. So I like to index to that child var2.Value then get Value.
Thank you

Add JSR223 PreProcessor as a child of the HTTP Request which body you need to amend
Put the following code into "Script" area:
def xyz = new File(vars.get("basePath")+"xyz.json")
def request = new groovy.json.JsonSlurper().parse(xyz)
request.block1.var2.value=vars.get('confVal') as int
xyz.newWriter().withWriter { writer ->
writer << new groovy.json.JsonBuilder(request).toPrettyString()
}
That's it, the value in the file should be replaced with what you have in the ${confVal} variable in the runtime.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Related

Groovy slurper.parser variable of a variable

Here is the snippet of my groovy script:
jsonFileData = slurper.parse(jsonFile)
Here is my JSON file
{
"MEMXYZ": {
"LINKOPT": {
"RMODE": "31",
"AMODE": "ANY"
},
"PROCESSOR": "PROCESSOR XYZ",
"DB2": {
"OWNER": "USER1",
"QUALIFER": "DB2ADMIN",
"SSID": "DBC1"
},
"COBOL": {
"VERSION": "V6",
"CICS": "V5R6M0",
"OPTIONS": "LIST,MAP,RENT",
"DB2": "YES"
}
}
}
println "Print1 ***** Parsing PROCESSOR = ${jsonFileData.MEMXYZ.PROCESSOR}"
println "Print2 ***** Parsing PROCESSOR = ${jsonFileData}.${Member}.PROCESSOR"
The Print1 is working fine with with explicit Member name "MEMXYZ", but I have problem with Print2, which I need to have the dyanmic ${Member} variable substitution. Please help!
${Member} is MEMXYZ
Please help to solve the Print2 statement
".. ${abc} ..." just injects the value of abc variable into string.
To access values of map (result of slurper.parse(...) in your case) you could use one of approaches:
jsonFileData[Member].PROCESSOR
jsonFileData[Member]['PROCESSOR']
So, your print line could look like:
println "PROCESSOR = ${jsonFileData[Member].PROCESSOR}"

Parsing script in node js using node-html-parser

I'm making a script using node.js and i need to parse a script inside a website, exactly i need 2 part not only the entire script. The 2 parts are "stock" and "local" and their values.
<script id="z-vegas-pdp-props" type="application/json">
![CDATA[{
"layout": "cover",
"model": {
"layout": "cover",
"priceInfo": {
"showPriceHint": false,
"priceHintType": ""
},
"mediaInfo": {
"currentIndex": 0
},
"price": {
"currency": "EUR",
"value": 129.99,
"formatted": "129,99 €"
},
"originalPrice": {
"currency": "EUR",
"value": 129.99,
"formatted": "129,99 €"
},
"available": false,
"stock": 0
}
//here the scripts continues but i "trimmed it to make it more easy"
</script>
This is what i made but it's parsing all the code and not only the parts that i need.
let root = HTMLParser.parse(response.body);
let availabiltyDiv = root.querySelector("#z-vegas-pdp-props")
console.log(availabiltyDiv)
The data you're looking for is hiding in json format inside the CDATA in the script. So you first need to extract the json string, parse it and get to the target data. Incidentally, the json string sample in your question is malformed, but is presumably well formed in the actual script. Also, there is no local in your sample, so I'll use another value instead.
All in all:
const jstring = availabiltyDiv.childNodes[0].nodeValue.split('CDATA[')[1].split(']')[0]
const target = JSON.parse(jstring);
#to get to (for example) price and stock:
const price = target.model.price.formatted;
const stock = target.model.stock;
console.log(price,stock)
Output:
"129,99 €" 0
EDIT:
As expalined in the respoinse to your comment, I don't have access to your actual availabilityDiv but you can also try replacing
const jstring = availabiltyDiv.childNodes[0].nodeValue.split('CDATA[')[1].split(']')[0]
with
const jstring = availabiltyDiv.innerHTML.split('CDATA[')[1].split(']')[0]
or with
const jstring = availabiltyDiv.innerText.split('CDATA[')[1].split(']')[0]
and see if they work.

jmeter Reading Json data from file using JSR223, converting braces to square bracketconverting

I am using jmeter 5.1 in windows 10, in my jmeter test plan i am reading json data from file, after reading, i am using log.info ${sdata} to log the messages, but the output is converted the braces { to square bracket [, could someone tell me what's wrong.
Below is the data which the json file contains
{"name":"Foo Bar","year":"2018","timestamp":"2018-03-08T00:00:00","tags":["person","employee"],"grade":3.14}
{
"name": "Foo Bar",
"year": "2018",
"timestamp": "2018-03-08T00:00:00",
"tags": [
"person",
"employee"
],
"grade": 3.14
}
Below is the line which i have in JSR223 Prepocessor to read the file and log it in info
def sdata = new groovy.json.JsonSlurper().parseText(new File("data.json").text)
log.info "$sdata"
And below is the output of log.info
["name":"Foo Bar","year":"2018","timestamp":"2018-03-08T00:00:00","tags":["person","employee"],"grade":3.14]
[
"name": "Foo Bar",
"year": "2018",
"timestamp": "2018-03-08T00:00:00",
"tags": [
"person",
"employee"
],
"grade": 3.14
]
In the above output, the braces { got replaced to square bracket [
Please help
This happens because you're basically printing a textual representation of LazyMap
If you want to see the same JSON as in the input you should create a JsonBuilder class instance and pass the "slurped" object to it.
Change this line:
log.info "$sdata"
to this one:
log.info(new groovy.json.JsonBuilder(sdata).toPrettyString())
More information:
Apache Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Updating Jmeter Json request

I have created a json block file which looks like this, I like to add a new element i.e
{
"Id": 0,
"cc": "123"
}
I need to add a new element
"xyz": ${abc}
the resulting to look like
{
"Id": 0,
"cc": "123",
"xyz": ${abc}
}
I have retrieved the file
String json1 = vars.get("basePath")+"Jmeter/Results/json1";
json1= new groovy.json.JsonSlurper().parse(json1);
How do I add
"xyz": ${abc},
to json1 ?
Use the following code:
String json1 = vars.get("basePath")+"Jmeter/Results/json1";
def parsedJson = new groovy.json.JsonSlurper().parse(json1);
parsedJson.put('xyz',vars.get('abc'))
def newJson = new groovy.json.JsonBuilder(parsedJson).toPrettyString()
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

How to access dynamic values in script assertion; which are set at test case level?

I have set a dynamic value at test case level for the below response.
{
"orderDetails": {"serviceOrderNumber": "SO-EUAM-MX-EUAM-16423"},
"transactionDetails": {
"statusMessage": "Success",
"startRow": "1",
"endRow": "400",
"totalRow": "1",
"timeZone": "EST"
},
"customerNodeDetails": {
"startDate": "20180622 06:32:39",
"nodeCreateDate": "20180622 06:32:39",
"customerId": "5562"
}
}
assert context.response, 'Response is empty or null'
def json = new groovy.json.JsonSlurper().parseText(context.response)
context.testCase.setPropertyValue('CustID', json.customerNodeDetails.customerId.toString())
Now while asserting another API which is a GET one, I am getting the CustID as customerNumber.
I have used the below code:
assert json.customerNodeDetails.customerNumber == "${#TestCase#CustID}"
and the block of response for the same was:
"customerNodeDetails": {
"nodeLabel": null,
"customerNumber": "5544",
"customerName": "ABCDEFGHIJ ABCDEFGHIJ LMNOPQRSTUV1234",
"taxIdCity": "",
"taxIdState": "",
"salesSegment": "Government",
"dunsNumber": "",
"mdsId": "",
"accountClassification": "B",
"specialCustomerBillCode": ""
}.
But I am getting the below error as:
startup failed: Script65.groovy: 26: unexpected char: '#' # line 26, column 54. eDetails.customerNumber == "${#TestCase# ^ org.codehaus.groovy.syntax.SyntaxException: unexpected char: '#' # line 26, column 54. at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:138) at
Please let me know how to access that value.
If you're referring to a property within a Groovy script, you can't use it directly as you might in other parts of the UI. You need to expand it:
def custID = context.expand('${#TestCase#CustID}')
Or, the messageExchange variable available in script assertions gives you an alternative way to do the same thing:
def alternative = messageExchange.modelItem.testStep.testCase.getPropertyValue('CustID');
Then, if you need a property that's defined somewhere else other than at the test-case level, you can use:
def projectLevelProperty = messageExchange.modelItem.testStep.testCase
.testSuite.project.getPropertyValue('projectLevelProperty');

Resources