Compile Groovy Script from command prompt which contains soapui libraries - groovy

I am trying to create a script library and compile a groovy class as described in https://stackoverflow.com/a/35498212/9997207
Groovy Script
import groovy.json.*
import com.eviware.soapui.*
class ScriptLibrary {
def context
def testRunner
def log
def boolean setHeaderValues(userId, password){
try{
loginTestStep = testRunner.testCase.testSuite.testCases["SetHeaderParameters"].testSteps["SetHeaderParametersJsonRequest"]
def request = loginTestStep.getPropertyValue("Request").toString()
def jsonReq = new JsonSlurper().parseText(request);
def builder = new JsonBuilder(jsonReq)
builder.content.userId=userId
builder.content.password=password
def jsonReqAsString = JsonOutput.toJson(jsonReq)
loginTestStep.setPropertyValue("Request",jsonReqAsString)
def contextJsonRequest = new WsdlTestRunContext(loginTestStep);
loginTestStep.run(testRunner,contextJsonRequest)
def response = loginTestStep.getPropertyValue("Response").toString()
def jsonResponse = new JsonSlurper().parseText(response);
def accessTokenFromResponse = jsonResponse.accessToken.toString()
def userPermissionFromResponse = jsonResponse.userPermissionIds.toString()
def userIdFromResponse = jsonResponse.userId.toString()
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_ID", userIdFromResponse)
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_PERMISSION", userPermissionFromResponse)
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_ACCESS_TOKEN", accessTokenFromResponse)
log.info "Header set with values "+userIdFromResponse+":::"+userPermissionFromResponse+":::"+accessTokenFromResponse
setHeader = true
}
return setHeader
}
catch (Exception ex) {
log.info "Header Not Set " +ex
setHeader = false
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_ID", "")
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_PERMISSION", "")
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_ACCESS_TOKEN", "")
return setHeader
}
}
}
Getting following compilation error while trying to compile the groovy script from the command prompt
C:\Path\apache-groovy-binary-2.5.1\groovy-2.5.1\bin\GroovyScripts>groovy ScriptLibrary.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Path\apache-groovy-binary-2.5.1\groovy-2.5.1\bin\GroovyScripts\ScriptLibrary.groovy: 20: unable to resolve class WsdlTestRunContext
# line 20, column 26.
def contextJsonRequest = new WsdlTestRunContext(loginTestStep);
^
1 error

You have to include soupui-{version}.jar file in the classpath to resolve this dependency issue. You can find it in SoapUI-{version}/bin folder. Let's say that SoapUI 5.4.0 is located in /tmp/SoapUI-5.4.0/. In this case I can compile a script with following command:
groovyc -d classes -cp ".:/tmp/SoapUI-5.4.0/bin/soapui-5.4.0.jar" script.groovy
Keep in mind that this command is run from the folder where script.groovy is located and compiled class can be found in ./classes/script.class

Related

Groovy call another script to set variables

I'm trying to define variables in another groovy script that I want to use in my current script. I have two scripts like this:
script1.groovy
thing = evaluate(new File("script2.groovy"))
thing.setLocalEnv()
println(state)
script2.groovy
static def setLocalEnv(){
def state = "hi"
def item = "hey"
}
When I println(state), I get a missing property exception. Basically I want script2 to have config variables that I can load in the context of script1. How can I do this?
I'm not sure what/how you want to do exactly, but I guess you can achieve your goal using one of the class available in groovy dynamique scripting capabilities: groovy.lang.Binding or GroovyClassLoader or GroovyScriptEngine, here is an example using GroovyShell class:
abstract class MyScript extends Script {
String name
String greet() {
"Hello, $name!"
}
}
import org.codehaus.groovy.control.CompilerConfiguration
def config = new CompilerConfiguration()
config.scriptBaseClass = 'MyScript'
def shell = new GroovyShell(this.class.classLoader, new Binding(), config)
def script = shell.parse('greet()')
assert script instanceof MyScript
script.setName('covfefe')
assert script.run() == 'Hello, covfefe!'
This is one way to bind a variable to an external script file, more examples from the doc:
http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html
P.S. Loading external file can be done with GroovyClassLoader:
def gcl = new GroovyClassLoader()
def clazz2 = gcl.parseClass(new File(file.absolutePath))
Hope this helps.

Unable to apply Newify on Groovyshell

I want to run some dynamic script with help of Groovyshell. But, i don't want to write new keyword in dynamic script. So, i thought of adding a CompilerConfiguration with Newify keyword. But, things are not working as expected.
CompilerConfiguration configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(
new ASTTransformationCustomizer(
[pattern: "[A-Za-z0-9].*"],
Newify
))
GroovyShell shell = new GroovyShell(profile, configuration)
Still i am getting error
Cannot find matching method sample#BoundingRegion(int, int, int, int)
where BoundingRegion is a class
Perhaps you need to provide more information. This works for me:
import org.codehaus.groovy.control.*
import org.codehaus.groovy.control.customizers.*
def script = '''
class Main {
static main(args) {
assert BigInteger.new(42).toString() == '42' // Ruby style
assert BigDecimal('3.14').toString() == '3.14' // Python style matching regex
}
}
'''
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(
new ASTTransformationCustomizer(
[pattern: "[A-Za-z0-9].*"],
Newify
))
new GroovyShell(configuration).evaluate(script)

Getting variables from a different file in Jenkins Pipeline

