error seeing when parsing the json response using groovy - groovy

import groovy.json.JsonSlurper
def testStepName = 'Adding_Users'
def jsonSlurper = new JsonSlurper()
def response = context.expand('$(testStepName#Response)')
def usersInfomration = jsonSlurper.parseText(response)
String userName = userInformation.name
log.info UserName

Related

How do i mock an attribute within nested constructor using unittest

This is what i am trying to test :
src/DBOps.py
class DBOps() :
class dynamodbOps() :
def __init__(self,db_table) :
dynamodb = boto3.resource('dynamodb')
self.table = dynamodb.Table(db_table)
def GetDBItem(self,pool):
response = self.table.get_item(Key={'pool' : pool})
And this is the test case that is unsuccessful :
class test_GetDBItem(unittest.TestCase) :
def setUp(self):
self.db_ops = DBOps()
db_table = "test_table"
self.dyn = self.db_ops.dynamodbOps(db_table)
#mock.patch('src.DBOps')
def test_run_query_with_item(self, getItem_mock) :
getItem_mock.dynamodbOps.table.get_item.return_value = {"Blah":"Blah Blah"}
pool = 'some_pool'
response = self.dyn.GetDBItem(pool)
I am trying to mock the 'table.get_item' call and failing at it no matter what i try. Any pointers would be great!
Figured it out as below :
class test_GetDBItem(unittest.TestCase) :
def setUp(self):
db_ops = DBOps()
db_table = "test_table"
self.dyn = db_ops.dynamodbOps(db_table)
def test_run_query_with_item(self) :
with patch.object(self.dyn.table, 'get_item') as getItem_mock :
getItem_mock.return_value = {"Blah":"Blah Blah"}
pool = 'some pool'
response = self.dyn.GetDBItem(quadra_pool)

groovy - replace values in json when loading from jmx

I have a piece a code as below. This is loading data from JMX to monitoring tool. Unfortunately, there are some 'NaN' values, which are not read properly by monitoring tool, and this interrupts transfer. My intention is to replace 'on fly' values 'NaN' to 'null'.
Has anybody any idea how to do it?
BR
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import java.security.PrivilegedAction;
def hostName = hostProps.get("system.hostname")
def jmxPort = "10002"
def query = "Hadoop:service=hiveserver2,name=hiveserver2"
def metricsURL = "http://${hostName}:${jmxPort}/jmx?qry=${query}"
def ad = true
public class FetchMetrics implements PrivilegedAction {
def url;
public FetchMetrics(String url) {
this.url = url;
}
public Object run() {
URL urlObject = new URL(url);
def con = (HttpURLConnection) urlObject.openConnection();
return con.getInputStream();
}
}
lc = new LoginContext("Client");
lc.login();
Subject subject = lc.getSubject();
PrivilegedAction action = new FetchMetrics(metricsURL);
def metrics = Subject.doAsPrivileged(subject, action, null);
def jsonSlurper = new JsonSlurper()
def deviceMetrics = jsonSlurper.parse(metrics)
// Hit out endpoint and get our metrics
//deviceMetrics = jsonSlurper.parse(new URL(metricsURL))
deviceMetrics.'beans'[0].each {
println it
}
return 0
simplest way to use LAX json slurper, however it will parse NaN as a string "NaN"...
import groovy.json.JsonSlurper
import groovy.json.JsonParserType
import groovy.json.JsonBuilder
def jsonSlurper = new JsonSlurper().setType( JsonParserType.LAX )
def json = jsonSlurper.parseText('{ "a":111, "b": NaN}')
println new JsonBuilder(json).toPrettyString()
prints
{
"a": 111,
"b": "NaN"
}

Hit a URL using groovy step

I created a HTTP request step and checked the response code 200/400 .
The same i want to check using groovy only. No HTTP requeststep. Use only groovy step.
URL response script:-
def rawResponse = new String(testRunner.testCase.testSteps["HTTP Request"].testRequest.response.rawResponseData)
log.info rawResponse
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def httpResponseHeaders = context.testCase.testSteps["HTTP Request"].testRequest.response.responseHeaders
def httpStatus = httpResponseHeaders["#status#"]
def httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
log.info("HTTP status code: " + httpStatusCode)
if (httpStatusCode == "200")
{
log.info "Success"
}
else
{
log.info "Failure"
}

SOAPUI - Groovy scripting - jsonBuilder strips quotes

I have a problem where jsonBuilder strips quotes from the result string. How do I format the output to return a JSON response with quotes ?
import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.*
import groovy.json.JsonOutput
import net.sf.json.JSONObject
def ResponseMessage = testRunner.testCase.testSteps["MerchantEMS_POST"].testRequest.response.contentAsString
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
log.info ResponseMessage
def merchantResult = ResponseMessage
def newMerchantID = "60300004055"
def entityID = jsonSlurper.entityId
jsonSlurper.merchantId = newMerchantID
def jsonBuilder = new groovy.json.JsonBuilder()
def updatedjson = jsonBuilder(jsonSlurper)
log.info "updated JSON = $updatedjson"
return updatedjson
ResponseMessage : { "entityId" : "93LSHLXW7BJ5K00MJALWZJMLL0", "creatorId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "createdTimestamp" : "2015-09-02T00:26:34.015Z", "updaterId" : "HPCDKMSV763K2VGHCKQQ09QSGM", "updatedTimestamp" : "2015-09-02T00:26:34.015Z", "merchantId" : "L7QWKA0001F5W1RRZY4Z006153",
"createdBy" : "ralgg00", "isDeleted" : false }
updatedjson (no quotes) = [updatedTimestamp:2015-09-02T00:26:34.015Z, createdBy:ralgg00, createdTimestamp:2015-09-02T00:26:34.015Z, creatorId:HPCDKMSV763K2VGHCKQQ09QSGM, entityId:93LSHLXW7BJ5K00MJALWZJMLL0, merchantId:60300004055, isDeleted:false, updaterId:HPCDKMSV763K2VGHCKQQ09QSGM]
EDIT:
When you log the 'updatedjson' it recognises it as Map object and prints its fields. You need to use something that can convert a Map object to JSON and print it out. There are many ways to do this, for example:
def json = JsonOutput.toJson(updatedjson)
println json
Source: http://www.groovy-lang.org/json.html

How to add a node to groovy MarkupBuilder?

I am using MarkupBuilder to generate xml, need to know how can I add NodeChild to a MarkupBuilder Object
my code
def fxml=new File("E:\\Projects\\dom.xml")
def xmltext=new XmlSlurper(false,false).parseText(fxml.text)
or
def xml=new XmlSlurper(false,false).parse("E:\\Projects\\dom.xml")
def abc = new groovy.xml.MarkupBuilder()
abc.product(name:"Dota"){
language("Java")
language("Groovy")
language("JavaScript")
domainsinfa{delegate.current.appendNode( xmltext)}
}
You can use StreamingMarkupBuilder to insert arbitrary nodes to the xml:
import groovy.xml.*
def xmltext = '''<node><name short="yes">tim</name><fun>maybe</fun></node>'''
def xml = new XmlSlurper( false, false ).parseText( xmltext )
def newxml = new StreamingMarkupBuilder().bind {
product(name:"Dota") {
language("Java")
language("Groovy")
language("JavaScript")
mkp.yield xml
}
}
println XmlUtil.serialize( newxml )

Resources