Cannot replace string text in Groovy script - groovy

I am trying to replace a test in pom.xml using a groovy script. These are my two approaches. The text should be replaced is {env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}
Approach one
File mainPomXml = new File(rootDir,'/pom.xml')
mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
Approach two
def mainPomXml = new File(rootDir,'/pom.xml')
def mainPom = mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
mainPomXml.write(mainPom);
But none of these approaches work. That means both executes but the test is not get replaced. How to fix this issue?

Change the mainPom part as below.
def mainPomXml = new File(rootDir, '/pom.xml')
def mainPom = mainPomXml.text.replace('AM_SERVER_CREDS_USR', '${env.AM_'+ env.toUpperCase() +'_SERVER_CREDS_USR}')
mainPomXml.write(mainPom)

Related

Transfer list between Groovy test steps (SoapUI)

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

Groovy replacing place holders of file content similar to multiline-string

Got the following script which replaces values in the multi line string.
def param1 = 'Groovy'
def param2 = 'Java'
def multiline = """
${param1} is closely related to ${param2},
so it is quite easy to make a transition.
"""
//output shows with the replaced values for param1 and param2
println multiline
Output is shown as expected:
Groovy is closely related to Java,
so it is quite easy to make a transition.
Issue:
Now I am trying to do the same using file instead of multi line string. i.e., copied the multi line string to a file and using the below script to do the same but not working(not giving the desired result).
I am sure, it must be something I am missing. Tried multiple way, but went futile.
Try #1: Script
def param1 = 'Groovy'
def param2 = 'Java'
def multiline = Eval.me(new File('test.txt').text)
println multiline
And it fails to run. Error follows:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: expecting EOF, found ',' # line 1, column 42.
s closely related to ${param2},
^
1 error
Try #2
def param1 = 'Groovy'
def param2 = 'Java'
def multiline = new File('test.txt').text
def finalContent = """$multiline"""
println finalContent
And there is no difference in the output, just showing the file content as it is.
Output:
${param1} is closely related to ${param2},
so it is quite easy to make a transition.
Any pointers what am I missing?
Please note that at the moment I want to avoid file content modification using replace() method.
Not sure why it doesn't work, however what I may suggest here is that templating suits best here. Please have a look:
import groovy.text.SimpleTemplateEngine
def f = new File('lol.txt')
println f.text
def binding = [
param1: 'Groovy',
param2: 'Java',
]
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(f.text).make(binding)
println template.toString()
An explanation why file content is not evaluated may be found here.

Property transfer in SOAPUI using groovy script

Hi i am new to soapui and have this situation.I have two service memberservice1 where the response has "Region" property.I need to check this property and see if its value is "SCR" i need to modify it to "SCA" and pass it to another WS memberservice2.
I tried this way but couldnt get it.Can anyone please suggest.
def smlholder = groovyUtils.getXMLholder("Webservice#request");
def node = smlholder.getnodevalue("//region");
if(node == 'SCA')
testRunner.testcase.testSteps("anotherwebservicename").setProperty('Region','SCR');
Your example code does not match you statement. Below I will follow your statement, and ignore the broken code example.
There are several different ways this cane be done. The easiest would probably be:
def region = context.expand("${Webservice#Response#//*:region}")
if (region == "SCR")
testRunner.testCase.testSteps["anotherwebservicename"].setProperty("Region", "SCA");
else
testRunner.testCase.testSteps["anotherwebservicename"].setProperty("Region", region);

Find an element in XML using XML Slurper

"I have a code that is working as expected but now I have to find the element in different format. Example is below
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>
I have to find the value of "corolla" from this XML. Please reply.
You can run this in the Groovy console
def text = '''
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>'''
def records = new XmlSlurper().parseText(text)
// a quick and dirty solution
assert 'corolla' == records.toString()
// a more verbose, but more robust solution that specifies the complete path
// to the node of interest
assert 'corolla' == records.'car-model'.'model-year'.'year.make'.name.text()

groovy returning different node count

I am trying to get the count of result nodes in soapUI using groovy and the below code gave me the correct count
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("StepName#ResponseAsXml")
def cnt = holder["count(//Results/ResultSet/Row)"]
but when i tried the below i got a count of 1. How are the two different?
def cnt = holder["count('//Results/ResultSet/Row')"]
Though I've never used SoapUI, in the second one, you are passing a String (wrapped in '...') to count.
The first passes a path which I guess gets evaluated into a list of nodes.
All the examples I can find do not wrap the path in a String, so my guess is the first example is the way to do it ;-)
EDIT
Refer Tips and Tricks for most of the SoapUI and Groovy related questions. And count in xpath.

Resources