0% found this document useful (0 votes)
1 views

Devtest script pdf

DevTest 8.0 allows for the customization of its components through scriptable extensions, enabling users to implement specific configurations and verify data integrity. This document serves as a guide for engineers new to scripted extensions, consolidating scattered information from product documentation and focusing on scripting best practices. It covers various scripting languages supported by DevTest, extension capabilities, and enhancements introduced in version 8.0.2.

Uploaded by

gshivamit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Devtest script pdf

DevTest 8.0 allows for the customization of its components through scriptable extensions, enabling users to implement specific configurations and verify data integrity. This document serves as a guide for engineers new to scripted extensions, consolidating scattered information from product documentation and focusing on scripting best practices. It covers various scripting languages supported by DevTest, extension capabilities, and enhancements introduced in version 8.0.2.

Uploaded by

gshivamit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

DevTest 8.

0 – Custom Extensions
Summary
DevTest 8.0 supports customization of its components by scriptable or programmable extensions. These
extensions are envisioned as configuration steps to complement the rich set of features available
already out of the box. Custom DevTest Extensions might be necessary to implement accommodating
customer specific configuration of the system under test, to match or to verify correctness of complex
dependencies and data integrity, for instance.
This document intends to help engineers, who are new to the concept of scripted extensions in DevTest
solutions, to get started. It is not supposed to replace current product documentation, but to
complement it: information about scripted extensions is scattered to various locations in product
documentation, located close to the DevTest components they can extend. This document pulls
together all this information into this single document. Because of its focus on scripting, commonalities,
specifics, recommendations, and finally best practices of the multiple scripting environments are
described and explained.
This document does not cover introductions into scripting languages used in DevTest.
Some extension capabilities become available with Service Packs for DevTest 8.0 only. This is noted
along with the description.
This document covers DevTest 8.0.2.

Document History
Date Version Author Comment
06/02/2015 1.0 Cameron Bromley Initial version. Covers DevTest 8.0.1.
Rick Brown
Ulrich Vogt
04/10/2015 1.1 Ulrich Vogt 8.0.2 enhancements
 Coloring custom events
 Scripted data
 Document references updated to wiki for 8.0.2

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Contents
Summary ....................................................................................................................................................... 1
Document History ......................................................................................................................................... 1
Legal .............................................................................................................................................................. 4
Copyright notice ........................................................................................................................................ 4
Target Audience ............................................................................................................................................ 4
Documentation ............................................................................................................................................. 5
Extension Capabilities ................................................................................................................................... 5
Extension by Scripting ................................................................................................................................... 5
Default Scripting Engine ............................................................................................................................ 6
Groovy ....................................................................................................................................................... 6
JavaScript .................................................................................................................................................. 6
BeanShell................................................................................................................................................... 6
Velocity ..................................................................................................................................................... 7
Scripting support in DevTest 8.0 ................................................................................................................... 7
Java Script Step ..................................................................................................................................... 7
Common.................................................................................................................................................... 7
Injected Variables and Properties ......................................................................................................... 7
TestExcec class ...................................................................................................................................... 8
Scripts in Mobile Testing ..................................................................................................................... 17
VSE Classes .......................................................................................................................................... 17
Security ............................................................................................................................................... 19
Logging ................................................................................................................................................ 19
Events .................................................................................................................................................. 21
Sharing Data ........................................................................................................................................ 23
Debugging ........................................................................................................................................... 26
Editor....................................................................................................................................................... 27
Configuration Area .............................................................................................................................. 27
Object Selector.................................................................................................................................... 28
Code Editor ......................................................................................................................................... 29
Status area .......................................................................................................................................... 30
Scripted Expression ................................................................................................................................. 31
Sample................................................................................................................................................. 31
Test Step - Execute Script (JSR-223) ........................................................................................................ 33
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 2 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

DevTest Product Documentation........................................................................................................ 33


Input Parameters ................................................................................................................................ 33
Output Parameters ............................................................................................................................. 33
Logging output .................................................................................................................................... 34
Editor ................................................................................................................................................... 34
Sample................................................................................................................................................. 35
Scripted Assertion ................................................................................................................................... 37
DevTest Product Documentation........................................................................................................ 37
Input Parameters ................................................................................................................................ 37
Output Parameters ............................................................................................................................. 37
Logging output .................................................................................................................................... 37
Editor ................................................................................................................................................... 37
Sample................................................................................................................................................. 38
Virtual Service Router Step ..................................................................................................................... 39
DevTest Product Documentation........................................................................................................ 39
Input Parameters ................................................................................................................................ 39
Output Parameters ............................................................................................................................. 39
Logging output .................................................................................................................................... 39
Editor ................................................................................................................................................... 40
Sample................................................................................................................................................. 40
Match Script in Virtual Service Images ................................................................................................... 42
DevTest Product Documentation........................................................................................................ 42
Input Parameters ................................................................................................................................ 42
Output Parameters ............................................................................................................................. 42
Logging Output.................................................................................................................................... 42
Match Script Editor ............................................................................................................................. 43
Sample 1.............................................................................................................................................. 44
Sample 2.............................................................................................................................................. 44
Scriptable Data Protocol ......................................................................................................................... 46
DevTest Product Documentation........................................................................................................ 46
Scripts .................................................................................................................................................. 46
Input Parameters ................................................................................................................................ 46
Output Parameters ............................................................................................................................. 46
Logging output .................................................................................................................................... 47
Editor ................................................................................................................................................... 47
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 3 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Best Practices ...................................................................................................................................... 47


Errata................................................................................................................................................... 50
Sample 1.............................................................................................................................................. 50
Sample 2.............................................................................................................................................. 53
Scripted Dataset ...................................................................................................................................... 54
DevTest Documentation ..................................................................................................................... 54
Input Parameters ................................................................................................................................ 54
Output Parameters ............................................................................................................................. 54
Editor ................................................................................................................................................... 54
Sample................................................................................................................................................. 55
Appendix ..................................................................................................................................................... 56
Performance considerations ................................................................................................................... 56
Sample Code ........................................................................................................................................... 56

Legal
 What kind of CA support is provided with a custom extension? Custom extensions are not
covered by common CA product support conditions. Special support can be negotiated. Please
contact your CA representative.
 What happens when a new version of DevTest is installed? A custom extension might need to be
recompiled to meet the differences in DevTest API. CA strives for DevTest API backward
compatibility.
 What happens if the customer finds a problem with the custom extension? If no special support
contract is in place CA Professional Services can be contracted to find the problem, fix it and
deploy it to every place it has been installed (all DevTest workstations, all DevTest servers).
All sample code provided in this document

Copyright notice
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective
companies. This document does not contain any warranties and is provided for informational purposes
only. Any functionality descriptions may be unique to the customers depicted herein and actual product
performance may vary.

Target Audience
This document is intended for customers, partners, and CA field personnel familiar with DevTest, who
want to create scripts to extend or to customize existing functionality in DevTest solutions.
Programming skills are required, as well as basic knowledge of scripting languages such as JavaScript,
Groovy or BeanShell. Java knowledge is required to understand java based code samples.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 4 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

It is strongly recommended to review related product documentation. References to related DevTest


product guide sections on CA support are given.

