I am parsing an XML file in Groovy and later I need to append the variables returned.
def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country + lmList.ResponseTime + lmList.timeset
This doesn't work to append the 3 strings. It just assigns the first string to the right. How to properly implement it in Groovy? I tried concat and it threw the following error:
groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChildren.concat() is applicable for argument types: (groovy.util.slurpersupport.NodeChildren) values: [4468]
Possible solutions: toFloat(), collect(), collect(groovy.lang.Closure)
at
Yor code shall look like:
String appendedString = "${lmList.country}${lmList.ResponseTime}${lmList.timeset}"
The exception you are getting means, that you are trying to invoke the plus()/concat() method which is not provided by NodeChildren
As an alternative to injecteer -
def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country.toString() + lmList.ResponseTime.toString() + lmList.timeset.toString()
You weren't trying to add strings, you were trying to add nodes the happen to contain strings.
Assuming the xml looks like:
def xml = '''
<Root>
<LastGlobal>
<HeatMap>
<Country>USA</Country>
<ResponseTime>20</ResponseTime>
<TimeSet>10</TimeSet>
</HeatMap>
</LastGlobal>
</Root>
'''
Below should give what is expected:
def slurped = new XmlSlurper().parseText(xml)
assert slurped.LastGlobal.HeatMap.children()*.text().join() == 'USA2010'
Related
In groovy, I am getting below output in List. I am using Jmeter JSR223 Post processor for the script. My List print below data in result.
def a = [{Zip=36448, CountryID=2}]
I want to fetch only values (36448 and 2) from this List and not Key. How Can I do that?
For simple single instance fetch do this:
def zip = a.first().Zip
def countryId = a.first().CountryID
Seems pretty straight forward if those are only known values that you want.
If you want all Zips and CountryIDs then you can do this:
def zips = a*.Zip
def countryIds = a*.CountryID
That will return 2 Lists one with all the Zips, and one with all the CountryIDs using the spread operator.
I don't know what is the data structure is inside your list your code is not a valid Groovy code.
For Map it would be something like:
a[0].collect {it -> it.value}
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
I want to do the following in SOAPUI using Groovy:
In a TestCase1 select values (Lastname, firstname) from database, and create a Map with dynamic values: def Map = [Login :"$Login", Nom: "$Nom"]
I need my map to be transferred to another TestCase, for this
I'm trying to put my map into properties:
testRunner.testCase.setPropertyValue( "Map", Map)
But I have error:
groovy.lang.MissingMethodException: No signature of method:
com.eviware.soapui.impl.wsdl.WsdlTestCasePro.setPropertyValue() is
applicable for argument types: (java.lang.String,
java.util.LinkedHashMap) values: [OuvInfoPersoMap,
[Login:dupond0001, Nom:Dupond]] Possible solutions:
setPropertyValue(java.lang.String, java.lang.String),
getPropertyValue(java.lang.String) error at line: 123
I found some posts on internet that suggests to use metaClass groovy property
context.testCase.metaClass.map = Map
log.info context.testCase.map
But I don't think it enough in my case.
I would like to be able to pass a map to Testcase2 using:
createMap = testRunner.testCase.testSuite.project.testSuites.testCases["TestCase1"]
createMap.map
Hopefully you can help me solving this problem.
Thanks advance
As #SiKing correctly explain in the comments, setPropertyValue method expects and String for the property name and for the property value.
Note that as #Rao suggest in general testCase execution should be independent, however despiste this technically it's possible to do what you ask for.
So a possible solution for your case is in the first testCase to serialize the Map to String in order that it's possible to save using setPropertyValue(Strig propertyName, String value) method, and then in the second testCase deserialitze it, something like the follow code must work:
TestCase 1
Serialize the map using inspect() method and save it as a property:
def map = ['foo':'foo','bar':'bar', 'baz':'baz']
testRunner.testCase.setPropertyValue('map',map.inspect())
TestCase2
Deserialitze the String property using Eval.me(String exp)::
// get the first testCase
def testCase1 = testRunner.testCase.testSuite.testCases["TestCase1"]
// get the property
def mapAsStr = testCase1.getPropertyValue('map')
// deserialize the string as map
def map = Eval.me(mapAsStr)
assert map.foo == 'foo'
assert map.bar == 'bar'
assert map.baz == 'baz'
I currently have a fixed format for an asset management code, which uses the Groovy string format using the dollar sign:
def code = "ITN${departmentNumber}${randomString}"
Which will generate a code that looks like:
ITN120AHKXNMUHKL
However, I have a new requirement that the code format must be customizable. I'd like to expose this functionality by allowing the user to set a custom format string such as:
OCP${departmentNumber}XI${randomString}
PAN-${randomString}
Which will output:
OCP125XIBQHNKLAPICH
PAN-XJKLBPPJKLXHNJ
Which Groovy will then interpret and replace with the appropriate variable value. Is this possible, or do I have to manually parse the placeholders and manually do the string.replace?
I believe that GString lazy evaluation fits the bill:
deptNum = "C001"
randomStr = "wot"
def code = "ITN${deptNum}${->randomStr}"
assert code == "ITNC001wot"
randomStr = "qwop"
assert code == "ITNC001qwop"
I think the original poster wants to use a variable as the format string. The answer to this is that string interpolation only works if the format is a string literal. It seems it has to be translated to more low level String.format code at compile time. I ended up using sprintf
baseUrl is a String containing http://example.com/foo/%s/%s loaded from property file
def operation = "tickle"
def target = "dog"
def url = sprintf(baseUrl, operation, target)
url
===> http://example.com/foo/tickle/dog
I believe in this case you do not need to use lazy evaluation of GString, the normal String.format() of java would do the trick:
def format = 'ITN%sX%s'
def code = { def departmentNumber, def randomString -> String.format(format, departmentNumber, randomString) }
assert code('120AHK', 'NMUHKL') == 'ITN120AHKXNMUHKL'
format = 'OCP%sXI%s'
assert code('120AHK', 'NMUHKL') == 'OCP120AHKXINMUHKL'
Hope this helps.
for Triple double quoted string
def password = "30+"
def authRequestBody = """
<dto:authTokenRequestDto xmlns:dto="dto.client.auth.soft.com">
<login>support#soft.com</login>
<password>${password}</password>
</dto:authTokenRequestDto>
"""
I am using SoapUI to test webservices. The following string (in xml format) is my request:
<Request>
<AC>
<AssetID>1</AssetID>
<Asset_Name>ABC</Asset_Name>
<Asset_Number>1</Asset_Number>
</AC>
<AC>
<AssetID>2</AssetID>
<Asset_Name>XYZ</Asset_Name>
<Asset_Number>2</Asset_Number>
</Ac>
</Request>
I am using the following code in a groovy script to extract value of Asset_Number for each AC (The above xml string is stored in variable strRequest):
def x = new XmlSlurper().parseText("$strRequest")
x.AC.each { AC ->
assetNum = AC."Asset_Number"
<<do something with the assetNum>>
}
However, I wish to parameterize the above code to pick up Asset_Number for various types of assets (e.g. AC, Peripheral etc). The request xml for each asset is in the same format as above. If I replace 'AC' with variable name 'requestName' in above code:
//strRequest = xml request
def requestName //I will pick up value for this from a test case property
def x = new XmlSlurper().parseText("$strRequest")
x.(requestName.toString()).each { requestName ->
assetNum = requestName."Asset_Number"
<<do something with the assetNum>>
}
it shows the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script166.groovy: 35: The current scope already contains a variable of the name requestName # line 35, column 2. { ^ org.codehaus.groovy.syntax.SyntaxException: The current scope already contains a variable of the name requestName
I have tried a solution mentioned in another post Using a String as code with Groovy XML Parser, but it doesn't serve my purpose.
Any other ideas?
You can use
x."$requestName".each
Why XmlSlurper? In SoapUI you can use XmlHolder
import com.eviware.soapui.support.XmlHolder
def responseHolder = new XmlHolder(messageExchange.getResponseContentAsXml())
def resultFromResponse = responseHolder["here_is_your_xpath"]
assert someExpectedResult == resultFromResponse
And if you need to iterate via multiple xml nodes
resultFromResponse.each
{
assert result == resultFromResponse
}
I'm writing a program in groovy, I want it to run a script with dynamically changing variables. The script is supposed to execute a method with its variables. This method is located in the program that runs the script.
The script would contain something like this:
// getAttribute is a method in my main program, the program which also runs the script
value = getValue("java.lang:type=OperatingSystem", "FreePhysicalMemorySize")
// do something with the value
if (value > 9000) { output = "ERROR" }
// the same thing maybe a few more times
value = getValue(...
I want to keep it as simple as possible.
I was working with these examples: http://groovy.codehaus.org/Embedding+Groovy
I already tried to use the GroovyScriptEngine, but it seems like the script only accepts Strings as input values. It would be great if I could hand over method pointers.
Just trying to hand over an integer like this:
def roots = 'PATH\\script.groovy'
def groscreng = new GroovyScriptEngine(roots)
def binding = new Binding()
def input = 42
binding.setVariable("input", input)
groscreng.run("script.groovy", binding)
println binding.getVariable("output")
With this script.groovy
output = ${input}
results in this error:
Caught: groovy.lang.MissingMethodException: No signature of method: script.$() is applicable for argument types: (script$_run_closure1) values: [script$_run_closure1#fcf50]
Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)
Receiving the value in the script as a String like "${input}" works just fine.
I know it has to work somehow and I would appreciate any help or other suggestions!
output = ${input}
isn't valid groovy
Try:
output = input