Assertion in json response - json

I am getting below json response:
{"participantUID": "000000000004871"}
I want to do assertion on participantUID.
My code:
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
assert jsonSlurper.participantUID == expectedparticipant
but I am getting error: groovy.lang.MissingPropertyException: No such property:
Please help me out. thanks

I'm not completely sure since you don't copy the complete MissingPropertyExceptionMessage in your question but since you're accessing correctly the response content using messageExchange context variable the problem is probably that you're not defining the expectedparticipant in your Script assertion try with:
def ResponseMessage = messageExchange.response.responseContent
def expectedparticipant = '000000000004871'
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
assert jsonSlurper.participantUID == expectedparticipant

Related

facing difficulties in Json parsing in groovy

I have a json and its response is {"canMerge":false,"conflicted":true,"outcome":"CONFLICTED","vetoes":[{"summaryMessage":"Requires approvals","detailedMessage":"You need 2 more approvals before this pull request can be merged."}]}
and I want to filter out data on the basis of "outcome":"CONFLICTED" for this I have tried following ways-
def mergeResponse = readJSON file:mergeFileName
for(mergenew in mergeResponse.values)
{
if(mergenew.outcome == "CONFLICTED") {
echo "pull request can not merged"
}
when I am trying above it is skipping if loop directly eventhough condition match properly I am not getting why?
ALSO TRIED BELOW
import groovy.json.JsonSlurper
def slurper = new JsonSlurper().parseText(mergenew)
assert slurper.outcome == "CONFLICTED"
String id = mergenew.getString("id");
echo "pull request can not merged"
getting error for above is
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseFile() is applicable for argument types: (org.apache.commons.collections.map.ListOrderedMap$ListOrderedMapEntry) values: [canMerge=false]
Possible solutions: parse([B), parse([C), parse(java.io.File), parse(java.io.InputStream), parse(java.io.Reader), parse(java.net.URL)
I also approved script in jenkins script approval for JsonSlurper.parseText
Please help me. Any help is appreciated.
try this : (set the file name var to whatever the file is)
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
data = jsonSlurper.parse(new File(mergeFileName))
assert data.outcome == "CONFLICTED"
println("pull request can not merged")
You can use Pipeline Utility Steps to read a json file. This works for me:
def data = readJSON file: "${WORKSPACE}/data.json" // here just read the json file
def outcome = "${data.outcome}"
if(outcome == "CONFLICTED") {
echo "pull request can not merged"
}

Parsing JSON on Jenkins Pipeline (groovy)

I created a method as shown online:
#NonCPS
def parseJsonString(String jsonString) {
def lazyMap = new JsonSlurper().parseText(jsonString)
// JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
def m = [:]
m.putAll(lazyMap)
return m
}
But I get the following error:
ERROR: java.io.NotSerializableException: groovy.json.internal.LazyMap
To work around this, I have to create an entire method to perform an entire step. For instance, in a method, I would do the same as above, parse the information I want, and finally return it as a string.
This, however, presents another issue, especially if you wrap this method inside a withCredentials, which would then require another withCredentials.
I finally find a BETTER solution!
readJSON() method from the Jenkins "Pipeline Utility Steps" plugin as shown here:
https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace
Here is a sample where we can finally ditch that ugly GROOVY JSONPARSE crap.
node() {
stage("checkout") {
def jsonString = '{"name":"katone","age":5}'
def jsonObj = readJSON text: jsonString
assert jsonObj['name'] == 'katone' // this is a comparison. It returns true
sh "echo ${jsonObj.name}" // prints out katone
sh "echo ${jsonObj.age}" // prints out 5
}
}

Django Invalid JSON Response

The following code produces the JSON given below. But when I validate it from JSON lint, it is invalid. What am I doing wrong here?
def json_candidate_get(request, model, m_id=None):
response = {'message' : 'Incorrect Json'}
try:
obj = model.objects.filter(pk=m_id)
ce = Candidate_profiles.objects.filter(pk=m_id)
cw = Candidate_company_profiles.objects.filter(pk=m_id)
response = json.dumps({ 'TechnologiesValue':[],'Technologies': [] })
except Exception as e:
logging.exception("Exception"+str(e))
return response
#is_login()
def candidate_create(request,m_id=None,token=None):
response_data = {'message': 'unsuccessfull'}
if token is not None:
try:
if request.method == 'GET':
response_data = json_candidate_get(request,Candidates,m_id)
print response_data
#response_data = serializers.serialize('json', response_data)
except Exception as e:
logging.exception(e)
return HttpResponse(response_data, content_type="application/json")
JSON:
{
TechnologiesValue: [0]
Technologies: [0]
}
The json.dumps function is meant to convert certain Python objects to a a JSON string. But you are already serializing your model instances (via QuerySets) to JSON strings, and json.dumps is trying to convert these strings into JSON all over again--it only knows that you've passed it str objects, not that these str objects represents JSON.
The JSON encoder used by json.dumps only knows how to convert a handful of built-in types:
Python 2
Python 3
So what you need to do is convert your model instances to one of these types. The easiest solution would be to use django.forms.models.model_to_dict on each element of your QuerySets, like so:
from django.forms.models import model_to_dict
response = json.dumps({
'candidate': [model_to_dict(x) for x in obj],
'CandidateEducationProfile': [model_to_dict(x) for x in ce],
...
)

SoapUi Assertions - Use a string as a json path with groovy

I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response.
Suppose I have the following json response:
{
"path" : {
"field" : "My Wanted Value"
}
}
And from my text file I would have the following two strings :
path="path.field"
value="My Wanted Value"
I tried the following :
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
assert json.path==value;
But of course it doesn't work.
Any idea how can I get it done please?
Thank you
I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach:
import groovy.json.JsonSlurper
def path='path.field'
def value='My Wanted Value'
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step to
// find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Additionally I'm not sure if you're also asking how to read the values from a file, if it's also a requirement you can use ConfigSlurper to do so supposing you've a file called myProps.txt with your content:
path="path.field"
value="My Wanted Value"
You can access it using the follow approach:
import groovy.util.ConfigSlurper
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value
All together (json path + read config from file):
import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Hope this helps,

How to get specific content from JSON response using context.expand?

I'm trying to use context.expand to get response and specific content from within the response,
def response = context.expand( '${Ranks of documents with SSE hits reflects scores#Response}' )
I also need to get specific detail from within the response, say if response has an array of ranks:
"ranks":[2234, 1234]
How can get both values of ranks?
You can use JsonSlurper from the groovy script testStep, supposing you get the follow JSON:
{"ranks":[2234, 1234]}
from your code:
def response = context.expand( '${Ranks of documents with SSE hits reflects scores#Response}')
You can use the JsonSlurper as follows to get your "ranks" values:
import groovy.json.JsonSlurper
// here I use this JSON as example, but you can
// parse directly your response which you get with context.expand
def response = '{"ranks":[2234, 1234]}'
def jsonRoot = new JsonSlurper().parseText(response)
log.info jsonRoot.ranks[0]
log.info jsonRoot.ranks[1]
Hope this helps,
Internally, SoapUI will convert almost anything to XML. You could grab just that node with ${step_name#ResponseAsXml}, and then parse it however you need to. Something like:
def ranksString = context.expand( '${Ranks of documents with SSE hits reflects scores#ResponseAsXml#//*:ranks}' )
def ranksArray = ranksString.split(",").trim()
log.info ranksArray[0]
log.info ranksArray[1]