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

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")

Related

Failing to test POST in Django

Using Python3, Django, and Django Rest Frameworks.
Previously I had a test case that was making a POST to an endpoint.
The payload was a dictionary:
mock_data = {some data here}
In order to send the data over the POST I was doing:
mock_data = base64.b64encode(json.dumps(mock_data).encode('utf-8'))
When doing the POST:
response = self.client.post(
'/some/path/here/', {
...,
'params': mock_data.decode('utf-8'),
},
)
And on the receiving end, in validate() method I was doing:
params = data['params']
try:
params_str = base64.b64decode(params).decode('utf-8')
app_data = json.loads(params_str)
except (UnicodeDecodeError, ValueError):
app_data = None
That was all fine, but now I need to use some hmac validation, and the json I am passing can no longer be a dict - its ordering would change each time, so hmac.new(secret, payload, algorithm) would be different.
I was trying to use a string:
payload = """{data in json format}"""
But when I am doing:
str_payload = payload.encode('utf-8')
b64_payload = base64.b64encode(str_payload)
I cannot POST it, and getting an error:
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'ewog...Cn0=' is not JSON serializable
even if I do b64_payload.decode('utf-8') like before, still getting similar error:
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'\xa2\x19...\xff' is not JSON serializable
Some python in the terminal:
>>> d = {'email': 'user#mail.com'} # regular dictionary
>>> d
{'email': 'user#mail.com'}
>>> dn = base64.b64encode(json.dumps(d).encode('utf-8'))
>>> dn
b'eyJlbWFpbCI6ICJ1c2VyQG1haWwuY29tIn0='
>>> s = """{"email": "user#mail.com"}""" # string
>>> s
'{"email": "user#mail.com"}'
>>> sn = base64.b64encode(json.dumps(s).encode('utf-8'))
>>> sn
b'IntcImVtYWlsXCI6IFwidXNlckBtYWlsLmNvbVwifSI=' # different!
>>> sn = base64.b64encode(s.encode('utf-8'))
>>> sn
b'eyJlbWFpbCI6ICJ1c2VyQG1haWwuY29tIn0=' # same
The issue is resolved.
The problem was NOT with the payload, but with a parameter I was passing:
signature': b'<signature'>
Solved by passing the signature field like this:
'signature': signature_b64.decode('utf-8')
Thank you!

JMeter Assertion failure with groovy

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.

Parsing the response Json string using groovy

4 for checking the status of the process using httpbuilder and getting the below response.
{"result":[{"id":"167687","dapadmin":"false","status":"in progress","lastupdated":"2017-04-21 14:34:30.0","started":"2017-04-21 14:34:28.0","user":"sys","log":"Running a Stop action\n\nRunning command \n"}]}
Am unable to parse this response using jsonSlurper.parseText() giving error
When I use `
def json = JsonOutput.toJson(statusresponse)
println JsonOutput.prettyPrint(json)
I could see it is printed as json object
{
"result": [
{
"id": "167687",
"dapadmin": "false",
"status": "in progress",
"lastupdated": "2017-04-21 14:34:30.0",
"started": "2017-04-21 14:34:28.0",
"user": "dapsystem",
"log": "Running a Stop action\n\nRunning command \n"
}
]
}
When i check the getClass() , it prints as java.lang.String.
I need to get the lastupdated and status , id values from this response. Please help me to find a solution for this.
Many thanks
Hi Yanpei.
Thanks for the response.
I am using the below code as suggested by you.
def statusresponse = http.putText(baseurl,path,query,headerMap, Method.GET)
println("The status response value is" )
statusresponse.each{ k, v ->
println "${k}:${v}"
}
def json = JsonOutput.toJson(statusresponse)
println "JSON Object List : " + json
println "------------------"
println JsonOutput.prettyPrint(json)
println "The result class is "+json.getClass()
println "The result status is "+(json instanceof Map)
//def entry = slurper.parseText(json)
def slurper = new groovy.json.JsonSlurper()
def entry = slurper.parseText(statusresponse)
def lastupdated = entry.result.lastupdated
checkStatus = entry.result.status
def id = entry.result.id
Am getting the below error
The result class is class java.lang.String
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.HashMap) values: [[result:[[id:170089, dapadmin:false, status:in progress, ...]]]]
Possible solutions: parseText(java.lang.String), parse(java.io.Reader)
groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.HashMap) values: [[result:[[id:170089, dapadmin:false, status:in progress, ...]]]]
Possible solutions: parseText(java.lang.String), parse(java.io.Reader)
at dap.Main.main(Main.groovy:171)
It works if i use the code as below
def json = JsonOutput.toJson(statusresponse)
def entry = slurper.parseText(json)
Am getting the results as below
The status of the action is :[in progress]
Last updated [2017-04-23 17:08:02.0]
the id is[170088]
First of all, am not sure why the code suggested is throwing this error
Secondly, why i am getting the results for the working solution, within the brackets?
def slurper = new groovy.json.JsonSlurper()
def entry = slurper.parseText('{"result":[{"id":"167687","dapadmin":"false","status":"in progress","lastupdated":"2017-04-21 14:34:30.0","started":"2017-04-21 14:34:28.0","user":"sys","log":"Running a Stop action\n\nRunning command \n"}]}')
def lastupdated = entry.result.lastupdated
def status = entry.result.status
def id = entry.result.id
Should work. Can't see your error so I can't give better info.

Soapui Script Assertion, when Json response return as string

My Json response(which return as string),
"[{\"Serial\":5,\"Name\":\"hold\",\"Types\":[{\"Serial\":36,\"Id\":5,\"Data\":true}]}]"
My Script Assertion,
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//verify the slurper isn't empty
assert !(jsonSlurper.isEmpty())
assert jsonSlurper.Serial == 5
But I'm getting an error
"A JSON payload should start with an openning curly brace '{' or an openning square bracket '['.
Instead, '"[{\"Serial\":5,\"Name\":\"hold\",\"Types\":[{\"Serial\":36,\"Id\":5,\"Data\":true}]}]"' was found on line: 1, column: 1"
How to fix this script, I just want to assert that my response should not be empty and Serial is equal to 5.
So I have fixed my own problem by simple regular expressions.
Here is the code guys,
//imports
import groovy.json.JsonSlurper
//grab the response
def ResponseMessage = messageExchange.response.responseContent
def TrimResponse =ResponseMessage.replaceAll('^\"|\"$','').replaceAll('^ \\[|\\]$','').replaceAll('\\\\','')
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(TrimResponse)
//verify the slurper isn't empty
assert !(jsonSlurper.isEmpty())
assert jsonSlurper.Serial != null
assert jsonSlurper.Serial == 5
assert jsonSlurper.Types[0].Serial == 36
Enjoy :)

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.