Hi In Groovy I need to remove part of string
the string.
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
should look like " Updated User id:nish.test11
how can i do that?
As the content looks like an XML,
def xml = """
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
"""
it's better to use XmlSlurper than parsing/extracting strings by hand
def result = new XmlSlurper().parseText(xml)
println result.toString()
this gives the desired result (the content of the Result)
If I run the code:
""" <Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>""".replaceAll( /<\/?[^<>]>/, '' ).replaceAll( /[\n\s]+/, ' ' )
it gives me
Updated User id:nish.test11
as output
Related
I need to compare two strings in SoapUI. The first one is from a text file stored in my local directory, and the second one is from an XML response I get from a REST API operation. Before comparing the two strings, I use some methods on them to remove the header because they contain information like Dates and Processing Time which is sure to be different each time.
Below is what I've tried.
def xml = messageExchange.responseContentAsXml
String fileData = new File("C://Users/362784/project/outputPGB123.txt").text
String responseContent = new XmlSlurper().parseText(xml)
String fileDataFiltered = fileData.substring(fileData.indexOf("PASSED :"))
String responseContentFiltered = responseContent.substring(responseContent.indexOf("PASSED :"))
log.info(fileDataFiltered)
log.info(responseContentFiltered)
assert fileDataFiltered == responseContentFiltered
Here is the error I received
SoapUI error message
and my two identical log.info
log.info
Here's what the XML response looks like
I am new to SoapUI and I'm not sure what those two are actually comparing but I've checked the log.info of them on https://www.diffchecker.com/diff and the contents are identical. However, this assertion returns an error.
Can anyone point out what I did wrong and how do I get the result as passed?
In Java/Groovy you compare string values for equality like this:
assert fileDataFiltered.equals(responseContentFiltered)
See if that solves your problem.
The == comparator could, for example, compare object instances which could fail even if the text values are identical. See here for a more in-depth explanation.
EDIT:
Having seen your sample, it looks like the value you are comparing is inside XML character data (CDATA).
Consider the following example from here:
Some XML:
def response = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sam="http://www.example.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:searchResponse>
<sam:searchResponse>
<item><id>1234</id><description><![CDATA[<item><width>123</width><height>345</height><length>098</length><isle>A34</isle></item>]]></description><price>123</price>
</item>
</sam:searchResponse>
</sam:searchResponse>
</soapenv:Body>
</soapenv:Envelope>
'''
Then access the CDATA node with XmlSlurper:
def Envelope = new XmlSlurper().parseText(response)
def cdata = Envelope.Body.searchResponse.searchResponse.item.description
log.info cdata
log.info cdata.getClass()
assert cdata instanceof groovy.util.slurpersupport.NodeChildren
As you can see, the value returned is of object NodeChildren. You can convert it to a string with:
log.info cdata.toString()
log.info cdata.toString().getClass()
So let's do a comparison (as per cfrick's comment, you can use == or .equals())
def expectedCdata = '<item><width>123</width><height>345</height>length>098</length><isle>A34</isle></item>'
if (cdata.toString().equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}
It still fails ???
Well, that is because of a residual newline that isn't obvious from printing with log.info, if you remove whitespace it works in this case:
if (cdata.toString().replaceAll("\\s","").equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}
As you can see, there are many levels of possible failure. You have to work through it.
I am getting the value of a field as ["value"]
I want to print only the value removing the [ "from the result value.
That looks like a JSON array of Strings? No idea, as you don't provide any context, but you could do:
import groovy.json.JsonSlurper
def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()
println result
Prints value
The following script should be what you need
def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))
I have one test case which is called (started and finished) before every run of other test cases. It is something like 'test data preparation' test case. Output from this test case is list with some elements, list looks like this:
def list = ['Login', 'Get Messages', 'Logout', etc.]
List is different on every run. I need to transfer this list from 'test data preparation' test case to other test cases. Transfer will be between two Groovy scripts.
How to transfer list between two Groovy test steps in SoapUI?
As I understand it:
You have one TestCase, which you call from every other TestCase.
I assume this is done using a "Run TestCase" teststep?
You would like to be able to pass a list of strings
As I read it, parameters go one way. From the "external testcase" and back to the calling testcase. There is no "input" from each testcase to this "external testcase"?
The Groovy Script in your "external testcase" may then generate a String result, which in turn can be converted to something like an Array or ArrayList of Strings.
This could be a string with values separated by ;
def result = ""
result += "Entry1;"
result += "Entry2;"
result += "Entry3;"
// You may want to add a line of code that removes the last ;
return result
This result will then be easily retrieved from Groovy Scripts elsewhere, by adding a few lines of code.
If the Groovy Script is placed in another TestCase, but in the same TestSuite, you may retrieve the result using:
def input = testRunner.testCase.testSuite.getTestCaseByName("Name of TestCase").getTestStepByName("Groovy Script Name").getPropertyValue("result")
If it is placed in a TestCase in a different TestSuite, you may use:
def input = testRunner.testCase.testSuite.project.getTestSuiteByName("Test Suite Name").getTestCaseByName("Test Case Name").getTestStepByName("Groovy Script Name").getPropertyValue("result")
and then loop over the input doing something like:
for (def s : input.split(";")) {
log.info s
// Do your stuff here
}
I hope that makes sense...? :)
from groovy step 1 you shall return the list:
def list = ['Login', 'Get Messages', 'Logout']
return list
from groovy step 2 you can get this returned list
def result = context.expand( '${Groovy Script 1#result}' )
list = result.tokenize('[,] ')
list.each{
log.info it
}
note that you get a string that you have to convert back to a list (tokenize).
I did this with SOAPUI pro.
Another way (ugly) would be to store the list in a custom property in groovy script 1 (using testRunner.testCase.setPropertyValue("myList",list.toString())
and to recover it in groovy step 2 (testRunner.testCase.getPropertyValue("myList")
I hope that will help
EDIT : if list elements contain spaces
this is not very clean and I hope someone will help to provide something better but you can do the following :
list = "['Login - v1', 'Get Messages - v2', 'Logout - v1']"
list = list.replace('\'','\"')
def jsonSlurper = new groovy.json.JsonSlurper()
list = jsonSlurper.parseText(list)
list.each{
log.info it
}
Alex
I am new to Groovy and wonder following is possible?
I have a file generated automatically with datestamp, example saledata20180429
Is it possible to code this with Groovy and convert the filename to saledata-2018-04-29.txt
Simple substring calls can get that done:
def name = 'saledata20180429'
def newname = "saledata-${name[8..11]}-${name[12..13]}-${name[14..15]}.txt"
newname evaluates to 'saledata-2018-04-29.txt'
I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific