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.
Related
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)
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
Hello Groovy Experts,
I am using the below command to get all the ODI Dataservers.
def PSchema=DServer.getPhysicalSchemas();
When I print the PSchema variable I getting the following values.
[oracle.odi.domain.topology.OdiPhysicalSchema ABC.X1, oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2]
What I am trying to achieve here I will be passing X1 or X2 during runtime...
And then I want to validate this value with the PSchema result and the print the following value:
oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2
I tried using the following options:
def PSchema44 = PSchema11.findIndexValues { it =~ /(X1)/ }
def pl=PSchema11.collect{if(it.contains ('X1)){return it}}
I tried for loop to check whether values are getting printed properly ..result is fine:
for (item in PSchema11 )
{
println item
}
Assuming 'X1' and 'X2' are the names for the physical schemas, you should be able to do something like this:
def phys = "X1"
def pSchemas = dServer.getPhysicalSchemas()
def schema = pSchemas.find{it.schemaName == phys}
also I guess you are new to Groovy, I suggest you read up on syntax and naming conventions. For example, variable names should always start with a lower case letter
"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()
I am adding jenkins parameters to a job from system groovy script (one build step):
1-st step.
import hudson.model.*
def pa = new ParametersAction([
new StringParameterValue("firstParam", 1), new StringParameterValue("secondParam", 2)
])
Thread.currentThread().executable.addAction(pa)
Now when I try to execute the next system groovy build step, I am looking for them and they are not there:
2nd step.
def firstParam = "firstParam"
def secondParam = "secondParam"
def resolver = build.buildVariableResolver
def firstParamValue = resolver.resolve(firstParam)
def secondParamValue = resolver.resolve(secondParam)
println firstParamValue
println secondParamValue
they both print null! How do I get the parameters in the next system groovy build step?
The weird thing is that when I try a shell execution as a following step and if I do:
echo $firstParam
echo $secondParam
I get both 1 and 2 printed.
Even when I try to print all parameters with the below code I don't get them:
def thr = Thread.currentThread()
def build = thr?.executable
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
println "parameter ${it.name}:"
println it.dump()
println "-" * 80
}
Your first build step didn't work for me, it gave a runtime error as the string parameters being set are integers not strings. I changed it to this and it works, the second step gets the parameters (I added quotes around integer values & used the 'build' variable for current build):
import hudson.model.*
def pa = new ParametersAction([
new StringParameterValue("firstParam", '1'), new StringParameterValue("secondParam", '2')
])
build.addAction(pa)
I am trying this on Jenkins v1.519.