Forum Discussion

harry21's avatar
harry21
Occasional Contributor
8 years ago

How to place the Groovy in centralized Groovy Library and access that class from any script

I have the below Groovy script which i need to place it in centralized Groovy Library and then access the class mentioned in the Groovy from any script in my Ready API Project.


//Change the name of the Properties test step below
def step = context.testCase.testSteps['Properties']

//Parse the xml like you have in your script
def parsedXml = new XmlSlurper().parse(file)

//Get the all the error details from the response as map
def errorDetails = parsedXml.'**'.findAll { it.name() == 'IntegrationServiceErrorCode'}.inject([:]){map, entry ->    map[entry.ErrorCode.text()] = entry.Description.text(); map    }
log.info "Error details from response  : ${errorDetails}"

def failureMessage = new StringBuffer()

//Loop thru properties of Property step and check against the response
step.properties.keySet().each { key ->
   if (errorDetails.containsKey(key)) {
       step.properties[key]?.value == errorDetails[key] ?:  failureMessage.append("Response error code discription mismatch. expected [${step.properties[key]?.value}] vs actual [${errorDetails[key]}]")
   } else {
       failureMessage.append("Response does not have error code ${key}")
   }
}
if (failureMessage.toString()) {
  throw new Error(failureMessage.toString())
} 


Path: D:\GroovyLib\com\Linos\readyapi\util\property\propertyvalidation
File Name: PropertyValidation
I have just tried the code in Groovy Library.. Please correct this if wrong

package com.Linos.readyapi.util.property.propertyvalidation
import com.eviware.soapui.support.GroovyUtils
import groovy.lang.GroovyObject
import groovy.sql.Sql

class PropertyValidation
{
    def static propertystepvalidation()
{
//Change the name of the Properties test step below
def step = context.testCase.testSteps['Properties']

//Parse the xml like you have in your script
def parsedXml = new XmlSlurper().parse(file)

//Get the all the error details from the response as map
def errorDetails = parsedXml.'**'.findAll { it.name() == 'IntegrationServiceErrorCode'}.inject([:]){map, entry ->    map[entry.ErrorCode.text()] = entry.Description.text(); map    }
log.info "Error details from response  : ${errorDetails}"

def failureMessage = new StringBuffer()

//Loop thru properties of Property step and check against the response
step.properties.keySet().each { key ->
   if (errorDetails.containsKey(key)) {
       step.properties[key]?.value == errorDetails[key] ?:  failureMessage.append("Response error code discription mismatch. expected [${step.properties[key]?.value}] vs actual [${errorDetails[key]}]")
   } else {
       failureMessage.append("Response does not have error code ${key}")
   }
}
if (failureMessage.toString()) {
  throw new Error(failureMessage.toString())
} 

I am not sure what to mention in the def static method. I am new to this process and haven't done that yet. Can someone please guide me! I've read the documentation on Ready API! website. But I'm not clear on that.

 

  • ByronJ's avatar
    ByronJ
    Occasional Contributor

    This is just a simple example I wrote for my team and thought I would share with you. What I found challenging was when to use a $ for a variable and when is it left off and how to handle that within strings for Groovy. My team also pulls all data from a datasource so the actual call in the second snippet has a data source property values instead of an actual hard coded values.

     

    Code from Utils.groovy:

    class Utils{ 
    
       
        def static doXmlCountComparison(String xmlApiRequest, String xmlApiResponseXpath, String xmlDbRequest, String xmlDbResponseXpath, log, context) 
        {
    
            def apiCount = context.expand( '${'+xmlApiRequest+'#ResponseAsXml#count('+xmlApiResponseXpath+')}' )
            def dbCount = context.expand( '${'+xmlDbRequest+'#ResponseAsXml#count('+xmlDbResponseXpath+')}' )
            
            assert apiCount == dbCount
        }
    }
    Utils.doXmlCountComparison('getThings','//ns1:things/ns1:e','JDBC','//Row',log,context)

    The above is a groovy snippet in the test case.

     

     

    My scripts folder is set Globally within Preferences.

    • Radford's avatar
      Radford
      Super Contributor

      Ahhh... Reading ByronJ's post has made me realise that I wasn't actually paying attention to the contents of your script. I didn't spot that you were referencing the Ready API variables context and log, plus a file variable. These will need to be passed into your static function.

       

      I've edited my post above to reflect this.

  • Radford's avatar
    Radford
    Super Contributor

    Could you edit your post to format your code and separate from your question text? You should be able to use the "Insert Code" button:

     

     

    Your script files must be valid classes, not just arbitrary scripts.

     

    You should be able to wrap your code into a simple class. Have you seen this documentation page? It has an example, that you can follow and try yourself.

     

     

     

     

     

     

    • harry21's avatar
      harry21
      Occasional Contributor

      yes.. this is the documentation which i read.. not clear in that.. doesn't have detailed information i felt

      Edited my post..

      • Radford's avatar
        Radford
        Super Contributor

        Thanks for the reformatting I think I understand now...

         

        Your code was missing a couple of closing brackets, this might of just been a cut and paste error. Also you will need to pass in the context and log Ready API variables and your file variable to your static method. Assuming your code is now:

         

        package com.Linos.readyapi.util.property.propertyvalidation
        import com.eviware.soapui.support.GroovyUtils
        import groovy.lang.GroovyObject
        import groovy.sql.Sql
        
        class PropertyValidation {
            def static propertystepvalidation(File file, context, log) {
                //Change the name of the Properties test step below
                def step = context.testCase.testSteps['Properties']
        
                //Parse the xml like you have in your script
                def parsedXml = new XmlSlurper().parse(file)
        
                //Get the all the error details from the response as map
                def errorDetails = parsedXml.'**'.findAll {
                    it.name() == 'IntegrationServiceErrorCode'
                }.inject([:]) { map, entry -> map[entry.ErrorCode.text()] = entry.Description.text(); map }
                log.info "Error details from response  : ${errorDetails}"
        
                def failureMessage = new StringBuffer()
        
                //Loop thru properties of Property step and check against the response
                step.properties.keySet().each { key ->
                    if (errorDetails.containsKey(key)) {
                        step.properties[key]?.value == errorDetails[key] ?: failureMessage.append("Response error code discription mismatch. expected [${step.properties[key]?.value}] vs actual [${errorDetails[key]}]")
                    } else {
                        failureMessage.append("Response does not have error code ${key}")
                    }
                }
                if (failureMessage.toString()) {
                    throw new Error(failureMessage.toString())
                }
            }
        }

         

         

        Save this in a file called "PropertyValidation.groovy"

         

        From your message I think you may have the directory wrong. Just set the script library to “D:\GroovyLib”

         

        Now because your class has specified it's package to be com.Linos.readyapi.util.property.propertyvalidation place your file "PropertyValidation.groovy" in the directory:

         

        D:\GroovyLib\com\Linos\readyapi\util\property\propertyvalidation

         

        Think of the package as the sub-directory within the script library directory.

         

        You should now be able to call your static method from any ReadyAPI groovy script window as such (note the import statement, this is just needed once at the top of each script that calls your static function):

         

        import com.Linos.readyapi.util.property.propertyvalidation.PropertyValidation
        import java.io.File
        
        def file // Obtain your file object however you need to
        
        PropertyValidation.propertystepvalidation(file, context, log)

         

        EDIT: To add the passing in of parameters into static method, see posts below.