I have a contants.groovy file as below
def testFilesList = 'test-package.xml'
def testdataFilesList = 'TestData.xml'
def gitId = '9ddfsfc4-fdfdf-sdsd-bd18-fgdgdgdf'
I have another groovy file that will be called in Jenkins pipeline job
def constants
node ('auto111') {
stage("First Stage") {
container('alpine') {
script {
constants = evaluate readTrusted('jenkins_pipeline/constants.groovy')
def gitCredentialsId = constants."${gitId}"
}
}
}
}
But constants."${gitId}" is says "cannot get gitID from null object". How do I get it?
It's because they are local variables and cannot be referenced from outside. Use #Field to turn them into fields.
import groovy.transform.Field
#Field
def testFilesList = 'test-package.xml'
#Field
def testdataFilesList = 'TestData.xml'
#Field
def gitId = '9ddfsfc4-fdfdf-sdsd-bd18-fgdgdgdf'
return this;
Then in the main script you should load it using load step.
script {
//make sure that file exists on this node
checkout scm
def constants = load 'jenkins_pipeline/constants.groovy'
def gitCredentialsId = constants.gitId
}
You can find more details about variable scope in this answer

Groovy Reusable Functions - Extract Node Value - groovy.lang.MissingMethodException:

I'm a Groovy noob and trying to get my head around using reusable functions to extract an xml node value for a given test step and node in SoapUI. It seems the class runs fine but the problem is when using the method. I get the following error:
groovy.lang.MissingMethodException: No signature of method: org.apache.log4j.Logger.info() is applicable for argument types: (java.lang.String, java.lang.String) values: [return TestStepName, Node] Possible solutions: info(java.lang.Object), info(java.lang.Object, java.lang.Throwable), any(), wait(), dump(), find(groovy.lang.Closure) error at line:
This is my class:
class Example
{
def log
def context
def responseSOAXmlStep
def resultValue
def responseNodePath
def storeProperty
// Class constructor with same case as Class name
def Example(logIn,contextIn,testRunnerIn)
{
this.log = logIn
this.context = contextIn
this.responseSOAXmlStep = responseSOAXmlStep
this.responseNodePath = responseNodePath
}
def execute(responseSOAXmlStep,responseNodePath)
{
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
// do some stuff to prove I've run with right context, etc.
log.info "return "+responseSOAXmlStep,responseNodePath
def holder = groovyUtils.getXmlHolder( responseSOAXmlStep+"#ResponseAsXml" );
resultValue = holder.getNodeValue( "//ns1:"+responseNodePath );
log.info("Node value: " + resultValue );
testRunner.testCase.testSuite.setPropertyValue(storeProperty, resultValue);
return execute
}
}
context.setProperty( "example", new Example( log, context, testRunner) )
log.info "Library Context:"+context
This is where I do the call in a step after the response step:
// get a reference to the library TestSuite
library = testRunner.testCase.testSuite.project.testSuites["Library"]
// find the module within the library
module = library.testCases["Library"].testSteps["Second Example_Class"]
// initialise the library; which places an instance of Example in the context
module.run(testRunner, context)
// get the instance of example from the context.
def example = context.example
// run the method, with parameter
log.info "example.execute(responseSOAXmlStep,responseNodePath) = " + example.execute("TestStepName","Node")
I've searched the forum but could not find an answer that suites my query. Any form of assistance is appreciated. Thanks.
Your error description says that you're invoking info() method on log passing two strings as and arguments, and this method doesn't exist.
The problem is easy to solve, pass one concatenated string with + as parameter instead of passing two strings. In your execute method inside your Example class use this:
def execute(responseSOAXmlStep,responseNodePath)
{
...
// USE + TO CONCATENATE STRINGS INSTEAD OF USE ,
log.info "return " + responseSOAXmlStep + responseNodePath
...
}
instead of:
def execute(responseSOAXmlStep,responseNodePath)
{
...
// do some stuff to prove I've run with right context, etc.
log.info "return " + responseSOAXmlStep,responseNodePath
...
}
EDIT:
As you said in your comment probably you've another problem storing properties in TestSuite level. You're using this code:
testRunner.testCase.testSuite.setPropertyValue(storeProperty, resultValue);
The problem is that setPropertyValue is expecting string as a first argument however at this line in your code storeProperty is not defined yet. Try for example defining storeProperty as:
def storeProperty = "myProperty" before using it in setPropertyValue call.
Hope this helps,

Why am I getting StackOverflowError?

In Groovy Console I have this:
import groovy.util.*
import org.codehaus.groovy.runtime.*
def gse = new GroovyScriptEngine("c:\\temp")
def script = gse.loadScriptByName("say.groovy")
this.metaClass.mixin script
say("bye")
say.groovy contains
def say(String msg) {
println(msg)
}
Edit: I filed a bug report: https://svn.dentaku.codehaus.org/browse/GROOVY-4214
It's when it hits the line:
this.metaClass.mixin script
The loaded script probably has a reference to the class that loaded it (this class), so when you try and mix it in, you get an endless loop.
A workaround is to do:
def gse = new groovy.util.GroovyScriptEngine( '/tmp' )
def script = gse.loadScriptByName( 'say.groovy' )
script.newInstance().with {
say("bye")
}
[edit]
It seems to work if you use your original script, but change say.groovy to
class Say {
def say( msg ) {
println msg
}
}

Resources