Documentation
[1] DevTest Solutions: Using Service Virtualization – DevTest 8.0.2 Product Documentation
Using CA Service Virtualization
[2] DevTest Solutions: Using Agents – DevTest 8.0.2 Product Documentation
Using CA Application Test
[3] DevTest Solutions: Using the SDK – DevTest 8.0.2 Product Documentation Using the SDK
[4] DevTest Solutions: Administering – DevTest 8.0.2 Product Documentation Administering
[5] SDK JavaDoc – {{LISA_HOME}\doc\SDKJavaDoc\index.html

Extension Capabilities
DevTest 8.0 allows for custom extensions in various components
 Test cases
o Custom Java Test step - Java
o Custom JSR-223 script Test step - Script
o Custom Assertions to verify customer specific dependencies [3] – Script/Java
o Custom Filters to store additional data in properties [3] – Java
o Custom Companion [3] – Java
 Staging documents
o Custom reports to report on customer specific events [3] – Java
o Custom Report Metrics to extract customer specific metrics from test cases [3] – Java
 Agent
o Modify agent behavior [2] – Java
o Manipulate data captured by the agent [2] – Java
o Execute additional steps during recording or playback before or after virtualized
methods are called [2] – Java
 Broker
o Change data in frames [2] – Java
o Add/remove frames [2] – Java
o Customize the stitching algorithm for data from different agents [2]
 Virtual Services
o Match script in Virtual service images [1] – Script
o Virtual Service Router step in Virtual Service models
o Scriptable Data Protocols to modify service requests or responses while recording [1] –
Script
o Custom Data Protocol Handlers modify service requests or responses while recording
[1] – Java

Extension by Scripting
Out of the box DevTest 8.0 supports scripting languages
 BeanShell
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 5 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

 Groovy
 JavaScript
 Velocity
BeanShell was the only scripting language available and supported in previous product versions. It is
now being deprecated, because it is rather slow if compared to JavaScript and Groovy, and because it is
not maintained actively by the internet community any more. Therefore BeanShell is discouraged to use
for new scripts. BeanShell scripting remains supported for backward compatibility.
BeanShell scripts are processed by a BeanShell interpreter. When possible, JavaScript and Groovy scripts
are compiled into Java byte code first before run. Therefore JavaScript and Groovy scripts have better
performance once compiled than BeanShell scripts.

Default Scripting Engine


BeanShell is the default scripting language in DevTest 8.0. To change the default scripting language to
Groovy, for instance, edit file ‘local.properties’ and add following line:
##=====DevTest Default Scripting Engine=====
lisa.scripting.default.language=groovy

DevTest can be configured to support additional scripting engines. Please see Enabling Additional
Scripting Languages for details.
The scripting languages that are installed and found by the runtime environment are listed out in the
relevant log file (e.g. workstation.log) once a script is called the first time:

Each log entry lists the valid names for the scripting engine. These names can later be used as language
specifiers to determine the scripting engine to use.

Groovy
Introduction, documentation, tutorials on groovy can be found on http://groovy.codehaus.org/.

JavaScript
Introduction, documentation, tutorials and samples are found on JavaScript at
http://www.w3schools.com/js/.

BeanShell
BeanShell is run by a Java interpreter. In a BeanShell script you can type normal Java statements and
expressions and display the results.
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 6 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Introduction, documentation and samples on BeanShell can be found at http://www.beanshell.org/.


DevTest Product documentation includes a basic introduction into BeanShell at Using BeanShell in
DevTest.

Velocity
Velocity can be downloaded from https://velocity.apache.org/index.html. Documentation on Velocity is
available at https://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html.

Scripting support in DevTest 8.0


Extending the existing rich set of DevTest functionality by scripting is available at following places:
 Scripted Expressions - Anywhere you use {{expressions}} you can specify a scripting language
 Execute Script (JSR-223) - A test case or virtual service model can be extended by a test step
that executes a script. This script can run additional logic to execute commands and return data
to the test case context for other tests steps to use. This test step replaces the ‘Java Script Step’
available in previous product releases, which is deprecated in DevTest 8.0.
 Scripted Assertion – An assertion can be added to a test step that executes a script in order to
assure and verify test step results
 Match Script - For virtual services images complex algorithms can be implemented in VSE by a
script to find a matching transaction to a client request.
 Scriptable Data Protocol Handler (DPH) – If built-in data protocol handlers do not correctly
translate client data into a format VSE understands or vice versa, a scriptable DPH can be
developed to bridge the gap.
 Virtual Service Router Step – This step routes a request from a virtual service listen step to the
response selector step and the protocol-specific live invocation step, or both. The decision is
made based on the current execution mode for the running model. If running in DYNAMIC mode
a script can be used to determine the route of the request.

Java Script Step


The ‘Java Script Step’, which is available previous product releases, but deprecated in DevTest 8.0, will
not be covered. The ‘Java Script Step’ step is functional equivalent to ‘Execute Script (JSR-223)’ step
configured for BeanShell scripting language with a property scope of ‘Test state and system properties’.

Common
This section covers information that is common to all the scriptable extensions in DevTest. Deviations
will be covered in the sections covering specifics of extensions.

Injected Variables and Properties


DevTest gives scripts access to the runtime environment by different means. It supplies built-in –
injected – variables to access information available in the current test case or virtual service.
 ‘textExec’ object – specifies the current test execution environment. The testExec object
includes the state and supporting behaviors for running the test.
 ‘lisa_vse_request’, ‘lisa_vse_response’ objects – specifies the current live transaction request,
current live or recorded transaction response in a scriptable Data Protocol Handler (DPH) of a
virtual service in action.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 7 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

 ‘incomingRequest’ and ‘sourceRequest’ objects – specify the live incoming and the recorded
source transaction request in Match Scripts
 ‘_logger’ object – specifies a logger object available to the current script environment
 Test state properties (optional) – provide shortcut access to test properties. This is also available
by ‘testExec’ via method calls
 System properties (optional) – provides shortcut access to java system properties, also available
via ‘testExec’ method calls
 ‘_webDriver’ – references the MobileSession object that is associated with the test case, and is
used to script Appium. ‘_webDriver’ works during runtime only. ‘_webDriver’ is available
starting with DevTest 8.0.1.

When creating a script in DevTest the developer can often choose the scope of variables to be injected
into the script:
• ‘testExec’ and ‘_logger’ only: only the ‘testExec’ and ‘_logger’ objects are available to the
script (recommended)
• Test state properties: direct access to properties that provide information about the test
case. ‘testExec’ and ‘_logger’ objects are also available
• Test state and system properties: all properties for the test case and system. This is the
same scope as in previous product versions. ‘testExec’ and ‘_logger’ objects are also
available.
The caveat to the wide scope of accessibility to the test environment is the fact that the broader the
scope is the longer it takes to setup the scope for the script and to start the script.
Test state and system properties are also available via ‘testExec’ object.
The syntax to access the variables may vary on language.
Some scripting entry points have other variables, e.g. Data Protocol Handlers and Match Scripts have
access to more variables, see specific examples below.

{{some_property}}
Referring to a property in property tags {{some_property}} in a script is supported. The property is
substituted for the property value at runtime before the script is executed. This use of property tags is
discouraged, though, as parsing for replacements slows down execution of the script setup.
When retrieving a property from test case that includes property tags there are methods, which replace
properties by their values.

TestExcec class
The TestExec class supplies several methods. The following list is just an overview of methods available
for this class. Please see [5] for more details. Of interest are mostly how to retrieve and to set properties
of the current test case under execution:
java.lang.Object getStateValue(String strKey) Returns the java.lang.Object of the given key

boolean getStateBoolean(String strKey, boolean bDefault ) Returns the value of strKey as a boolean value.
If property strKey does not exist, has no value or no
boolean value, bDefault is returned

int getStateInt(String strKey, int nDefault) Returns the value of strKey as an int value.
If property strKey does not exist, has no value or no int
value, nDefault is returned.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 8 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

String getStateString(String strKey, String strDefault) Returns the value of strKey as a String value.
If property strKey does not exist, has no value or no
String value, strDefault is returned.

void setStateValue(String strKey, java.lang.Object value) Sets property strKey to value of type java.lang.Object

void log (String shortMsg, String longMsg) Pushes a ‘Log message’ event message

void warn (String shortMsg, String longMsg) Pushes a ‘Step warning’ event message

void raiseEvent(int eventID, String shortMsg, String Send a custom event message
longMsg)

For samples on retrieval or setting of properties see Reading a Property and Setting a Property. Samples
for different scripting languages are given in Script Samples Accessing testExec objects and Properties.
Samples to create event messages are described in Events.
There are many other methods available through TestExec objects - see [5] for details.

Reading a Property
Almost every script needs to retrieve data from test case. The recommended way to do that is using a
‘testExec.getState*()’ method.
The ‘testExec.getStateValue(“Key”)’ method returns the value of property ‘Key’ as Object. If Key is not
set the returned string is empty, if ‘Key’ does not exist the returned value is ‘null’.
Then there are type specific ‘testExec.getState*()’ methods, such as ‘testExec.getStateString(“Key”,
defaultString)’, ‘testExec.getStateInt(“Key”, defaultInteger)’, ‘testExec.getStateBoolean(“Key”,
defaultBoolean)’. These type specific retrieval methods return their respective default value in case
property ‘Key’ is undefined. For Boolean and Integer values the default string is also returned if property
‘Key’ is not set. For String values the empty string is returned if property ‘Key’ exist but is not set.

Sample
For each of the String, Boolean, and Integer type two properties are defined, one set with a valid value,
another one not set.

The following sample groovy code executes for each property ‘testExec.getStateValue(“Key”)’ and the
type specific method to retrieve the property value. Additional both methods are applied to retrieve an
undefined property.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 9 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

String

Please note the differences in the output when retrieving the value for the undefined property
‘AA_String3’ in ‘Info-3’ output. Retrieving an empty property returns identical values (‘Info-2’).

Boolean

Please note the differences in the output when retrieving the value of the empty property
‘AA_Boolean2’ in ‘Info-2’ output and of the undefined property ‘AA_Boolean3’ in ‘Info-3’ output. For
Boolean and Integer type the default value is returned if respective property is not set or does not exist.

Integer

Please note the differences in the output when retrieving the value of the empty property ‘AA_Integer2’
in ‘Info-2’ output and of the undefined property ‘AA_integer3’ in ‘Info-3’ output. For Boolean and
Integer type the default value is returned if respective property is not set or does not exist.

Using parseInState()
Retrieving a property that includes property tags, i.e. {{some_prop}}, requires the use of method
‘testExec.parseInState()’ in order to replace a property by its current value.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 10 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Sample
Using property ‘EXAMPLES_HOME’

The following groovy script returns the real path only after applying the ‘parseInState()’ method in
variable ‘strInfo2’

Note that scripts are parsed for {{properties}} before they are executed, so the following script is
equivalent to the above:
strInfo1 = “{{EXAMPLES_HOME}}”
return “INFO-1 = (“ + strInfo1 + “)”;

Setting a Property
Scripts return results when finished. Depending on the scripting language there are different means to
do that, usually by a return value.
If there is a need to return more than one value a script can create and update properties of a test case.
‘testExec.setStateValue(“Key”, value)’ sets a property ‘Key’ to a string value.
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 11 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Sample
This groovy code snippet (creates and) sets three new properties:

Opening the ‘Properties pane’, clicking on the ‘Refresh’ button and sorting the properties by ‘Key’ lists
all the properties of the test case.

Access to Test state and system property


Test state and system properties can be accessed directly by name or via ‘testExec’.

Sample
Please note the property scope, which includes direct access to test case properties, as used in line #2 of
the code sample.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 12 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

The same code will fail in line #2 if the scope is changed to ‘TestExec and logger only’, because property
‘LISA_USER’ will then be unavailable.

Access to Properties that not in Java variable format


When a script is being set up, system and test case properties will be copied into the runtime scope of the
script as variables. These variables need to have valid JavaScript/BeanShell/Groovy variable names. Variable
names with dots in them are not valid identifiers. So a property 'foo.bar' is converted into a form suitable for
a variable name, in this case of we change all ‘.’ chars to ‘_’. So we end up with a variable named ‘foo_bar’.
‘Available Objects’ list contains already converted property names.
With ‘testExec’ unconverted, original property names have to be used. Please see the following sample.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 13 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Sample
Property scope is ‘Test state and system properties’ and there is a system property ‘file.encoding’
available. ‘Available Objects’ has this property already converted, ready to use as a variable in the script.

The following sample script shows how to access this property by its variable name or by ‘testExec’.
‘testExec.getStateString()’ would return the ‘default’ string to indicate that this property is unavailable
or not set.
Reviewing the script output shows that
 Direct access to property ‘file_encoding’ works as expected (INFO-1).
 Reading the converted name by ‘testExec’ does not return the string (INFO-2).
 Reading the original system property name by ‘testExec’ works as described above.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 14 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Script Samples Accessing testExec objects and Properties


Following are some samples of retrieving and setting properties in scripting languages BeanShell,
JavaScript and Groovy.
BeanShell sample code:
 #7: Logs information to current logging file,
incl. reading property ‘LISA_PROJ_NAME’ via
TestExec object
 #10: Sets var ‘osname’ via property
‘os_name’, which is in fact a system property
‘os.name’
 #11: Reads String property ‘LISA_HOST’ via
TestExec object with default string ‘No Host’
 #12: Reads Integer property ‘PORT’ via
TestExec object with default value of 9989
 #13: Adds to read port number to proof
integer type
 #14: Reads property DBPORT
 #15: Adds to read DBPORT property to proof
integer type.
 #17: Sets property SCRIPT_OUT via TestExec
object
 #20: Returns some string.

Groovy sample code:


 #1: Logs information to current logging file,
incl. reading property ‘LISA_PROJ_NAME’
directly
 #5: Sets property Hello via TestExec object
 #7: Sets var ‘osname’ via ‘System’ call
 #8: Reads String property ‘LISA_HOST’ via
TestExec object
 #9 Reads Integer property ‘PORT’ via
TestExec object with default value of 9989
 #10: Adds to read port number to proof
integer type
 #11: Reads property DBPORT
 #12 Adds to read DBPORT property to proof
integer type.
 #14: Sets property SCRIPT_OUT via TestExec
object
 #17: Returns some string.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 15 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

JavaScript sample:
 #1: Logs information to current logging file,
incl. reading property ‘LISA_PROJ_NAME’
directly
 #5: sets test state property Hello via TestExec
object
 #6: Reads String property ‘LISA_HOST’ via
TestExec object with default string ‘No Host’
 #7: Sets var ‘osname’ via property ‘os_name’,
which is in fact a system property ‘os.name’
 #8: Reads Integer property ‘PORT’ via
TestExec object with default value of 9989
 #9: Adds to read port number to proof
integer type
 #10: Reads property DBPORT
 #11: Adds to proof integer type.
 #13: Sets property SCRIPT_OUT via TestExec
object
 #19:Last expression evaluated is returned by
script

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 16 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Scripts in Mobile Testing


Test cases for testing mobile application are part of DevTest Application Test. Test cases for mobile
Applications can be customized by scripting using ‘Execute Script (JSR-223)’ test step the same way as
for other applications.
Specifically for scripting Appium the ‘_webDriver’ variable is available since DevTest 8.0.1. This variable
is a reference to the ‘MobileSession’ object associated with the test when running. Because of this, the
‘Test’ button at the bottom of the script editor is mostly useless as the ‘_webDriver’ variable is only
active in a running session that is being recorded or played back. Otherwise errors are thrown when
clicking this button.
‘_webDriver’ is an instance of class ‘org.openqa.selenium.remote’. Javadoc documentation of the API is
available at org.openqa.selenium.remote.
Following sample executes on an iOS application:

VSE Classes
Match Script and Scriptable Data Protocol Handlers work on transactions of virtual services. These
scripts are supported by DevTest. DevTest supplies injected variables automatically giving access to the
objects needed.

Request
‘lisa_vse_request’, ‘incomingRequest’ and ‘sourceRequest’ are supplied injected variables containing
objects of class ‘com.itko.lisa.vse.stateful.model.Request’ and include single transaction requests. This
class provides following methods:
String getOperation() Returns the operation of the incoming request

void setOperation(String newOperation) Changes the operation of the request

Boolean isBinary() Returns whether or not the request body is binary or text data

void setBinary(Boolean bFlag) Sets the ‘Binaryflag’ indicating whether or not the request body contains
binary or text data

String getBodyText() Returns the request body data as text

void setBodyText(String strBody) Changes the request body to content of strBody.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 17 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

This method sets the BinaryFlag to ‘false’ automatically.

byte [] getBodyBytes() Returns the request body data as binary

void setBodyBytes(byte [] arrayByte) Changes the request body to content of arrayByte.


This method sets the BinaryFlag to ‘true’ automatically.

String toString() Returns the entire request as String

long id() Returns the ID of the request

Response
‘lisa_vse_response’ is a supplied injected variable containing objects of class
‘com.itko.lisa.vse.stateful.model.Response’ and include a transaction response. This class provides
following methods.
Boolean isBinary() Returns whether or not the response’s body is binary or text data

void setBinary(Boolean bFlag) Sets the ‘Binaryflag’ indicating whether or not the response’s body contains
binary or text data

String getBodyText() Returns the response body data as text

void setBodyText(String strBody) Changes the response body to content of strBody.


This method sets the BinaryFlag to ‘false’ automatically.

byte [] getBodyBytes() Returns the response body data as binary

void setBodyBytes(byte [] arrayByte) Changes the response body to content of arrayByte.


This method sets the BinaryFlag to ‘true’ automatically.

String toString() Returns the entire response as String

long id() Returns the ID of the response

String getThinkTimeSpec() Returns the time difference passed by between the request and this
corresponding response, called ‘Think time’

void setThinkTimeSpec() Changes the ‘Think time’ of the response.

ParameterList
Transaction requests and responses contain arguments, attributes and Metadata. Access to each of
them is provided by class ‘com.itko.util.ParameterList’. A ‘ParameterList’ object is a set of key/value
pairs. Methods of this class are available to both requests and responses:
ParameterList getArguments() Retrieves the set of arguments from request or response

void setArguments (ParameterList args) Changes the set of arguments

ParameterList getAttributes() Retrieves the set of attributes from request or response

void setAttributes (ParameterList args) Changes the set of attributes

ParameterList getMetaData() Retrieves the Metadata from request or response

void setMetaData (ParameterList args) Changes the Metadata

Boolean isDupesAllowed() Indicates whether or not duplicate transactions are allowed in


the Virtual Service

void setAllowDupes(boolean bFlag) Sets the flag to indicate whether or not duplicate transactions
are allowed in the Virtual Service.

void addParameter(String strKey, String strVal) Sets a single parameter as key/value pair

void addParameters(String strParams) Sets multiple parameters at once. Key and value are separated
by ‘=’, multiple key value pairs are concatenated by ‘&’.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 18 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Sample:

String getParameterValue(String strKey) Returns the value of a parameter given by strKey.

void setParameterValue(String strKey, String strVal) Changes value of parameter strKey to strVal.

void removeParameter(String strKey) Removes parameter strKey from parameter list

void clear() Removes all parameters from list

For additional methods available on ‘com.itko.util.ParameterList’ please see *5+.

Security
You cannot call ‘System.Exit’ or ‘System.Exec’ from scripts. This is to prevent terminating the java
process that runs the embedded script or running malicious scripts.

Logging
The injected ‘_logger’ variable logs data to the log file of the DevTest component that the script is
executed within.

_logger
The injected variable ‘_logger’ is a SLF4J logger (http://www.slf4j.org/manual.html) with namespace
‘com.itko.lisa.script.logger’. Log level is set to INFO level by default, so a script can call something like
_logger.info("foo") and that will show in the relevant log file (simulator.log, vse.log,
workstation.log).
The log level for ‘com.itko.lisa.script.logger’ can be set to other values (e.g. DEBUG) in
‘logging.properties’. Then any calls to _logger.debug(“A debug message, my x value is ,- and my y value
is ,-”, x, y) will be printed to the log file.
The default ‘logging.properties’ file does not contain a log level setting for ‘com.itko.lisa.script.logger’.
So, the following line has to be added to {{LISA_HOME}}/logging.properties to enable different settings.
# for logging of scripts
log4j.logger.com.itko.lisa.script.logger=DEBUG

Possible log level values are:


• OFF – switches off logging
• ERROR – report error logs (_logger.error()) only. Errors have a serious impact to functionality
• WARN – report warning (_logger.warn()) and error logs only. Warnings can have an impact to
expected functionality
• INFO – report informational (_logger.info()), warning and error logs only. Informational logs are
for informational purposes only and are not supposed to have an impact to functionality
• DEBUG – report debug (_logger.debug()), informational, warning and error logs only. Debug logs
are additional informational logs that should support error analysis.
• ALL – report any log, including trace logs (_logger.trace()). Trace logs are intended for extended
diagnostic requests.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 19 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Sample 1
The following script snippet
_logger.error("ERROR: Sample script test - false");
_logger.warn("WARN: Sample script test - false");
_logger.info("INFO: Sample script test - false");
_logger.debug("DEBUG: Sample script test - false");
_logger.trace("TRACE: Sample script test - false");

And a setting of in {{LISA_HOME}}/logging.properties


# for logging of scripts
log4j.logger.com.itko.lisa.script.logger=ALL

Creates following log file output:

Changing the setting in {{LISA_HOME}}/logging.properties to


# for logging of scripts
log4j.logger.com.itko.lisa.script.logger=INFO

Generates:

Sample 2
The following script snippet demonstrates how to pass parameters of different types to a ‘_logger’ call
using ‘,-’ as place holders in the output string:
String p1 = "one";
int p2 = 2;
long p3 = 3;
double p4 = 4;
boolean p5 = true;
String[] p6 = {"five", "six"};
_logger.error("\nThis is an error message with parameters > {} {} {} {} {} {} <",
p1, p2, p3, p4, p5, p6);

This leads to following output:

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 20 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Sample 3
Even complex objects can be logged. Following snippet logs content of injected variable ‘testExec’:
_logger.error("\nThis is testExec > {} <", testExec);

And generates following output:

Events
‘testExec’ supports methods for pushing a TestEvent with an EVENT_LOGMSG Event ID:
 ‘log()’ – ‘Log Message’ event
 ‘warn()’ – ‘Step Warning’ event
 ‘raiseEvent()’ – custom event

testExec.log()
This is a convenience method for pushing a TestEvent with an EVENT_LOGMSG Event ID to the event system. This
method comes with two different signatures:
 ‘testExec.log(String shortMsg)’
 ‘testExec.log(String shortMsg, String longMsg)’.
Following Code snippet applies both signatures:
testExec.log(“Sample single script test – false);
testExec.log(“Sample Log”, “Sample script test – false);

Creates following events (when started in ITR)

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 21 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

testExec.warn()
This method raises a warning message into the events for this test. For scripts it supports two
signatures:
 ‘testExec.warn(String shortMsg)’
 ‘testExec.warn(String shortMsg, String longMsg)’
The following Code snippet
testExec.warn(“Sample short Warning – false);
testExec.warn(“Sample long Warning”, “Sample script test – false);

Creates following events (when started in ITR):

testExec.raiseEvent()
Previously described testExec methods raise specific events ‘Log message’ or ‘Step warning’ to the event
system. Method ‘testExec.raiseEvent()’ enables raising custom events with the event system.
Custom events must be specified in ‘lisa.properties’ before they can be used. Custom event numbers
must start at 101. To define custom events 101 and 102, for instance, add following lines to
‘lisa.properties’:
#=====================================
# DevTest Testing Stuff
#=====================================
lisa.test.custevents=&101="Custom Event 101";&102="Custom Event 102"

There are multiple raiseEvent() signatures available. For details please see the Javadoc on the SDK [5].
The following one is recommended to use:
 public void raiseEvent(int event,java.lang.String shortDesc, java.lang.String longDesc)
Parameters have following meaning and effect:
1. event – this is the Event ID to use
2. shortDesc – the small-ish data associated with the event
3. longDesc – the long description can have much larger data associated

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 22 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

The following code snippet creates


testExec.raiseEvent(101,”Short Msg“, “Long Message“);

This output in the list of test events:

Starting with DevTest 8.0.2 colors can be assigned to the custom events. This is optional but the color
will be used by the workstation test event panel if is defined. The colors are based on hexadecimal
encoding. For some examples please see http://en.wikipedia.org/wiki/Web_colors.
This feature can also be used to override the default colors in the event table.
With the above settings for custom events 101 and 102 and the additional settings in ‘lisa.properties’
#=====================================
# DevTest Testing Stuff
#=====================================
# here we are assigning 'tomato' and 'mediumPurple' to events 101 and 102
lisa.test.custevents.colors=101=FF6347&102=9370DB

The following code snippet creates


testExec.raiseEvent(101,”short Msg“, “long Message“);
testExec.raiseEvent(102,”short Msg“, “long Message“);

This output in the list of test events:

Sharing Data
DevTest supports sharing data between its processes. Non-persistent data can be shared between VSMs
on the same VSE. Persistent data are stored in the reporting database and can be shared across
processes running with the same registry.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 23 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

SharedModelMap
Sometimes non-persistent data needs to be shared across virtual services. The ‘SharedModelMap’
object supports this requirement. ‘SharedModelMap’ enables exchange of data by keys.
One VSM can do something like this (taken from scriptable DPH sample below):
com.itko.lisa.vse.SharedModelMap.put(“transactionName”, “currentOperation”, fileToSave);

And another VSM can retrieve the key’s value as follows:


String fileName = com.itko.lisa.vse.SharedModelMap.get(“transactionName”, “currentOperation”);

The first parameter in both calls is the optional namespace. It is optional but recommended so that keys
are distinguished by different namespaces and unique within a namespace.
SharedModelMap supports following methods. For each method there is a variant available with and
without specification of a namespace:
int size() Returns the number of entries in the default or
int size(String nameSpace) specified namespace, respectively.

boolean isEmpty() Returns whether or not the (default or


boolean isEmpty(String nameSpace) specified) namespace is empty.

boolean containsKey(String key) Returns whether or not the (default or


boolean containsKey(String nameSpace, String key) specified) namespace contains an entry with the
given key.

boolean containsValue(Object key) Returns whether or not the (default or


boolean containsValue(String nameSpace, Object key) specified) namespace contains an entry with the
given value.

Object getObject(String key) Gets a value from the (default or specified)


Object getObject(String nameSpace, String key) namespace.

String get(String key) Gets a value from the (default or specified)


String get(String nameSpace, String key) namespace cast as a string.

Object putObject(String key, Object value) Puts a value into the (default or specified)
Object putObject(String nameSpace, String key, Object value) namespace.

String put(String key, String value) Puts a value into the (default or specified)
String put(String nameSpace, String key, String value) namespace cast as a string, and returns the
currently known value of the key cast as a
String.

String remove(String key) Removes a value from the (default or specified)


String remove(String nameSpace, String key) namespace, and returns the currently known
value of the key cast as a String

void clear() Clears the (default or specified) namespace


void clear(String nameSpace)

Set<String> keySet() Returns the set of keys currently known in the


Set<String> keySet(String nameSpace) (default or specified) namespace. The returned
set will never be null.

void setCapacity(String nameSpace, int newCapacity) Resizes the capacity of the specified namespace

Each unique namespace is backed by a map that is restricted to a default capacity of 256 key/value
pairs. Each namespace has a LRU (Last Recently Used) map created on demand the first time the
namespace is used. It's backed by an ‘org.apache.commons.collections.map.LRUMap’. The LRU map
determines which map entry to remove if there is no capacity left.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 24 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

SharedModelMaps are not persisted across VirtualEnvironmentService restarts.

PersistentModelMap
DevTest (>7.1.1.141) provides a convenient mechanism to store arbitrary key/value pairs in its reporting
database. The Registry provides a java API and it is also exposed as a RESTful service by the DevTest
console.
Persistent maps are accessed by namespace and key. Values must be Strings. To store complex objects
then the user is responsible for serialization using libraries such as XStream. By default key/value pairs in
persistent model maps expire over time.
There are 4 basic APIS which are declared in PersistentMap and are implemented by
‘com.itko.lisa.coordinator.TestRegistry’:
String getMapValue(String nameSpace, String key) Gets a value from the specified namespace cast
as a String.

String putMapValue(String nameSpace, String key, String value) Puts a value into the specified namespace, and
returns the value of the key cast as a String.

String removeMapValue(String nameSpace, String key) Removes a value from the specified namespace,
and returns the value of the key cast as a String

Map<String,String> getAllMapValues(String nameSpace) Returns all key/value pairs in a given


namespace. Values are cast as Strings.

Restful API
Access to PersistentModelMap is also available by a RESTful API:
GET http://localhost:1505/lisa-invoke/persistentMap/namespace/key Returns the value of ‘key’ in ‘namespace’

GET http://localhost:1505/lisa-invoke/persistentMap/namespace Returns all key/value pairs in namespace


(equivalent to getAll)

PUT http://localhost:1505/lisa-invoke/persistentMap/namespace/key/value Set ‘key’ in ‘namespace’ to ‘value’

POST http://localhost:1505/lisa-invoke/persistentMap/namespace/key Set ‘key’ in ‘namespace’ to requestBody

DELETE http://localhost:1505/lisa-invoke/persistentMap/namespace/key Removes ‘key’ in ‘namespace’.

Shared Data expiration


‘key/value’ pairs are deleted by the registry when they expire. The relevant data expiration properties
are set in ‘lisa.properties’ files. The default values are as follows:
lisa.persistent.map.delete=true whether to expire the data at all

lisa.persistent.map.delete.cycle=10m check for expired entries every ten minutes

lisa.persistent.map.delete.age=30d delete entries older than 30 days

The timestamps on key/value pairs are updated whenever an entry is added, updated or retrieved.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 25 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Sample
The following sample sets, retrieves and removes values to keys persistently to the reporting database:
 #1: create the persistentModelMap object
 #4: set ‘key’1’ to ‘value1’
 #5: set ‘key1’ to ‘value2’ and return previous
value
 #6: retrieve current value of ‘key1’
 #7: set ‘key1’ to ‘value3’ and return previous
value
 #8: remove ‘key1’ and return previous value

Debugging
Scripts cannot be debugged by an attached debugger. Using ‘_logger’ for debugging scripts and
breakpoints on custom java code called by the script might help.
Best practice is to set the log level for scripting to DEBUG or ALL (Logging) and to use ‘_logger.debug()’
when developing. When in production the log level is then set to INFO. With log level of INFO the data of
script calls ‘_logger.debug()’ will actually not be logged. Otherwise it would have a negative impact to
performance.
The actual DevTest infrastructure that runs the script has a logger that you can set to DEBUG level –
‘com.itko.lisa.test.ScriptExecHandler’.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 26 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Editor
For all the scripted extensions there is a Script Editor in context available. The editor comprises of four
sections
 Configuration area: specifies the language that will be used for scripting, the scope of properties
that will be available for the script and context related effects of the script.
 Code editor – contains the script
 Object selector – lists the objects and properties available to the script
 Status/Action area – located at the bottom of the editor, containing information about cursor
position in the editor, writing mode, read-only status, and – depending on the context a button
to test the script.

Configuration area

Code Editor Object Selector

Status Area

Configuration Area
The configuration area includes specifications of the script’s context, how to react on the script’s result
or a failure when executing the script.
Common to configuration areas of all script extensions are the specifications of the
 Scripting language
 Scope of available objects and properties
Out of the box script languages
 Beanshell
 Groovy
 JavaScript
 Velocity
Are available.
Additional languages can be added on demand
(Enabling additional Scripting Languages)

Specification of the scope of available


properties and objects:

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 27 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

‘Copy properties into scope’


 Test state and system properties: all
properties for the test case and system. This
is the same scope as in previous product
versions
 Test state properties: properties that provide
information about the test case
 TestExec and logger only: only the TestExec
and logger objects are available to the script
(recommended)

Object Selector
Depending on the selection in drop-down list ‘Copy properties into scope’ the objects available for use
in the script editor are listed in the ‘Available Objects’ panel to the right of the screen. The list includes
primitive types of data (strings and numbers) and objects such as EJB response objects that were
executed in the test case.
The drop-down list includes
• Test state and system properties: all properties for the test case and system. This is the
same scope as in previous product versions
• Test state properties: properties that provide information about the test case
• testExec and logger only: only the testExec and logger objects are available to the script
(recommended)
Notes:
• The less objects and properties are required by the script the better the performance to
start the script.
• Properties can also be retrieved via testExec.
Double-click an entry in the Available Objects table to paste that variable name into the editor area.
testExec and logger only

Available test state properties


The screenshot shows a subset only

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 28 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Available test state and system properties


The screenshots show a small subset only

Code Editor
The code editor can be configured to display line numbers, a toolbar at the top and a status bar at the
bottom.
Clicking on the left bar of the editor brings up a
menu to add or remove
 Line numbers to the script
 A menu bar on top of the editor
 A status bar at the bottom of the editor

The Toolbar icons mean from left to right


(Script Editor Toolbar)
 (greyed out) Returns you to the last edit that
was made (Ctrl + Q)
 Finds the next occurrence of the selected text
(Ctrl + F3)
 Finds previous occurrence (Shift F3)
 Finds next occurrence (F3)
 Toggles the highlight search (Alt+Shift+H)
 Shifts the current line to the left four spaces
(Alt+Shift+KeyPadLeft)
 Shifts the current line to the right four spaces
(Alt+Shift+KeyPadRight)
 Inserts comments slashes (//) at the cursor
position
 Removes the comments slashes

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 29 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Editor for scripting.

 Status bar:
On the bottom left hand side the cursor
position is displayed, and whether the editor
mode is set to INSert or OVerRide.

Status area
The status area contains the status bar information of the code editor and for some scripted extensions,
such as the ‘Execute Script (JSR-223)’ test step a button to start a test of the script. For some scripted
extensions, such as ‘Scripted Assertion’ this ‘Test’ button is integrated in the ‘Configuration Area’.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 30 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Scripted Expression
Expressions in DevTest, such as {{=<expression>}}, can be scripted. Using {{=%<language specifier>%
<script code>}} the runtime environment starts the selected scripting engine to execute <script code>.
For the scripting languages available in DevTest out of the box the following language specifiers are
defined
 BeanShell: %beanshell%, %bsh%
 Groovy: %groovy%, %Groovy%
 JavaScript: %js%, %javascript%, %JavaScript%, %ECMAScript%, %ecmascript%
 Velocity: %velocity%, %Velocity%

Sample
DevTest installation comes with a sample test case ‘scripting.tst’ in the ‘examples’ project. This test case
includes a step ‘Embedded expressions’, which is an ‘Output Log Message’ step.
To open the log message editor click on the
‘Output Log Message’ node in RHP

This log snippet includes scripted expressions


for each of the scripting engines available out of
the box.
The script section starts at ‘,,=%<language
specifier>%’ and ends at ‘--’.
Expression in line #28 returns the default
scripting language as configured in
lisa.properties.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 31 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

After execution the scripted expression create


the output at the left side.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 32 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Test Step - Execute Script (JSR-223)


A test step is a workflow test case element that performs a basic action to validate a business function in
the system under test. Steps can be used to invoke portions of the system under test. These steps are
typically chained together to build workflows as test cases in the model editor. For each step, you can
create filters to extract data or create assertions to validate response data. For details please see
Elements of a Test Step).
The ‘Execute Script (JSR-223)’ step lets you write and run a script to perform some function or
procedure. This step has been introduced in DevTest 8.0 and replaces ‘Java Script Step (deprecated)’
(Java Script Step (deprecated)) going forward.

DevTest Product Documentation


 [1] - DevTest Solutions: Using the Workstation and Console with CA Application Test – Elements of a
Test Step
 [2] - DevTest Solutions: Reference – Execute Script (JSR-223) Step
 [3] - DevTest Solutions: Reference – Java Script Step (deprecated)

Input Parameters
Other than the selected injected variables and properties the script does not have any specific input
variables. Input data are retrieved from properties, usually.
As mentioned before, to support test cases for mobile applications variable ‘_webDriver’ is available
since DevTest 8.0.1 to access the MobileSession object while the test is running. Please see Scripts in
Mobile Testing.

Output Parameters
It is best practice to supply a return value of scripts, if supported by the scripting engine.

As mentioned before, JavaScript does not support the concept of explicit return values in scripts.
BeanShell and Groovy, however, do.
A script in ‘Execute Script (JSR-223)’ test steps does have to supply a specific return value. If no return
value is specified the last evaluated expression is taken as the script’s response. This applies to
BeanShell, Groovy, and JavaScript.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 33 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

By default, following properties are set when execution of the script is finished:
 ‘LASTRESPONSE’ – contains the script’s return value
 ‘lisa.<step name>.rsp – also contains the script’s return value
Other properties can be set by the script explicitly, using ‘testExec.setStateValue()’.

Logging output
The script can be started in different ways, which has an impact to the logging output
• Pressing the ‘Test’ button in the Script Editor: ‘_logger’ output is in workstation.log
• Starting the test case in ITR: ‘_logger’ output is in workstation.log
• Submitting the test case to ‘Stage a Quick Test’
o Stage Local (No Coordinator Server): ‘_logger’ output is in workstation.log
o Coordinator@Default: ‘_logger’ output is in simulator.log
• Submitting the test case to ‘Stage Test’: ‘_logger’ output is in simulator.log

Editor
The editor to create a script opens in context of the ‘Execute Script (JSR-223)’ test step.
Open a test case, right click into the empty area,
select ‘add step > Custom Extensions > Execute
script’ from context menu to add a Custom
Script step select.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 34 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

 ‘If environment error’ setting specifies the


action to execute in case of a test step
failure.
 Language – determines the scripting
language of the scripted assertion
 ‘Copy properties into scope’
 Test state and system properties: all
properties for the test case and system
 Test state properties: properties that
provide information about the test
case
 TestExec and logger only: only the
TestExec and logger properties
(recommended)
 ‘Run Assertion’ – to open a window with the
result of the script execution or a description
of the errors that occurred.

At the bottom of the editor is a ‘Test’ button to


test the script.

Sample
This code sample takes a date, a date format and calculates a new date with a difference of a given
amount of days. The difference of days can be positive or negative, and the new date must not be on a
weekend. If it is on a weekend Monday after it is returned as the new date.
Input properties of this ‘Execute Script (JSR-223)’ test step are:
 ‘myStartDate’ (optional) – defines the date to start calculation from. Default value: today
 ‘myOffset’ (optional) – defines the number of days to add/subtract from start date. Default
value: -8
 ‘myFormat (optional)’ – defines the date format to return the new date. Default value:
‘M/d/yyyy’, sample output: ‘2/9/2015’ = Feb 2nd, 2015.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 35 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Output properties of this test step are:


 ‘LASTRESPONSE’ – contains a test step response by default
 ‘lisa.<step name>.rsp – also contains a test step response by default
 ‘myNewDate’ – contains output of this script, as it was set explicitly by the script code.
 #15: import of java class needed for
calculation
 #19 - #21: retrieve input properties with
default values
 #23: if no start date is given take today’s
date
 #24: create a SimpleDateFormat object
to format Date objects correctly
 #29: set the new Date object to the old
one plus the difference of days
 #33: Specify the date format that returns
the day of the week as number
 #36: convert the return string to an
integer
 #38,#39: check for Saturdays and
Sundays, and add additional days to end
up on Monday
 #42: format the new date according to
the requested format
 #44: set property ‘myNewDate’ to the
new date
 #47: return the new date as the test
step’s response.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 36 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Scripted Assertion
The Scripted Assertion lets you write and run scripts to verify the expected outcome of a test step. The
script’s result must be a Boolean. Otherwise, false is returned.

DevTest Product Documentation


 [1] - DevTest Solutions: Using the Workstation and Console with CA Application Test – Scripted
Assertion

Input Parameters
Other than the selected injected variables and properties the script does not have any specific input
variables. Input data are retrieved from properties, usually.

Output Parameters
The script must return a Boolean value. Otherwise, false is returned.

Logging output
The Scripted Assertion logs data to the same log file as the test case and its test steps do.
• Pressing the ‘Test’ button in the Script Editor: ‘_logger’ output is in workstation.log
• Starting the test case in ITR: ‘_logger’ output is in workstation.log
• Submitting the test case to ‘Stage a Quick Test’
o Stage Local (No Coordinator Server): ‘_logger’ output is in workstation.log
o Coordinator@Default: ‘_logger’ output is in simulator.log
• Submitting the test case to ‘Stage Test’: ‘_logger’ output is in simulator.log

Editor
The script editor for a scripted assertion opens in context of a test step.
In the Test case, select a test step, expand the
‘Assertions’ on LHP and click the ‘+’-sign to open
the context menus for the various assertions
available out of the box.

From context menu select


‘Other > Scripted Assertion’, which opens the
editor

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 37 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

 Name – specifies the name of the assertion


occurring in the list of assertions
 ‘If’ clause specifies the condition of the
script’s return value when the assertion will
trigger
 ‘Then’ defines the action to execute when
the condition is met
 Log – specifies the event text to print to the
event log when the assertion triggers
 Language – see Configuration Area ‘Copy
properties into scope’ – see Configuration
Area and Object Selector
 ‘Run Assertion’ – to open a window with the
result of the script execution or a description
of the errors that occurred.

Sample
These samples show how to return Boolean expressions in Scripted Assertions for the different scripting
languages. The Scripted Assertions samples are contained the ‘scripting.tst’ test case, which is part of
the examples project of DevTest 8.0.
This BeanShell sample is quite straight forward.
It checks if property LASTRESPONSE equals the
given static string. Return value is the result of
this evaluation.

This Groovy script similarly returns the result of


the equality check of strings, leveraging the ‘tr’
method, which is special to Groovy.
‘tr’ translates characters from source set (“I”) to
characters from replacement set (“i”), similar to
the Unix ‘tr’ command’.

JavaScript does not have a concept of a ‘return’


statement outside of functions.
The return value of a JavaScript based Scripted
Assertion is the value of the expression
evaluated last.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 38 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Virtual Service Router Step


DevTest Service Virtualization supports multiple modes to execute a virtual service. Please see VSE
Console Request Events Details Tab for details.
Within a Virtual Service Model this protocol-independent step routes a client request from a protocol-
specific virtual service listen step to the protocol-specific response selector step or to the live invocation
step, or to both. The decision is made based on the current execution mode for the running model.
Only when running in DYNAMIC mode, the actual mode is determined by a sub-process or a by a script.
The return value of either one determines the actual mode virtual service model is running in. By
default, a script is run. The default script evaluates to EFFECTIVE mode.
Currently, the step supports the BeanShell scripting engine only.

DevTest Product Documentation


 [1] - DevTest Solutions: Using Service Virtualization – Virtual Service Router Step

Input Parameters
Other than the selected injected variables and properties the script does not have any specific input
variables. Input data are retrieved from properties, usually.

Output Parameters
This script must return either an ‘enum’ entry from class ‘com.itko.lisa.vse.ExecutionMode’ or a string
that is the name of an enum entry. The DYNAMIC entry may not be returned. The script will be
executed for DYNAMIC execution mode only.
Possible return values are:
Model Behavior String Enum
Most Efficient "EFFICIENT" ExecutionMode.EFFICIENT
Tracking “TRACK” ExecutionMode.TRACK
Live Invocation “LIVE” ExecutionMode.LIVE
Learning “LEARNING” ExecutionMode.LEARNING
Fail Over “FAILOVER” ExecutionMode.FAILOVER
Image Validation “VALIDATION” ExecutionMode.VALIDATION
Dynamic “DYNAMIC” ExecutionMode.DYNAMIC

Logging output
The ‘Virtual Service Router’ step script support the ‘_logger’ variable. During replay logging output is
part of VSE logging output and this is directed to vse.log.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 39 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Editor
This editor has not changed (yet) from previous versions. Currently it does not support a visual script
language selector. However, the scripting language can be determined by a language specifier (e.g.
%groovy%). The only object and property scope currently supported is ‘test state and system
properties’.

Setting scripting language


At the beginning of a script the scripting language can be configured by a language specifier
%<scripting_language>%.
For the scripting languages available in DevTest out of the box the following language specifiers are
defined
 BeanShell: %beanshell%, %bsh%
 Groovy: %groovy%, %Groovy%
 JavaScript: %js%, %javascript%, %JavaScript%, %ECMAScript%, %ecmascript%
 Velocity: %velocity%, %Velocity%
The language specifier must be the first statement in the script.
In the virtual service model, select the Virtual
Service Router Step.
In ‘Step information’ click
‘Virtual Service Router’ to open the associated
script editor.
This editor does not (yet) support language
selection nor variable scoping.
It supports BeanShell as scripting language only.
All test states and system properties, plus
injected testExec and _logger variables are
available.

There is a radio button to select whether the


execution mode should be determined by a
subprocess or by a script, which is the default
selection.
In the upper right corner a ‘Test’ button starts a
script test.
The remainder of the editor is the same as
described in Editor.

Sample
This sample script returns the value of a test state property, which contains the intended VSE execution
mode for this virtual service model.
For demo purposes a project property
‘AA_VSM_Eexec_Mode’ is added with the value
of ‘LIVE’.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 40 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

The script imports the ‘ExecutionMode’ java


class and returns EFFICIENT as the current mode
to execute the virtual service in.
It attempts to store property
‘AA_VSM_Exec_mode’ in variable ‘mode’.
If the property exists and contains a value this
value is stored. Otherwise, the default string
‘EFFICIENT’ is stored in the variable.
Running the script by the ‘Test’ button verifies
that the property is available and set, and used
as the return value of the script.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 41 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Match Script in Virtual Service Images


Match Scripts are used in VSE to identify a transaction in VSI that matches an incoming request. A Match
Script is the mean to implement a custom matching algorithm that is not covered by the built-in
matching algorithms, which come with DevTest 8.0 out of the box.
DevTest Product Documentation
 [1] - DevTest Solutions: Using Service Virtualization - Match Script Editor

Input Parameters
A Match Script has following injected variables
 com.itko.lisa.vse.stateful.model.Request sourceRequest: contains the recorded request object from VSI
to compare against
 com.itko.lisa.vse.stateful.model.Request incomingRequest: contains the live request object received
from service client.
 com.itko.lisa.vse.RequestMatcher defaultMatcher(): executes the default matching logic.
Please see VSE Transaction Request for available methods of objects ‘incomingRequest’ and
‘sourceRequest’.
Access to arguments, attributes and metadata of transaction requests is handled by class
‘ParameterList’. For available methods of this class please see ParameterList.

Output Parameters
A Match Script must return a Boolean value to determine outcome of the matching calculation. A return
value of ‘true’ means a matching transaction was found.
Instead of returning a Boolean value explicitly, the Match Script can call ‘defaultMatcher.matches()’to
fall back to the default matching logic for further evaluation (see sample).
If there is an error evaluating the script, VSE deliberately ignores the error and defaults to the regular
matching logic.

Logging Output
It is recommended to add logging and tracing into match script and to embed calls to the VSE matching
logger. The VSE matching logger produces the messages in the vse_xxx.log file, where xxx is the service
image name. For example, the log file of a virtual service ‘kioskV6’ appears as in the respective directory:

The log level of INFO value typically reports every failure to match. If messages are logged at INFO level,
later when the production settings are applied to the logging.properties file, the log level is set to WARN
and log messages appear as a DevTest test event (a "Log Message" event), but do not appear in the log
file.
To simplify debugging, keep a separate log for VSE transaction match/no-match events. For production
systems change INFO to WARN in following line of ‘logging.properties’:

If you want to disable VSE logging, do not comment out this line, but set the property value to OFF.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 42 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Match Script Editor


The Match Script editor is integrated into the virtual service image (VSI) editor. To open the Match Script
Editor, open a virtual service image.
With the VSI Editor select the ‘Transaction’ tab.
Pick and select a transaction,

In the bottom part of the LHP select the


response of the transaction that will host the
Match Script. Each transaction response can
have a different Match Script.

In the RHP expand the ‘Match Script’ node of


the selected transaction response
Like any other of the script editors right click on
the border of the editor and select any option to
add a tool bar, line numbers and a status bar

Apart from well-known information the status


area of the editor includes the drop-down list to
select the scripting engine.
There is also a check box to deactivate the
script. If deactivated the script is not called to
identify the matching request, but the regular
match algorithm is used instead.

There is no button to run a local test of the script. Thus, scripts cannot be tested within context.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 43 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Sample 1
The editor includes an option to add a sample Match Script.
With the VSI Editor select the ‘Transaction’ tab.
Pick and select a transaction, expand the ‘Match
Script’ node.
Right click into the editor area and select the
‘Insert sample match script’ menu

 #18: This scripts first checks (#18) if the


incoming live request from client includes an
operation ‘SampleRequest’.
 #19: If it does not the default matching logic
is executed by calling
‘defaultMatcher.matches()’.
 #21: If it includes an operation
‘SampleRequest’ then the operation name
and the first three chars of parameter
‘SomeParameterName’ are compared from
the live request and the recorded request.
 #25: If both match true is returned to
indicate the matched recorded request has
been identified.
 #31: if there is no match between live and
recorded request false is returned.

Sample 2
The second sample uses the kioskV6 virtual service that is part of the examples project in DevTest
workstation. The ‘kioskV6.vsi’ is extended by a Match Script that adds logging information to the
recorded transactions to visualize the execution order.
 #7: the call logs the operation of the
incoming client request (live) and the source
(recorded) request.
 This sample code identifies the META
response of the ‘getNewToken’ transaction

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 44 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

The match script is added to each of the


transactions META and specific definition.

Once the Match Scripts are completed the VS


needs to be deployed and the transactions with
Match Scripts in the service called.

Logging into the ‘kiosk’ sample application and


logging out again produces the following log file
content

The first two logs show the execution of the


META and the specific match scripts for
‘getNewToken’, which is called upon log in.
These log show that the operation match.
The remaining five logs are logs of the match
scripts of the META definitions for all the
transactions showing that the operations do not
match.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 45 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Scriptable Data Protocol


A data protocol defines the payload of a transport protocol. The Data Protocol Handler (DPH) is
responsible for parsing and translating requests from live service client or responses from live or virtual
services, or both of them.
The Scriptable Data Protocol is available for situations where you need a small amount of processing on
the live request, the live or virtual response, or both when recording or playing back a Virtual Service.
DPHs can be ‘daisy-chained’, meaning the output of one DPH is passed as input to the next one.
Note: It needs to be verified if Scriptable DPHs support ‘daisy-chaining’. Current assumption is that
Scriptable DPDHs do not, but are always executed first.
DevTest Product Documentation
 [1] - DevTest Solutions: Using Service Virtualization - Scriptable Data Protocol

Scripts
The Scriptable Data Protocol comprises of three scripts:
 Request script – to make data from client requests available for processing by DevTest
 Live Response script – to make data from live service responses available to DevTest processing
 Playback/Virtual Response script – to format the response from Virtual Service to suit the
client’s response requirements.

Request Script
This script is to parse the incoming request and generate the entries DevTest needs to identify the
incoming client request. At minimum, it will need to define the name of the operation and add
parameters for DevTest to match against. This script is used during recording and playback.

Response Script for generation of Virtual Service


DevTest can use text response payloads, binary ones, JSON ones or XML ones. The most human-
readable of these is often XML, and it is most integrated with DevTest auto-correlation and time-shifting
facilities (magic dates and magic strings) so the purpose of the generation response script is to parse the
response from live service and store it as a set of XML values that can be viewed by testers and
developers in DevTest Workstation.

Response Script for playback of Virtual Service


The response will need to be parsed from how DevTest Workstation has displayed it above. This script is
to take the mashed response and reformat it back to the format that the client application requires.

Input Parameters
The request script has access to injected variable ‘lisa_vse_request’. This variable gives access to
elements of the client request. Please see VSE Transaction Request for available methods.
The response scripts have access to injected variable ‘lisa_vse_response’. This variable gives access to
elements of the live or the virtual response. Please see VSE Transaction Response for available methods.
Access to arguments, attributes and metadata of requests and responses is handled by class
‘ParameterList’. For available methods of this class please see ParameterList.

Output Parameters
There is no specific output parameter required.
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 46 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Logging output
The DPH scripts support the ‘_logger’ variable. During recording logging output is part of the
workstation log.
When deployed to VSE logging output is directed to vse.log.

Editor
Scripted Data Protocol Handlers are created when configuring the Service recorder in DevTest
Workstation. Once the service recording is completed, data protocol handlers are configured for the
request, the live and the playback responses.
Note: Unless the recorder setup is saved at the very last step of the recorder wizard the code of scripted
DPH cannot be retrieved once the virtual service is created. Therefore it is strongly recommended to
save DPH script code in an external editor.

Clicking on the ‘+’ button adds a new row of


Data Protocols to each of the lists.
From dropdown list the ‘Scriptable Data
Protocol’ is available

The next screen opens the script editor for the


request-side Scriptable DPH.

The next screen opens the script editor for the


both response-side Scriptable DPHs.

Best Practices
Developing a DPH is cumbersome with regard to testing and debugging. First and foremost
recommendation for debugging scripts is always to set the log level for scripts to DEBUG or ALL (see
Logging). Second recommendation is then to take advantage it by making extensive use of
Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 47 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

‘_logger.debug(“{}”; value)’ statements. Check ‘workstation.log’ for exceptions and logging output and
expand the DevTest System Message panel from the bottom of the Workstation window by double click
on ‘System Messages’

DPH Test using ‘Execute Script (JSR-223)


A recommended approach is to test the DPH script code with an ‘Execute Script (JSR-223)’ test step if
possible. Sample 1 below demonstrates how code would look like that can be used in both DPH and in a
test case. Main difference is that when used in a test case the transaction request or response is read
from properties instead. VSE passes transaction request and responses in by injected variables.

DPH Test within VSE Recorder


Following recommendations might help when testing the DPH within the VSE recorder:
1. Load the saved VSE recorder settings for
the next test cycle upon re-launch of the
recorder wizard.
2. Following parameters are not set when
loading a .vrs file
a. ‘Write image to’
b. ‘Import traffic’
c. ‘Model file’
3. Test with traffic that was recorded
beforehand.
a. Import the recorded traffic via ‘Import
traffic’ combo box.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 48 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

4. For debugging purposes keep parameter


‘Treat all transactions as stateless’
unchecked. This will make sure to have an
intermediate wizard step available to check
for exceptions reported by the scripting
engine, and to return to the script editor.
5. Make sure not to override the existing raw
traffic file when re-launching the wizard for a
new test cycle. Otherwise the traffic file
might contain data modified by the DPHs.
a. Make sure list box ‘Export traffic’ is
empty or has a different file path than
‘Import traffic’

6. Prior to clicking ‘Next’ on the screen below


check for any exceptions in
workstation.log, particularly for exceptions
of scripting engines.
7. After pressing the ‘Next’ button there is
no way to return to the script editors

8. At the end of the wizard save the recorder


settings in a .vrs file to save the latest DPH
script code.
9. Always have a backup copy of the latest
Scriptable DPH version in an external
editor.
10. In case the latest recorder settings are not
saved in a .vrs file there is no way to
retrieve a copy of the latest script source
code

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 49 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Errata
Out of the box in DevTest 8 there is sample code added to each of the DPHs. However, with current
DevTest 8 versions and latest LISA versions method ‘addParameter(String key, String value)’ is not
supported.
// Adding parameters

p.addParameters("key1=val1&key2=val2"); // many at once

p.addParameter("key3", "val3"); // one at a time

Javadocs (*5+) for class ‘ParameterList’ does not contain a method with this signature.
Please see Sample 2 below how to use ‘addParameter(String label, String key, String value)’ instead.

Sample 1
This DPH sample records the request sent from client and the live responses sent by the live services in a
file. The request-side DPH exchanges data with the response-side DPH using a ‘SharedModelMap’.
Recorded requests and responses are logged in individual files. File names comprise of the operation’s
name, the ID, a timestamp to make them unique, and an indicator whether the file contains a request or
response.

Request DPH
The following sample DPH logs requests from live client system. In order to test and debug main parts of
the Scriptable DPH in a test step, the script can either retrieve the client request from VSE or from a
property.
 #9: retrieval of message from property
 #10-#16: if retrieval from property fails it
means that the script is not run in a test step
but as part of a VSM in VSE. If retrieval fails
message content and arguments of operation
are retrieved from current request in VSE
 A property ‘runningAsVSE’ is set accordingly

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 50 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

 #23ff: If running in VSE message properties


are retrieved such as
o Operation
o Payload as binary or text depending on
content
o ID
o Request in String representation
o Operation’s arguments, attributes and
Meta data

 #44ff: If NOT running in VSE message


o Operation is hard coded as
‘myOperation’
o Payload is text
o ID is hardcoded as ‘0001’

 #52ff: Web service requests and responses


can contain forward slashed (‘/’),w hich may
interfere with file path definitions. So they
are replaced by underscores (‘_’)
 #54ff: calculation of a timestamp
 #59ff: calculation of the file path prefix,
comprising of the DevTest project path, its
‘/data/’ subdirectory, the operation’s name,
the message id, and the time stamp.
 #61: The file path prefix is stored in Shared
Model Map.
 #64: The file name is constructed based on
the file path prefix and the suffix that
determines whether it is a request or a
response. On the request side DPH the suffix
‘-req.txt’ is added.
 #65ff: retrieved message content is printed
to the file.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 51 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Response DPH
The following sample DPH logs responses from live service.
 #4ff: retrieval of response content, including
payload, meta data and – specific for the
response – the think time, as required by the
live service.
 #10: the file path prefix is get from
SharedModelMap where it was stored by the
Request DPH.
 #13: For the response log file the file path
name is completed yb the ‘-rsp.txt’ suffix
 #14ff: logging of the response data.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 52 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

Sample 2
The following Scriptable DPH example extends the list of arguments of an operation by an additional
argument:
%beanshell%

import com.itko.util.ParameterList;
import com.itko.util.Parameter;

// Retrieve transaction operation and arguments


_logger.debug("{}", lisa_vse_request.getOperation());
_logger.debug("All Arguments:");
ParameterList args = lisa_vse_request.getArguments();
_logger.debug("{}", args);

// Get the values of all parameters and concatenate all of them


String valueToAdd = "";
for(i=0;i<args.size();i++) {
_logger.debug("Argument {}", i);
Parameter thisParameter = args.get(i);
_logger.debug("{}", thisParameter);
thisName = thisParameter.getName();
thisValue = thisParameter.getValue();
// Replace string separators
thisValue = thisValue.replaceAll(" ", "%20");
// Extend the new string value
valueToAdd = valueToAdd + thisName + ":" + thisValue + "&";
}
if(i > 0) {
if(valueToAdd.length() > 5) valueToAdd = valueToAdd.substring(0, valueToAdd.length() - 1);
_logger.debug("Argument {} being added", i);
// Add a new parameter with label and key „combinedValue‟ to the list of parameters
// of the operation and assign to it the previously created value
args.addParameter(new Parameter("combinedValue", "combinedValue", valueToAdd));
_logger.debug("{}", valueToAdd);
// Update transaction request with the new set of arguments
lisa_vse_request.setArguments(args);

_logger.debug("All Arguments now:");


_logger.debug("{}",lisa_vse_request.getArguments());
}

This script logs following information for a LisaBank transaction:

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 53 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

Scripted Dataset
With DevTest 8.0.2 the use of ‘Scripted DataSet’ is supported.
The Scripted Dataset enables creation and usage of test data by a script. The script maintains the current
'state' of the dataset across calls using SharedModelMap or PersistentModelMap. It passes the map to
the test step for the test step to retrieve the value from the map.

DevTest Documentation
 [1] - DevTest Solutions: Using the Workstation and Console with CA Application Test – Data Sets

Input Parameters
Other than the selected injected variables and properties the script does not have any specific input
variables. Input data are retrieved from properties, usually.

Output Parameters
The script must return a SharedModelMap or PersistentModelMap map variable.

Editor
The script editor for a scripted dataset opens in context of a test step.
In the Test case, select a test step, expand the
‘Data Sets’ node and click the ‘+’-sign to open
the context menus for the various data sets
available out of the box.

From context menu select ‘Common


DataSets > Scripted DataSet’, which opens the
editor

 Name – specifies the name of the data set


 On the use of ‘Local’ and ‘Random’ please
product documentation on data sets [1].
 On settings for ‘Start over’ and ‘Execute’
please see product documentation on data
sets [1].
 Language – see Configuration Area
 ‘Copy properties into scope’ – see
Configuration Area and Object Selector

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 54 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

In the Test case, select a test step, expand the


‘Assertions’ on LHP and click the ‘+’-sign to open
the context menus for the various assertions
available out of the box.

From context menu select


‘Other > Scripted Assertion’, which opens the
editor

 Name – specifies the name of the assertion


occurring in the list of assertions
 ‘If’ clause specifies the condition of the
script’s return value when the assertion will
trigger
 ‘Then’ defines the action to execute when
the condition is met
 Log – specifies the event text to print to the
event log when the assertion triggers
 Language – see Configuration Area ‘Copy
properties into scope’ – see Configuration
Area and Object Selector
 ‘Run Assertion’ – to open a window with the
result of the script execution or a description
of the errors that occurred.

Sample
This sample shows how to maintain the current status of a scripted data set in a Shared Model Map and
how to pass the data to the test step. This Scripted Data Set sample is part of test case
‘scriptedDataSet.tst’, which itself is part of the examples project in DevTest 8.0.2
This is an example data set which is able to save state across executions within the same test. This is a
common use case for custom data sets that read proprietary file formats, for example. All this sample
really does is to count from 1 to 10 and pass the current value by the Shared Model Map to the test
case. This approach can be used to save the current file position or cursor data or the last primary key
value used. The 'state' of the dataset is saved across calls using SharedModelMap or
PersistentModelMap. Both of them save and retrieve String values only so we need to do some data
conversion.
This Javascript sample is quite straight forward.
Initially it checks if a Shared Model Map
‘myNameSpace’ exists and contains a value for
property ‘myValue’. If it does not variable
‘currentValue is initialized to 0.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 55 of 57
product performance may vary.
DevTest 8.0 – Custom Extensions

The next two steps increment and then save the


current value in the Shared Model Map.

Now the Shared Model Map is prepared for


passing to the test step. If the limit is reached
the current Shared Model Map is cleared.
Otherwise the new value is stored in the map.

In Javascript there is no explicit return value,


but the last evaluated expression is returned.

Appendix
The Appendix section contains information that does not fit yet into other chapters or sections of this
document.

Performance considerations
 Some scripts can be compiled, others need interpretation
 inline {{=%javascript% doSomething()}} style scripts are NEVER compiled
 setup cost (variable injection)
 Some actual performance numbers
o On a 2014 Mac Book Pro 2.3Ghz i7,
o ‘Do nothing’ LISA step - 225k steps/second
o Trivial groovy scripting step - 90k steps/sec
o Trivial JavaScript step - 62k steps/sec
o Legacy BeanShell scripting step - 38k steps/sec

Sample Code
SampleCode.zip contains files with sample code used in the document:
File name Comment
Logger-Sample-1 Sample _logger statements representing different log levels
Logger-Sample-2 Sample _logger statements for different object types
Logger-Sample-3 Sample _logger statement to log complex objects
testExec-raiseEvent-Sample-1 Sample testExec.raiseEvent() statement for custom events
EmbdExpr-Sample-1 Samples for embedded expressions in different scripting languages
used in test step ‘Output Log Message’. This sample is taken from
test case ‘scripting-1.tst’, which is part of the examples project in
DevTest 8.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any warranties and
Page 56 of 57 is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual product performance may
vary.
DevTest 8.0 – Custom Extensions

TestStep-Sample-1 Sample BeanShell script used in test step ‘Execute Script (JSR-223)’.
This script returns a ‘work day’ (<> Sat, Sun) with an offset of days
to a given start date.
VSE-Router-Sample-1 Sample script returns a VSE execution mode based on a property if
virtual service is running in DYNAMIC mode
MS-Sample-1 Default Match Script sample, which is available out of the box upon
right mouse click. It demonstrates the usage of injected variables
‘incomingRequest’ and ‘sourceRequest’, and of invocation of the
default matching logic.
MS-Sample-2 Match Script sample that demonstrates specific VSE logging
capability in addition to usage of the injected variables and default
matching logic
DPH-Sample-1-req This Scriptable DPH sample showcases the usage of
ShardeModelMap in the request part of a DPH, injected variable
‘lisa_vse_request’ and usage of classes ‘ParameterList’ and
‘Parameter’
DPH-Sample-1-recrsp This Scriptable DPH sample showcases the usage of
SharedModelMap in the response part of a DPH, injected variable
‘lisa_vse_response’ and usage of class ‘ParameterList’.
DPH-Sample-2-req This DPH sample demonstrates how to add a single parameter to
an operation using ‘addParameter()’ correctly.
DPH-Default-req This is the demo DPH that is inserted out of the box if a Scriptable
DPH was selected for the transaction request. It gives an overview
on available methods for injected variable ‘lisa_vse_request’ and
classes ‘ParameterList’ and ‘Parameter’.
DPH-Default-recrsp This is the demo DPH that is inserted out of the box if a Scriptable
DPH was selected for one of the transaction responses. It gives an
overview on available methods for injected variable
‘lisa_vse_response’ and classes ‘ParameterList’ and ‘Parameter’.

Copyright © 2015 CA, Inc. All rights reserved. All marks used herein may belong to their respective companies. This document does not contain any
warranties and is provided for informational purposes only. Any functionality descriptions may be unique to the customers depicted herein and actual
Page 57 of 57
product performance may vary.

You might also like