I have a json file with values - {"testID":"smoke_01","testID":"smoke_02","testID":"smoke_04"}.
I read the values for testID and saved to array. Now I was trying to make it as a simple string like -
testcase = smoke_01,smoke_02,smoke_02. My code is below :
def props = readJSON file: 'input.json'
def list = []
props.each { key, value ->
list.push("$value")
}
echo "$list"
def asString = list.join(", ")
def testcase = asString.join(", ")
But when i print testcase - its printing as [smoke_01, smoke_02, smoke_04] . Please help me to understand where I am wrong.
Assuming you really have this invalid strange JSON (keys must be unique in an Object in basically every language you parse to, but yours are not), and that readJSON actually parses your custom JSON into something you can iterate over as if it were a Map... then, this should do what you want:
def props = readJSON file: 'input.json'
def testCase = props.values().join(', ')
println testCase
Assuming you use proper JSON
By proper JSON I mean something that does not break JSON semantics, hence can be parsed by any JSON parser, not your custom one.
You JSON file should look more like this:
{ "tests": [
{ "testID": "smoke_01" },
{ "testID": "smoke_02" },
{ "testID": "smoke_03" }
] }
In which case you would parse it with:
def json = new JsonSlurper().parse(new File('input.json'))
def testCase = json.tests.collect { it.testID }.join(', ')
println testCase
There are other ways to represent this in JSON, but you should study how JSON works and what suits you best depending on how it is going to be used.
Here's the JSON spec which is simple enough you can learn it in 20 minutes:
https://www.json.org/json-en.html
Related
I need to take my output from the for loop below and add it to a single array. The list object can either be ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"] or ["envName-inactive-2", "", "", "envName-active-2"]
My code:
if (appendVersion) {
for (elements in list) {
test = (elements + "-" + branch)
println(test)
}
} else {
println(list)
}
output:
envName-inactive-1-v2
active-1-v2
inactive-1-v2
envName-active-1-v2
and
envName-inactive-2-v2
-v2
-v2
envName-active-2-v2
desired output:
["envName-inactive-1-v2", "active-1-v2", "inactive-1-v2", "envName-active-1-v2"]
and
["envName-inactive-2-v2", "", "", "envName-active-2-v2"]
You desired format seems to be json. In Jenkins you have option to use writeJSON to convert list to json format.
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = writeJSON returnText: true, json: versionedList
println json
the same in plain groovy:
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = new groovy.json.JsonBuilder(versionedList).toString()
println json
result:
["envName-inactive-1-v2","active-1-v2","inactive-1-v2","envName-active-1-v2"]
I am trying to pass a dictionary (loaded from JSON file) to format string. While single key-value unpack works correctly, I am not sure how I can access the nested keys (children) with a format string.
Or is there any other better way to pass JSON to string format?
config = {
"TEST": "TEST",
"TEST1": "TEST1",
"TEST2": {
"TEST21": "TEST21"
}
}
query_1 = """
{TEST} {TEST1}
"""
query_2 = """
{TEST} {TEST1}
{TEST2.TEST21}
"""
print(query_1.format( **config )) # WORKING
print(query_2.format( **config )) # NOT WORKING
Using f-string
config = {
"TEST": "TEST",
"TEST1": "TEST1",
"TEST2": {
"TEST21": "TEST21"
}
}
query_2 = f"""
{config['TEST']} {config['TEST1']}
{config['TEST2']['TEST21']}
"""
print(query_2)
Note, if query is sql query, there is probably better way to do what you do, not using string formatting
In your query_2 change {TEST2.TEST21} to {TEST2[TEST21]} it will work.
Ex.
query_2 = """
{TEST} {TEST1}
{TEST2[TEST21]}
"""
print(query_2.format(**config))
Output
TEST TEST1
TEST21
I am trying to create a groovy script assertion in SoapUI. In the response, I and trying to pull a field called written. however there are +15 of these fields.
I is possible to add the XPath to the XmlSlurper to find the exact written fields I want to assert against.
Looking at the XML response below, I would like to assert the value in b:premium\written. not the one from the b:other. Given there are 15+ b:written fields i would like to assert the value using the xpath.
XML Response:
<s:Body>
<NewRateResponse>
<NewRateResult>
<b:policies>
<b:other>
<b:written>00.00</b:written>
</b:other>
<b:premium>
<b:written>31.21</b:written>
</b:premium>
</b:policies>
</NewRateResult>
</NewRateResponse>
</s:Body>
Assertion Code:
import org.junit.Assert
def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def nodePremium = xml.'**'.find { it.name() == 'written'}
Assert.assertEquals(00.01, nodePremium.toDouble(),0)
I believe the area we need to change is def nodePremium = xml.'**'.find { it.name() == 'written'}. to be something like def nodePremium = xml.'**'.find { it.name() == 'premium\written'} but that does not work for me.
assert xml.'**'.find { it.name() == 'premium'}.written.text() as Double == 31.20
I am trying to assert the response, to check if the response value starts with a certain text. I tried using the function startsWith but it seems like it does not work in SOPAUI script assertion.
This is what I have tried:
import groovy.json.JsonSlurper
//grab the response
def ResponseMessage = messageExchange.response.responseContent.records
//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//log.info jsonSlurper
assert jsonSlurper.startsWith("Text")
Here is the json response
{
"Name": "Natalie",
"message": "What are you doing"
}
I want to check if the Name starts with "Nat"
From documentation JsonSlurper().parseText(String text) returns:
data structure of lists and maps
so you can not use startsWith directly. To achieve what you want you have to go to the desired object in the path and use startsWith there. Something like must works for your case:
import groovy.json.JsonSlurper
def jsonStr = '{ "Name": "Natalie", "message": "What are you doing" }'
def jsonSlurper = new JsonSlurper().parseText(jsonStr)
assert jsonSlurper.Name.startsWith("Nat")
Concerning soapUI and groovy, I'm trying to get assertion (working) and response both in XML into a variable. I get the error
groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.getResponseAsXml() is applicable for argument types: () values: [] error at line: 6
I have tried adding import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep but still cant figure it. I did another attempt with message exchange, also to no avail - from what i understand you can't actually use messageExchange in this particular instance
import com.eviware.soapui.model.testsuite.Assertable.AssertionStatus
def TestCase = testRunner.getTestCase()
def StepList = TestCase.getTestStepList()
StepList.each
{
if(it.metaClass.hasProperty(it,'assertionStatus'))
{
if(it.assertionStatus == AssertionStatus.FAILED)
{
def ass = it.getAssertableContentAsXml()
def res = it.getResponseContentAsXml()
log.error "${it.name} " + "${it.assertionStatus}"
log.info ass + res
}
}
}
If you want to get the response from com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep, a possible way is first get the testStep from this class using getTestStep() method.
This method returns a object of class com.eviware.soapui.model.testsuite.TestStep, from this object you can get the testSteps properties like request, response, endpoint... using getPropertyValue(java.lang.string) method.
So in your case to get the response use:
def res = it.getTestStep().getPropertyValue('Response')
instead of:
def res = it.getResponseContentAsXml()
As #tim_yates comments the exception description in this case it's pretty clear, so please take a look at the SOAPUI api and at the links provided in the answer for the next time :).
Hope this helps,