Emit local variable values during Groovy Shell execution - groovy

Consider that we have the following Groovy script:
temp = a + b
temp * 10
Now, given that a and b are bound to the context with their respective values, and that the script is executed using a groovy shell script.
Is there a way I could obtain the value of thetemp variable assignment, without printing/logging the value to the console? For instance, given a=2 and b=3, I would like to not only know that the script returned 50 but also that temp=5. Is there a way to intercept every assignment to capture the values?
Any suggestions or alternatives are appreciated. Thanks in advance!

You can capture all bindings and assignments from the script by passing a Binding instance to the GroovyShell object. Consider following example:
def binding = new Binding()
def shell = new GroovyShell(binding)
def script = '''
a = 2
b = 3
temp = a + b
temp * 10
'''
println shell.run(script, 'script.groovy', [])
println binding.variables
Running this script prints following two lines to the console:
50
[args:[], a:2, b:3, temp:5]
If you want to access the value of temp script variable you simply do:
binding.variables.temp

Related

Can you pass variables to Groovy's evaluate(File file)?

Is it possible to pass scope variables to Groovy's evaluate(File file)? And therefore to access variable a in the file OtherScript.groovy listed below?
FirstScript.groovy:
a = 4
evaluate(new File('OtherScript.groovy'))
println 'I can see b = ${b}'
OtherScript.groovy:
b = 2 * a
When running this example the following exception is raised: groovy.lang.MissingPropertyException: No such property: a for class: OtherScript
I believe you can use some sort of Bean Scripting Framework (BSF) which supported by Groovy,
Groovy implement BSF in org.codehaus.groovy.bsf.GroovyEngine,here is a quick example to use BSFManager
#Grab('org.apache.bsf:bsf-api:3.1')
import org.apache.bsf.BSFManager
BSFManager manager = new BSFManager()
manager.declareBean("xyz", 4, Integer.class)
Object answer = manager.eval("groovy", "test.groovy", 0, 0, "xyz + 1")
assert 5 == answer
Example from the groovy doc.
This answer uses GroovyShell which is another possible solution for your example.
code tested with Groovy v2.5.1. Hope this helps.
your scripts are fine except one thing:
the string with println should be doublequoted to interpolate expressions
so, if you have
FirstScript.groovy
a = 4
evaluate(new File('OtherScript.groovy'))
println "I can see b = ${b}"
OtherScript.groovy
b = 2 * a
then the following command line works:
groovy FirstScript.groovy
and prints:
I can see b = 8

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

What is the meaning of this script field in Groovy?

What parameters.script means in the following Groovy code:
example.groovy
class Example {
def call(Map parameters) {
def script = parameters.script
...
}
}
It retrieves a value from a Map with the key 'script'. The following are all equivalent
def script = parameters.script
script = parameters['script']
script = parameters.get('script')
from https://www.timroes.de/2015/06/28/groovy-tutorial-for-java-developers-part3-collections/:
Beside using brackets you can also use dot notation to access entries

Find a value in a collection and assign top an variable using groovy

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

Calling groovy method from script

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

Resources