if condition not displaying correct message after output - groovy

I am having a little issue with my if condition in groovy.
Virtually I want to look at a property value I've set and ensure that is every instance on the response delivered from the JSON contains the same value as the property value, then it should equal a match. Now when I log the location_id and location_id_request, I am getting the values expected. However, in my if statement it seems to still state that that the location id does not match, making me believe that my if condition is incorrect. What do I need to change my if condition to, to output the correct message.
Below is the code I have with the log information underneath:
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def location_id = json.reviews.location_id
assert location_id != null
def location_id_request = messageExchange.modelItem.testStep.testCase.getPropertyValue("locationid")
assert location_id.every {it == location_id_request}
log.info location_id_request
log.info location_id
if (location_id == location_id_request)
log.info "Good News, location match!"
else
log.info "Test has failed, location do not match!"
Log information in correct order:
location_id_request:INFO:000000
location_id:INFO:[000000, 000000, 000000, 000000, 000000]
if condition output:INFO:Test has failed, location do not match!

You compare a String (Number?) with List - it won't work. Instead, try to check if given location_id is present on location_id_request List:
if (location_id in location_id_request) { //... }

Related

Groovy assertion on SOAP UI for database output

Using SOAP UI I am running query and fetching data for an specific ID and after that I want to validate specific field and its corresponding Value which is returning .
Ex -
Version =2
So I want to validate that every time for the generated record the version is 2 .
I checked and came up with the below code but the Select query is giving me error ,where it is unable to read value returning from recordId variable which i am using in Where condition ,So how to resolve it ?
The below is the database result which i want to validate
here
def listOfPostedRecordIds = parser.parseText(context.expand( '${1.CreateTestData#IdsToBeDeleted}' ))
def **recordId**=listOfPostedRecordIds[0]
log.info "recordId is "+recordId
def Version = myDB.firstRow('''Select cast(("Research"."meta"#>>'{versionId}') as integer)as Version from "Research"where id= **("recordId")** ''')
log.info "The value of is ${Version}
To parameterize data in your SQL in Groovy, do it with a ? like this:
def recordId = listOfPostedRecordIds[0]
def Version = myDB.firstRow("""
Select cast(('ResearchSubject'.'meta'#>>'{versionId}') as integer) as Version
from 'ResearchSubject'
where id = ?;""", [recordId])
log.info "The value of is ${Version}"
Also note that your select is quite complicated with ", ', # >> and {}. Make sure all those are really required.

SOAPUI Square brackets around my actual results causing assert to fail

I am writing a Groovy script assertion which is verifying a value from a previous JDBC response step against a value contained in a SOAP response.
When I run my scripts I can see that both values are coming back the same but the actual result value (from the SOAP response) is surrounded by square brackets which in turn makes the assert fail. I'm guessing this is something to do with one being a string and one not?
How do I either strip out the square brackets from actual result or get them added to the expected result value to ensure the assert passes?
Below is my assert script.
Expected result is 001
Actual result is [001]
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = groovyUtils.getXmlHolder( messageExchange.responseContent )
def pxml = new XmlSlurper().parseText(context.response)
//grab the expected result from jdbc response
def expectedCodes = context.expand( '${JDBC Request#ResponseAsXml#//*:TW304_PRODHIST.PRODUCT_1}' )
//grab the actual result from the SOAP response
def actualCodes = pxml.'**'.findAll{it.name() == 'CurrHospProductCode'}*.text()
assert expectedCodes == actualCodes
log.info expectedCodes
log.info actualCodes
Because you are expecting a single value as expected where as you are getting an array with single element in it.
You can do it as below if that is right :
assert expectedCodes == actualCodes[0]
On a side note, you may have to check carefully are you really expecting single value only or if there is possible to get list of values.
EDIT: based on your script.
findAll gives you list as result. If you are expecting single element in the xml, then you can change it to find and then you actual code should work as it is.

How to pick up child element of specific parent element in Script Assertion?

I have the following XML example which shows there are multiple occurrences of node 'ProductCode' which fall under both nodes 'PrevHospProduct' and also under 'PrevExtrasProducts'.
<ns2:PrevHospProducts>
<ns2:PrevHospProduct>
<ns2:ProductCode>D00</ns2:ProductCode>
<ns2:ExcessPaid>Yes</ns2:ExcessPaid>
</ns2:PrevHospProduct>
<ns2:PrevHospProduct>
<ns2:ProductCode>900</ns2:ProductCode>
</ns2:PrevHospProduct>
</ns2:PrevHospProducts>
<ns2:PrevExtrasProducts>
<ns2:PrevExtraProduct>
<ns2:ProductCode>00A</ns2:ProductCode>
</ns2:PrevExtraProduct>
</ns2:PrevExtrasProducts>
For this test I am only interested in the values in 'ProductCode' which are a child of 'PrevHospProduct'. I am not interested in any of the values under 'PrevExtrasProducts'.
I have the following Groovy Script Assertion in SoapUI to pick up values in 'ProductCode' but the test is failing as the actual results are also returning 'D00', '900' and '00A' from the examples response. I only want the expected results to pick values 'D00', '900'.
def expectedCodes = ['D00','900']
def pxml = new XmlSlurper().parseText(context.response)
def actualCodes = pxml.'**'.findAll{it.name() == 'ProductCode' }*.text() as List
assert expectedCodes.sort() == actualCodes.sort()
First need to find the parent node i.e., PrevHospProduct and then get the ProductCode.
Here is the script assertion:
def expectedCodes = ['D00','900']
def pxml = new XmlSlurper().parseText(context.response)
def actualCodes = pxml.'**'.findAll{it.name() == 'PrevHospProduct'}*.ProductCode*.text() as List
log.info actualCodes
assert expectedCodes.sort() == actualCodes.sort()

Assert multiple values in an XML response received on querying DB in SOAP UI

I am trying to retrieve some data from db and based on the response, I have to pass or fail a test case. I have to do this each time I query the db
I am able to make the connection to the db and get the response. However, not quite sure on how to assert the values from the response
Tried to use Script Assertion but not able to figure out as I am completely new at this
<Results>
<ResultSet fetchSize="10">
<Row rowNumber="1">
<T1>TEXT1</T1>
<T2>TASK1</T2>
<T3>Value1</T3>
<T4>xyz</T4>
</Row>
<Row rowNumber="2">
<T1>TEXT2</T1>
<T2>TASK2</T2>
<T3>Value1</T3>
<T4>ABC</T4>
</Row>
</ResultSet>
From the above response, on the first step I will have to assert that "TASK1" exists and the "Value1" exists with in the same set followed by the "TASK2" and "Value1"
Please let me know if this is vague so that I can try to modify my query
Use Xpath assertion instead
Assertion 1
/Results/ResultSet[#fetchSize="10"]/Row[1]/T1
Expected result
Task1
Assertion 2
/Results/ResultSet[#fetchSize="10"]/Row[1]/T3
Expected result
Value1
You can add as many Xpath Assertion as you want for any number of nodes.
Quick Tip: To generate XPaths use online tools or Oxygen XML Editor. :)
You can use Script Assertion for the JDBC Request test step in soapUI.
Script assertion
//define your expected data as map. You may add more key value pairs if more Rows
def expectedData = ['TASK1':'Value1', 'TASK2':'Value1']
//Assert if the response is not null
assert context.response, 'Response is not null or empty'
//Parse and get rows
def rows = new XmlSlurper().parseText(context.esponse).ResultSet.Row
def getRowData = { data, elementName, elementValue ->
data.'**'.findAll { it.name() == elementName && it == elementValue }*.parent()
}
def assertionErrors = new StringBuffer()
//Loop thur expectedData and capture the errors
expectedData.each { key, value->
def matchingRow = getRowData(rows, 'T2', key)[0]
value == matchingRow.T3.text() ?: assertionErrors.append("Assertion failed for rowNumber ${matchingRow.#rowNumber}\n")
}
//Check and show the result
if (assertionErrors) {
throw new Error(assertionErrors.toString())
} else {
log.info 'Assertions passed'
}
You may quickly try the solution online Demo; it shows how failure error message look like.
Note that, column names T2, T3are used in above script. If the names are different in original result, just make the change at your end.
Also note that assertion is not used deliberately to catch all the comparison issues, do not want to stop at first compare issue.
Try XmlSlurper: http://groovy-lang.org/processing-xml.html
To check TASK1:
def results = new XmlSlurper().parseText(response)
def row1 = results.ResultSet.find { node->
node.name() == 'Row' && node.#rowNumber == '1'
}
assert row1.T2 == 'TASK1'
I hope you'll be able to do the rest by your own ;)

Setting json key using bind variables in groovy

I've this code by which I am trying to set the value of a Key (a json node id). But its not setting the value. Log.info statement is showing right values.
Key= context.expand( '${#Project#key}' )
Value= context.expand( '${#Project#value}' )
Binding binding = new Binding()
binding.setVariable("v", "$Value")
binding.setVariable("k", "$Key")
log.info(binding.getVariable("v")) // gives me the value 1234
log.info(binding.getVariable("k")) // gives me the value request.id
def SetKey = new GroovyShell(binding).evaluate( "k=v")
Can someone please comment on whats wrong in this code. and how can I correct it.
Edit: Explanation of the issue
In SoapUI I've some json nodes saved in data source like this request.id and request.app.id and there expected values in Value column which I am fetching through Key and Value above. I am hoping to change the value of a json node to its respective value at run time. So for each iteration of data source, it should set the correct value of that particular json node. Befor the above code I've parsed my json request by json slurper and after the above code I am building the json again by Json builder and running the request. Parsing and running the request works fine, its just that I couldnt set the value of the json node.
If your keys are just dotted names, you could simply use some string manipulation, no need to involve the Groovy parser.
For example, if they all begin with request:
def steps = Key.split(/\./)
if (steps.size() < 2 || steps[0] != 'request') {
throw ...
}
def obj = request
if (steps.size() > 2) {
steps[1..-2].each {
obj = obj[it]
}
}
obj[steps[-1]] = Value

Resources