Virtual Service Scripting

Applies to ReadyAPI 3.56, last modified on October 29, 2024
ReadyAPI uses a number of third-party libraries. It is quite possible that we will update some of these libraries or even remove them from ReadyAPI. If you use classes from these libraries, you will have to update your scripts. See a list of third-party libraries updated in ReadyAPI 3.56.

About

Although ReadyAPI offers you power and flexibility for building virtual APIs, you may want to use scripts to implement specific behavior for which there are no pre-defined settings. Below are some situations when you might want to use scripts:

  • Transfer values from the request to the response, perhaps, modifying them on the way.

  • Read some data in a request and use this value to select the response to return.

  • Read the response (or parts of it) from an external file or database instead of having it hard-coded in service properties.

  • Creating custom HTTP responses.

Script properties

You can use scripts in various areas:

  • Service functioning

    Each virtual service has a number of script properties that let you create script handlers for specific events:

    Property Description
    Start Script

    Runs on a virtual service start. Use this script to perform some service-wide actions like reading files, setting up network connections or allocating resources that will be shared by other scripts.

    Stop Script

    Runs before the virtual service stops. Use this script to close connections and release the resources that were allocated during the service functioning.

    OnRequest Script

    Runs every time a virtual service receives a request. You can use this script to check request data or bypass the dispatching strategy (as this script is called before the service dispatches the incoming request).

    AfterRequest Script

    Runs after the virtual service replies to an incoming request. You can use this script for specific logging and reporting actions, for example.

    Show image

  • Virtual responses

    The script code that you write in the Script property of a virtual response is executed before the virtual service sends the response to the client. You can use this code, for example, to change the response contents or for debug purposes.

    Show image

  • VirtResponse test steps

    The script core for SOAP and REST VirtResponse test steps is similar to what you specify for virtual responses. It is executed before the test step sends a response to the client.

    Show image

  • Response dispatching

    You use the Script dispatch strategy for checking incoming requests and returning the name of a mock response that your virtual service should return to the client. See the description of this dispatch strategy for complete information and code samples.

    Show image

  • Script Assertions

    You use them to validate incoming requests using the validation actions, for which ReadyAPI does not offer pre-defined checks. See Script Assertions for details.

    Show image

Notes:

  • The operation and response scripts run only if your service has a virtual operation for the incoming request.

  • The scripts can contain the return statement. However, the service uses the result of the dispatch script only. The result values of all other scripts are ignored.

  • A virtual service runs several script event handlers while processing an incoming request. Here is the order of these scripts:

    • OnRequest script of the service
    • Dispatch script (if used by the virtual operation)
    • Script code in response Script property
    • After Request script of the service
    • Script assertions (if used by the service)
    • Script assertions (if used by the virtual operation)
  • An alternative approach to perform specific actions when a virtual service starts, stops or processes a request is to create event handlers in the Event Manager. See Virtual Service Events.

Script language

The “script” properties support Groovy and JavaScript. The virtual service uses the language set by the Script Language property of your project.

By default, projects use Groovy. This language uses Java-like syntax and can work with Java objects and libraries. More information on the language and its syntax is available at http://www.groovy-lang.org/.

For information on JavaScript, see popular Web resources like JavaScript in MDN or JavaScript Tutorial at w3schools.com.

Script objects

Below is a list of objects that are commonly available in service scripts. To check which objects are available in this or that script property, see the message above the script edit box in the product UI:

Object Description
context Provides a scripting interface to the virtual service, responses and virtual service runner. Use the context.properties collection to store properties related to the service.
log

Includes methods and properties for posting messages to the Script log (to view this log, click Logs in the bottom left corner of the ReadyAPI window and switch to the Script log tab).

You use this for debugging and logging purposes: to post and view data in the log.

message Used in JMS virtual services. Provides a scripting interface to the JMS message body and headers.
mockOperation Corresponds to a virtual operation. Provides a scripting interface to the virtual response and request data, assertions, dispatch settings and other properties.
mockRequest Provides a scripting interface to the incoming request. Use methods and properties of this object to get query string, port, headers, body, and other data.
mockResponse Provides a scripting interface to the virtual response data defined in a virtual service for a response. You can use responseContent of this property, for example, to change the response data before the virtual service sends the response to a client.
mockResult Provides a scripting interface to the entire message exchange procedure: request, response and assertion results.
mockRunner Provides a scripting interface to the virtual service runner. You can use methods of this object to stop the current service.
requestContext Provides a scripting interface to the request context. Use the requestContext.properties collection to store request-related properties.

