JMeter Assertion failure with groovy - json

Update:
I want to check a JSON document on his structure. I created a JSR223 Assertion with language groovy. My code to check the JSON structure looks like this:
import groovy.json.*;
import org.apache.jmeter.samplers;
def response = prev.getResponseDataAsString();
log.info("Response" + response);
def json = new JsonSlurper().parseText(response);
//tests
def query = json.query;
assert query instanceof String;
def totalResults = json.totalResults;
assert query instanceof Integer;
def from = json.from;
assert from instanceof Integer;
def to = json.to;
assert to instanceof Integer;
assertionResult = new AssertionResult("Assertion failed! See log file.");
assertionResult.setError(true);
assertionResult.setFailureMessage(e.toString());
The validation in the JMeter logfile works great.
But in my View Result Tree, i got the following error message:
Assertion error: true
Assertion failure: false
Assertion failure message: javax.script.ScriptException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script27.groovy: 2: unable to resolve class org.apache.jmeter.samplers
# line 2, column 1.
import org.apache.jmeter.samplers;
^
Script27.groovy: 21: unable to resolve class AssertionResult
# line 21, column 19.
assertionResult = new AssertionResult("Assertion failed! See log file.");
^
2 errors
I want to see if the test result is successful or not.
How to fix this issue?

Don't instantiate AssertionResult class, it is pre-defined
Don't use Groovy assert keyword, it won't fail the parent sampler as expected, refer below example simple code
if (1 != 2) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage("1 is not equal to 2")
}
once you get it working like below:
you can start modifying your tests as required
See How to Use JMeter Assertions in Three Easy Steps guide to learn more about using assertions in JMeter tests.

Related

How to compare two JSON responses in groovy and get the differences (similar to what json editor does)?

