Cycle includes a step to execute Groovy scripts.
I execute Groovy script "<GROOVY_SCRIPT_FILE>"
Groovy scripts can be constructed to perform multiple functions in a single file by creating user defined methods. Cycle variables can be used to control which methods to execute and provide the execution data. The benefit to this approach is creating utility scripts to consolidate functionality. This will make your script suite easier to reference and maintain.
This example Groovy script called mathMethods.groovy is comprised of 4 user defined methods (avg,total,max,min) that execute different mathematical functions. Cycle will pass in the numbers that make up the list (a,b,c). Cycle will pass in the method name (method) to execute. The Groovy output is controlled by the Cycle inputs providing flexibility and re-usability.
// Create list of numbers from passed in Cycle variables
list = [a,b,c];
//Method definitions
def avg(l){
result = l.sum()/l.size();
average = "The average is: ${result}";
}
def total(l){
result = l.sum();
total = "The total is: ${result}";
}
def max(l){
result = l.max();
max = "The max is: ${result}";
}
def min(l){
result = l.min();
min = "The min is: ${result}";
}
// Determine what method to call from Cycle
if(method == "avg"){
output = avg(list)
}else if(method == "total"){
output = total(list)
}else if(method == "max"){
output = max(list);
}else if(method == "min"){
output = min(list);
}
The corresponding Feature assigns variables and executes the Groovy script. In this example we are executing all the methods in series to show output for all. In reality the methods would be called at different times within a Feature or across Features depending on need. Notice the value of $output is different for each of the method calls but the same script is executed each time.
Scenario: Groovy Math Methods
Given I assign 28 to variable "a"
And I assign 17 to variable "b"
And I assign 9 to variable "c"
When I assign "avg" to variable "method"
Then I execute Groovy script "scripts\mathMethods.groovy"
And I echo $output
When I assign "total" to variable "method"
Then I execute Groovy script "scripts\mathMethods.groovy"
And I echo $output
When I assign "max" to variable "method"
Then I execute Groovy script "scripts\mathMethods.groovy"
And I echo $output
When I assign "min" to variable "method"
Then I execute Groovy script "scripts\mathMethods.groovy"
And I echo $output