You can see methods and properties of these objects on the Code Completion list. To invoke it, type the object name and press Ctrl+Space.

Writing script code

The script editors support modern features that make code writing simpler and faster:

  • Use the Code Completion list to see available objects, methods and properties. To invoke the list, select Edit > Code Completion from the menu or press Ctrl+Space.

  • Open a script in a separate window for convenient editing. To do this, click the button on the script editor toolbar.

  • Search for and replace a string with the built-in Find/Replace dialog. To invoke it, press Ctrl+F or select Edit > Find / Replace from the menu.

  • Show line numbers for better navigation. To show or hide the numbers, select Edit > Show Line Number from the menu or press Alt+L.

    To jump to a line by its number quickly, press Ctrl+G or select Edit > Go to Line from the menu.

  • Collapse or expand code regions. Use the Edit > Folding menu items for this.

Examples

To get the value of a project or virtual service property, use the property expansion:

Groovy

//Get a project property
def foo = context.expand( '${#Project#Property}' )

//Get a virtual service property
def bar = context.expand( '${#MockService#Property}' )

To set properties, you can use the setPropertyValue("Property Name") method of the context.mockService object:

Groovy

// Set a virtual service property
def context.MockService.setPropertyValue("Property", "New Value")

For example, the following dispatch script gets the api_key project property and compares it with the value obtained from the request:

Groovy

// Get the XML content of the request
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def xmlHolder = groovyUtils.getXmlHolder( mockRequest.getRequestContent() )

// Get api_key from the request by using XPath
requestAPIKey = xmlHolder.getNodeValue("//request/api_key")
    
// Get the value of api_key from the project property
def validAPIKey = context.expand( '${#Project#api_key}' )

// Compare the values
if (requestAPIKey == validAPIKey) {

    // Get the name of the added pet
    def petName = xmlHolder.getNodeValue("//request/petName)
    
    // Store the value to the property of the virtual service     context.mockRequest.setPropertyValue("addedPet", petName)
    
    // Send the "Success" response
    return "Success"
} else {

    // Send the "Wrong api_key" response
    return "Wrong api_key"
}

To get request headers, use the getRequestHeaders() method of the mockRequest object. It returns the StringToStringsMap object containing the name and value of request headers.

To get a particular header, use the following method:

def headerValue = mockRequest.getRequestHeaders().get("Header Name").get(0)
Note: Since the request may contain several headers of the same name, the get("Header Name") method returns the list of values. If the header is unique, use the get(0) method to get the first (and the only) value from the list. If the request has several headers of the same name, you may need to use another index.

For example, the following dispatch script uses the value of the Accept header to determine which response to send:

Groovy

// Get the value of the Accept header
def contentType = mockRequest.getRequestHeaders().get("Accept").get(0)

// Determine which response to send
if (contentType == "application/xml") {
    
    // Send the XML response
    return "XML"
} else if (contentType == 'application/json') {
    
    // Send the JSON response
    return "JSON"

To read a file, use the File object. For example, the following response script reads a file and sends its content as a response:

Groovy

// Read the file
fileContent = new File( "C:/temp/response.json" ).text

// Save the response content in the context variable.
context.response = fileContent

To insert the file content in the response, you need to use the ${response} property expansion in the response editor:

Scripting in ReadyAPI Virtualization: Sending file as a response content

Click the image to enlarge it.

The following example gets a query string and transforms parameters into the HashMap object:

Groovy

// Get a query string
def queryString = mockRequest.getRequest().getQueryString()

// Split the query string into an array of parameters and its values
String[] fields = queryString.split("&");

// Declare a helper array
String[] kv;

// Create a HashMap object. This object will store key-value pairs.
// The key of each entry is a parameter name, and an entry value is a parameter value.
HashMap<String, String> params = new HashMap<String, String>()

// Iterate through the parameters, transform a parameter string into the key-value pairs,
// and store the entry to the created parameter.
for (int i = 0; i < fields.length; ++i) {
    kv = fields[i].split("=");
    if (2 == kv.length)
        params.put(kv[0], kv[1]);
}

See Also

Configuring Virtual Services
Virtual Service Events
Preparing Virtual Service Before Deploying to VirtServer

Highlight search results