Can someone please tell me why the error happens and possible alternatives in solving this
My code:
def actual = " [{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8369"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def expected = "[{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8366"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def removedA = actual.replaceAll("[_]","").trim();
def removedE = expected.replaceAll("[_]","").trim();
def json = new groovy.json.JsonSlurper().parseText(removedA)
//Checks all elements of resource one by one and compare with expectedData
json.each{k, v -> assert v == removedE."$k" }
Here is the error:
groovy.lang.MissingMethodException: No signature of method: Script23$_run_closure1.doCall() is applicable for argument types: (org.apache.groovy.json.internal.LazyMap) values: [[inputs:[[typename:ElementalField]], constraint:FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0', ...]] Possible solutions: doCall(java.lang.Object, java.lang.Object), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object) error at line: 37

How to send a json script as a file to groovy

Below is my JSON script.
PRAMS.json
{
"JSON" : {
"test": "iTEST",
"testname": "BOV-VDSL-link-Rateprofile-CLI-Test-1",
"params": [
{
"n2x_variables / config_file": "C:/Program Files (x86)/Agilent/N2X/RouterTester900/UserData/config/7.30 EA SP1 Release/OSP Regression/BOV/Bov-data-1-single-rate-profile.xml"
},
{
"n2x_variables / port_list": "303/4 303/1"
}
]
}
}
Below is my groovy script and I am sending params.json script to the same groovy script.
parseJSON.groovy
import groovy.json.JsonSlurper
def jsonFile = new File("../var/PARAMS.json")
def keys = new JsonSlurper().parse("jsonFile.text")
println keys.keySet()
I am getting below error :
****No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile.text]****
Can any one please help me ?
Thanks for reply, I am new to this json.
I am unable to share screen shot, showing error message when I am trying to upload image but i can give total error message :
developer#cn-vm-yourname:~/Desktop/kramdeni/vars$ groovy parseJSON.groovy
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile]
Possible solutions: parse(java.io.Reader), parseText(java.lang.String), use([Ljava.lang.Object;), wait(), grep(), any()
groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile]
Possible solutions: parse(java.io.Reader), parseText(java.lang.String), use([Ljava.lang.Object;), wait(), grep(), any()
at parseJSON.run(parseJSON.groovy:3)
developer#cn-vm-yourname:~/Desktop/kramdeni/v
and my expected output is to print only all values without keys in required order.
To get above result I wrote groovy script like below :
import groovy.json.JsonSlurper
label = "test testname params"
def jsonFile = new File('PARAMS.json')
def par = new JsonSlurper().parse(jsonFile)
println keys.keySet()
def command = ""
keys = label.split(" ")
println "keys: " + keys
for (key in keys) {
command += par[key] + " "
}
println "command: " + command
import groovy.json.JsonSlurper
def src = new File("MYPATH/MY.json")
//next line downloads json from URL:
//def src = new URL("http://date.jsontest.com")
def json = new JsonSlurper().parse( src.newInputStream() )
json.each{ k,v-> println "$k = $v" }
try it:
https://groovy-playground.appspot.com/#?load=ccceffd570c6ee176bc6f1fcdafdcbe0
if you have exception
groovy.lang.MissingMethodException: No signature of method:
groovy.json.JsonSlurper.parse() is applicable for argument types:
(java.io.BufferedInputStream)
Possible solutions: parse(java.io.Reader) ...
that means you have quite old version of groovy, however it suggests solution - try to get reader from file:
def src = new File("MYPATH/MY.json")
def json = new JsonSlurper().parse( src.newReader("UTF-8") )
json.each{ k,v-> println "$k = $v" }
but to continue you have to find version of your groovy, then find documentation for your version and continue developing referencing it
for example in groovy 1.8.6 there are only two parse methods in JsonSlurper:
http://docs.groovy-lang.org/1.8.6/html/api/groovy/json/JsonSlurper.html
and in the latest groovy much more...
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonSlurper.html

Unable to use json parsed object in another call in jmeter?

I am using jsr223 assertion with groovy script ,I am saving the parsed response as variable
def slurper = new groovy.json.JsonSlurper();
def t1= prev.getResponseDataAsString();
def response = slurper.parseText(t1);
vars.putObject("Summary", response);
Now I want to use this Summary variable in another call, so that I can assert it
def nn = ${SummaryJDBC};
But I am getting this error
jmeter.threads.JMeterThread: Error while processing sampler
'Competitive_Landscape(Past_awardees)' : java.lang.ClassCastException:
java.util.ArrayList cannot be cast to java.lang.String
You should use the getObject() method:
nn = vars.getObject("SummaryJDBC")

Groovy file check

I am a java fresher and I went to an interview recently. They asked a question which was something like: Set up Groovy, test whether a sample json file is valid or not. If it is valid, run the json file. If it is not, print "File is not valid". If file is not found, print "file not found". I was given 2 hours time to do it and I could use the internet.
As I had no idea what groovy was or json was, I searched it and set up groovy but could not obtain the output in two hours. What should I have written? I tried some code but I am sure that it was wrong.
You can use file.exists() to check if the file exists on the filesystem and file.canRead() to check if it can be read by the application. Then use JSONSlurper to parse the file and catch JSONException if the json is invalid:
import groovy.json.*
def filePath = "/tmp/file.json"
def file = new File(filePath)
assert file.exists() : "file not found"
assert file.canRead() : "file cannot be read"
def jsonSlurper = new JsonSlurper()
def object
try {
object = jsonSlurper.parse(file)
} catch (JsonException e) {
println "File is not valid"
throw e
}
println object
To pass the file path argument from the command line, replace def filePath = "/tmp/file.json" with
assert args.size == 1 : "missing file to parse"
def filePath = args[0]
and execute on the command line groovy parse.groovy /tmp/file.json

No JSON object could be decoded

while running this script i am getting the following error...
ERROR: getTest failed. No JSON object could be decoded
My code is:
import json
import urllib
class test:
def getTest(self):
try:
url = 'http://www.exapmle.com/id/123456/'
json_ = urllib.urlopen(url).read()
self.id = json.loads(json_)
print self.id
except Exception, e:
print "ERROR: getTest failed. %s" % e
if __name__ == "__main__":
ti = test()
ti.getTest()
while opening this url "http://www.exapmle.com/id/123456/" in browser i am getting json format data, but why it is throwing an error?
Print the json_ before calling json.loads(). If there is in an error in your url, urllib does not necessarily throw an exception, it might just retrieve some error page (like with the provided url), that is not valid json.