Error in groovy script - json

show this msg for me
groovy.lang.MissingMethodException: No signature of method: java.io.File.write() is applicable for argument types: (java.lang.Integer, java.lang.String) values: [62, UTF-8] Possible solutions: write(java.lang.String, java.lang.String), write(java.lang.String), wait(), size(), canWrite(), wait(long)
and code is
import groovy.json.JsonSlurper
requestTestStepName = "Criar/Login Usuario 1"
responseContent = testRunner.testCase.getTestStepByName(requestTestStepName).getPropertyValue("response")
response = new JsonSlurper().parseText(responseContent)
userId = response.userId
new File( "C:/tc/json/userId_H24_userid.txt" ).write(userId, "UTF-8")

The answer is staring at you from the really helpful error message..
You need to wrap your 62 userid up as a String:
new File( "C:/tc/json/userId_H24_userid.txt" ).write("$userId", "UTF-8")

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 can I compare two test steps Json results!? in one test case with Groovy script?soapUI

I do appreciate if anyone can help me with this error ,tried to compare Json responses in two test steps of one of my test cases.
the first step adds a task, and the second step gets a list of all tasks.
all I have in my Json file from first step is a number which is the TaskId of last added task. and i need to check in the second test step Json response whether that taskid exists or no?
My Groovy assertion is :
import groovy.json.JsonSlurper
def Response1 = context.expand( '${#ApiSmartsTaskPhysicalsPost - add an
Unplanned task#Response}' );
def JSON1 = new JsonSlurper().parseText Response1;
log.info JSON1
def Response2 = context.expand( '${#ApiSmartsTaskPhysicalsGet -Check if
values have been updated#Response}' );
def JSON2 = new JsonSlurper().parseText Response2;
log.info JSON2
assert JSON1 == JSON2
but I am getting this error :
" java.lang.illegalargumentexception:Text must not be null ,error at
line:3 "
is there any chance to direct me to get solve this issue ? checked the end points they are the same and the URL is correct.
solved I could fix it :
import groovy.json.JsonSlurper
def Response1 = context.expand( '${ApiSmartsTaskPost - add an
Unplanned task#Response}' );
def JSON1 = new JsonSlurper().parseText(Response1);
log.info JSON1
def Response2 = context.expand( '${ApiSmartsTasksGet -check if task
has been added#Response}'.toString() );
def JSON2 = new JsonSlurper().parseText(Response2);
log.info JSON2
assert JSON2.taskid.contains(JSON1), "Task has not been created!"`

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

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!

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.