DevWeb JavaScript SDK

This section describes the various objects, methods, and properties that are part of the JavaScript SDK for DevWeb scripts.

For information on the concepts and structure used for the scripts, see Script structure.

Note: If you are manually writing a script, make sure it uses UTF-8 encoding without a BOM.

Flow control

This function group provides functions that are responsible for the flow control of the Vuser life cycle.

load.initialize(callback)

Registers the given callback to be run in the initialize phase of the test. The initializes are run in the same order as they are registered by calls to load.initialize().The callback may return a promise that is used to determine if the callback has succeeded or failed.

Example:

load.initialize(async function (){
//This code will run during Vuser initialization
});

load.initialize(name, callback)

Registers the given callback as a named initialize of the script with the given name. The initializes are run in the same order as they are registered by calls to load.initialize() or as defined in the run logic. The callback may return a promise that is used to determine if the callback has succeeded or failed.

load.initialize("myFirstInitialize", async function (){
   //This code will run during Vuser initialization 
});
load.initialize("mySecondInitialize", async function (){
   //This code will run during Vuser initialization 
});

load.finalize(callback)

Registers the given callback to be run in the finalize phase of the test. The finalizes are run in the same order as they are registered by calls to load.finalize() or as defined in the run logic.The callback may return a promise that is used to determine if the callback has succeeded or failed.

Example:

load.finalize(async function (){
//This code will run during Vuser finalization
});

load.finalize(name, callback)

Registers the given callback as a named finalize of the script with the given name. The finalizes are run in the same order as they are registered by calls to load.finalize() or as defined in the run logic. The callback may return a promise that is used to determine if the callback has succeeded or failed.

load.finalize("myFirstFinalize", async function(){
   //This code will run during Vuser finalization 
});
load.finalize("mySecondFinalize", async function(){
   //This code will run during Vuser finalization 
});

load.action(callback)

Registers the given callback to be run in the action phase of the test. The actions are run in the same order as they are registered by calls to load.action(). The callback may return a promise that is used to determine if the callback has succeeded or failed.

load.action(async function(){
  //This will run first during the run phase    
});

load.action(name, callback)

Registers the given callback as a named action of the script with the given name. The actions are run in the same order as they are registered by calls to load.action() or as defined in the run logic. The callback may return a promise that is used to determine if the callback has succeeded or failed.

Example:

load.action("myFirstAction", async function(){
  //This will run first during the run phase    
});
load.action("mySecondAction",async function(){
  //This will run second during the run phase
});									

Back to top

WebRequest

This object enables you to send web requests to the AUT. When creating a WebRequest, you can pass an options object with all the configuration you need for the request. Then you can send the request asynchronously or synchronously.

Example:

const jsonPage = new load.WebRequest({
url: "http://myserver/cgi-bin/json/generate_json_simple.asp",   
method: "GET"
returnBody: true
});
const jsonResponse = jsonPage.sendSync();

(static) load.WebRequest.defaults : Object

Returns an object that contains all the default options that are used as options for any subsequent calls to the WebRequest constructor.

Example:

load.WebRequest.defaults.method = "POST";
const webRequest = new load.WebRequest("www.foo.bar");  
//webRequest.method === "POST"	

constructor(options) : WebRequest

Creates a new WebRequest instance. You can provide the options argument to override any default options. The options must include at least a url property which is mandatory, while all the other properties are optional. Alternatively, you can call the constructor with a string argument and then this argument will be the URL.

Currently supported options are:

url (mandatory) string The URL to which the request is sent.
method string

The HTTP method used for the request.

Default: "GET"

headers object

A key value store that maps the header name to its value.

Default: {}

id integer The ID used to generate the corresponding snapshot file.
returnBody boolean

When true, the body property of the WebResponse is populated. Otherwise the body property of the WebResponse is set to null.

Default: false

queryString object

A key value store that maps the query string options. You can specify more than one value per key using the array notation.

For example { foo: "bar", baz: ["qux", "quux"], corge: "" } results in the following query string:

"foo=bar&baz=qux&baz=quux&corge="

Default: {}

body

JSON object/
string/Buffer/
MultipartBody

The body of the request, if the method supports a body (for example, POST or PUT).

If a JSON object is provided, it is converted to a data string automatically upon send.

If the body is a Node.js Buffer, then the body is sent as binary data.

Content-type examples:

  • www-form-urlencoded. If body equals {"foo":"bar","bat":10} it is converted to:
    foo=bar&bat=10
  • text\plain form. If body equals {"foo":"bar","bat":10} and formDelimiter is a newline character (\r\n), it is converted to:
    foo=bar
    bat=10

  • application/json. If body equals {"foo":"bar","bat":10} it is converted to:
    '{"foo":"bar","bat":10}'

bodyPath string

The path to a file whose content is used as the body of the request. This can be a path relative to the script folder or an absolute path.

This property is only used if the body property is not set.

isBinaryResponse boolean

When set to true the response body is returned as a binary Node.js Buffer.

Default: false

formDelimiter string

The delimiter that is used for form body fields separation.

Default: "&"

forceAuthentication boolean
  • true. Forces an authentication header to be added to the request using the credentials provided by the load.setUserCredentials API.
  • false (default). Waits for an HTTP 401 (unauthorized) before sending the credentials.

awsSigning

object

When defined, WebRequest is automatically signed with AWS Signature Version 4 using the credentials provided by the load.setUserCredentials API (see setUserCredentials(AWSAuthentication).

For example:

{ region: "us-west-1", service: "sqs" }

Example that includes adding signature to url:

{ region: "us-west-1", service: "sqs", sign: "url" }

Available properties are:

  • region (string, mandatory): AWS service region.

  • service (string, mandatory): AWS service name.

  • sign (string, optional): Determines how to authenticate requests, by using Authorization header or Query parameters. Can be either:

    a) header (default). The Authorization header is added automatically before the request call.

    b) url. Authentication information is added to query string parameters.

  • disableURIPathEscaping (boolean, optional): If true, disables automatic escaping of the URI path of the request for the signing. S3 is an example of a service that does not need additional escaping.

  • unsignedPayload (boolean, optional): If true, request payload is not signed.

disableRedirection boolean

When true, WebRequest redirects are not processed automatically.

Default: false

resources array

A list of resources that is downloaded as part of the request. An element in the array can be a string, in which case it is used as the URL of the resources, and the rest of the parameters (for example, headers) are the same as in the WebRequest.

Default: []

handleHTTPError string/function Determines how HTTP errors are handled. (see sendsync())

extractors

array/object An extractor object or array of extractor objects to apply on the response of this WebRequest. See Extractors.
transactionName string

Associates a WebRequest with a transaction. When the Dynatrace flag is enabled in the Runtime Settings, the default behavior is to associate each WebRequest with the transaction that has the latest start time (if a transaction exists).

This transaction name is used to display the request in Dynatrace dashlets. To change this behavior, manually define a value for transactionName, or deactivate for a single request by entering an empty string: ""

Default: nil

charset string

Destination character set of encoded form values. For example: iso-8859-1, windows-1252

For the supported character sets, see the Internet Assigned Numbers Authority (IANA) site.

Default: utf-8

downloadHtmlStaticResources boolean

When true, the HTML parser will search the HTML response body for resources and download them during replay.

Default: false

saveResponseBodyToFile string

The path to a file where the response body will be saved. This should be a relative path (the path starts from the script folder).

Example:

const webRequest = new load.WebRequest({
	url:"www.url.com"
	method: "POST",
	id: 1
});
//If you don't need to change the method (default is "GET") then you can do the following:
const webRequest = new load.WebRequest("www.url.com");

MultipartBody

You can send a multipart web request by assigning the code object as the body of a WebRequest.

constructor(entries, boundary) : MultipartBody

Creates a multipart body object with the given entries. The optional boundary argument are used to separate the entries within the sent body. The entries array should contain at least one of the following entry objects:

  • MultipartBody.StringEntry

    Represents an entry of a single string.

    constructor(name, value): StringEntry. Creates a string entry object based on the given name and _value.

  • MultipartBody.FileEntry

    Represents a file entry within a multipart request.

    constructor(name, filePath, contentType, fileName): FileEntry. Creates a file entry object based on the given name and filePath. You can specify the content type using the contentType argument. If content type was not specified, text/plain is used. You can specify the file name of the sent file using the fileName argument. If the file name is not specified it is extracted from the filePath argument.

Example:

new load.WebRequest({
        url: "http://someHostName", 
        method: "POST",
        headers: {
            "Accept-Encoding": "gzip, deflate, sdch",
        },
        body: new load.MultipartBody([
                new load.MultipartBody.StringEntry("entry", "some text"),
                new load.MultipartBody.FileEntry("name_of_files",
                    "test.json",
                    "text/plain",  // Content-Type property, optional, default is 'text/plain'
                    "newFile.json" // filename property, optional, default is the file name
                )
            ],
            "---myBoundary---")// Boundary property, optional, randomly generated if not supplied
    }).sendSync();
 

Alternatively, you can use an array containing the part type (string or file), and the rest of the relevant constructor arguments. For example, the definitions are equivalent in each of these two code examples:

new load.MultipartBody([
                new load.MultipartBody.StringEntry("myName", "myText")
                ]);
new load.MultipartBody([
                ["string","myName", "myText"]
                ]);

Methods

sendSync() : WebResponse

The synchronous version of send. When called, the script execution is blocked until a response is returned.

Returns the resulting WebResponse object, or throws an exception if an error occurs and the error is not handled by the user by means of an error handler.

HTTP errors are handled by setting the handleHTTPError property of the WebRequest.

The possible values are:

Function with the signature

func(webResponse) : boolean

Calls the function with the WebResponse object received from the request. You can change the received response and it will be returned from the call to sendSync.

The function return value affects how the current iteration continues execution. If the function returns false, the iteration continues running as usual. In any other case, the iteration ends immediately.

A string

A log message is printed with the given string and the iteration continues as usual.

null The error is not handled, and the current iteration ends. (Default value)

Examples:

  • No error handling:

    const request = new load.WebRequest({
            url: "http://myhostname.com/webgui", 
            method: "GET",
            headers: {
    		"Referer": "",
    		"Upgrade-Insecure-Requests": "1"
            	}
    });
    const response = request.sendSync();7,
  • Handle Http error:

    const request4 = new load.WebRequest({
            url: "http://myhostname.com/cgi-bin/print_request.asp", 
            method: "POST",
            headers: {
    		"Referer": "http://myhostname.com/JSON/test_json.html",
    		"Origin": "http://myhostname.com",
    		"Upgrade-Insecure-Requests": "1",
    		"Content-Type": "application/x-www-form-urlencoded"
    		},
    		body: {
     			"email" : "devweb_forum@anyco.com",
    			"media : "2012-11-17T04:51:06-08:00",
    			"author_id : "32856507@N32856507"
    		},
    	 	handleHTTPError: (webResponse) =>{
    			if (webResponse.status === 404){
    				return false; //We can continue, its fine.
    			}
    		}				
    });
    const response4 = request4.sendSync();

send() : Promise

Sends the request to the defined URL (see constructor) and returns a promise which is resolved with a WebResponse object or rejected with an unhandled error.

Example:

const webRequest = new load.WebRequest("www.url.com");
webRequest.send().then(function(response) {
			//Do something with the response
}).catch(function(error) {
			//Handle the error or throw it 
});

You can use the JavaScript Promise constructs to control the asynchronous nature of the requests.

For example, the following code sends 3 simultaneous requests:

Promise.all([
	(new load.WebRequest("www.first.com")).send(),
	(new load.WebRequest("www.second.com")).send(),
	(new load.WebRequest("www.third.com")).send()
]).then((results)=>{
	//This will be called when all 3 requests return
	//Do something with all 3 results
});			

Back to top

WebResponse

This object is returned as a WebRequest result. You do not need to create it on your own.

Properties

Supported properties list:

status number The status code of the response.
headers object A key value store of the headers in the response sent by the server.
size number The size (in bytes) of the response.
startTime number

The UNIX timestamp in milliseconds, providing the engine time at the start of the request roundtrip.

duration number

The request roundtrip time in milliseconds. This is the time taken for the main request roundtrip only, without resources.

body string or Buffer

The body of the response. Note that body is available only if the property returnBody was set to true in the request.

If the isBinaryResponse property was set to true, then the returned value is a Node.js Buffer object.

jsonBody object The body of the response as an object (only applicable when the body is a valid json). Note that jsonBody is available only if the request had the property returnBody set to true.
request WebRequest The WebRequest object that caused this response to be generated.
resources array, object

A list of all the resources that were downloaded as part of the request. Each resource object contains the following fields:

  • url (string). The URL of the resource.
  • status (number). The status code that was returned when the resource was downloaded.
  • size (number). The size (in bytes) of the downloaded resource.
redirectUrls array A list of all the URLs passed through while redirecting to this response.
extractors object The results of the extractor applied on the response. For more information, see Extractor results.

Example:

const response1 = request1.sendSync(); //Create a WebResponse
load.log(response1.body); //Print the response body to the console
load.log("Request startTime: " + new Date(response.startTime).toISOString(), load.LogLevel.info); // print request start time               

Methods

textCheck(expression) : boolean

Checks if the given expression matches a substring within the body.

expression can be either a string or a regular expression.

Returns true if the expression was found in the response body and false otherwise.

Note: textCheck works only if the request had the property returnBody set to true.

Example:

const response = request.sendSync();
if (response.textCheck("Web Tours")){
    	load.log("Success!");\
} else {
	load.log("Failure!");
}

Back to top

WebSocket

An object that enables you to create a WebSocket connection to the AUT. When creating a WebSocket, you need to pass an options object with all the required configuration. You can then send and receive messages over the socket.

Example:

let messageHandler = function (message) {
      load.log(`Got message on ${socket.id}`, load.LogLevel.info);
    }

    const socket = new load.WebSocket({
        url: "ws://myserver:8080",
        onMessage: messageHandler
    });

    socket.open();
    socket.send("Ping", false);
    socket.send({dataPath: "c:\\myImg.png", isBinary: true});
    socket.close();

constructor(options) : WebSocket

Creates a new WebSocket instance. The mandatory options argument must include at least the url and the onMessage properties, all the other properties are optional.

The created WebSocket instance has an automatically generated and unique id (string) property indicating the connection number.

Note: The created WebSocket instance is not connected to the host. To initiate the connection, the open method must be called.

The supported options are:

url

(mandatory)

string

The WebSocket endpoint in ws:// or wss:// (secure WebSocket schema) format.

headers object

A key value store that maps the header name to its value.

Default: {}

onMessage

(mandatory)

function

A callback function for the onMessage event. The assigned function has the signature of func(message), where message contains the following fields:

id (string) A unique number indicating the connection number.
data (string or Buffer) The received message. If the message is binary, it will be a Buffer object.
size (number) The size (in bytes) of the received message.
isBinaryData (boolean) Indicates whether the received message is binary.
onError function

A callback function for the onError event. The assigned function has the signature of func(error) where error is the error message string.

onOpen function

A callback function for the onOpen event. The assigned function has the signature of func(message) where message contains the following fields:

id (string) The unique connection number.
status (number) The status code of the response.
headers (object) A key value store of the headers in the response sent by the server.

onClose

function

A callback function for the onClose event. The assigned function has the signature of func(message) where message contains the following fields:

id (string) The unique connection number.
code (number) The connection close status code.
reason (string) The connection close reason.
isClosedByClient (boolean) Indicates whether the connection was closed by the client.

Example:

 let messageHandler = function (message) {
      load.log(`Received message ${message.data}, socket id ${socket.id}`, load.LogLevel.info);
    }

    let errorHandler = function (err) {
        load.log('Socket error: ' + JSON.stringify(err), load.LogLevel.error);
    }

    let openHandler = function (response) {
      load.log(`Socket id: ${response.id} opened. Status: ${response.status}`, load.LogLevel.info);
    }

    let closeHandler = function (code) {
      load.log(`Socket id ${socket.id} closed, message: ${code}`, load.LogLevel.info);
    }

    const socket = new load.WebSocket({
        url: "ws://myserver:8080",
        onMessage: messageHandler,
        onError: errorHandler,
        onOpen: openHandler,
        onClose: closeHandler
    });

Methods

open()

Opens the WebSocket connection to the remote host. After calling this function, it is possible to send and receive messages.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message)=>{ load.log(message.data); },
});

socket.open();

send(data)

Sends the data to the connected server. To send a binary message, pass a Node.js Buffer object as data.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message)=>{ load.log(message.data); },
});
socket.open();

socket.send("ping");

send(options)

The supported options are:

data string or Buffer

The message.

In order to send a binary message, data must be a Node.js Buffer object.

dataPath string Path to a file that contains the data to send.
isBinary (optional) boolean

If isBinary is set to true, or a binary Buffer is passed as data, the data is sent in a binary socket.

Either data or dataPath value must be specified when isBinary is set to true.

Default: false

Sends the message specified in data, or the content of the file specified in dataPath, to the connected server. data argument and dataPath property are mutually exclusive, but one of them must be specified.

If both data argument and dataPath property are specified, only data argument is considered.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message)=>{ load.log(message.dataPath); },
});
socket.open();

socket.send({dataPath: "c:\\myImg.png", isBinary:true});

close(code, reason)

Closes the connection to the server. If the optional code and reason arguments are provided, then the connection is closed with given code and reason.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message)=>{load.log(message);},
});
socket.open();

socket.send("ping", false);
socket.close();

waitForData(timeout) : Promise

Returns a promise that is resolved only when continue is called on the WebSocket or when the timeout has expired.

The timeout is given in milliseconds:

  • Default: 120000 milliseconds
  • Unlimited: Use -1

This function can be used to asynchronously wait until some other event happens in the system. If the timeout expires before continue has been called, the returned promise is rejected.

Note: Only one call to waitForData can be activated at a time, for each WebSocket.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message) => {
        if (message.data === 'myMessage'){
          socket.continue();
        }
    },
});
socket.open();
socket.send("ping", false);
await socket.waitForData(6000);
socket.close();

continue()

Resolves a promise previously created by waitForData.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message) => {
        if (message.data === 'myMessage'){
          socket.continue();
        }
    },
});
socket.open();
socket.send("ping", false);
socket.waitForData(60000);
socket.close();

waitForClose(timeout) : Promise

Blocks the Vuser script until the connection to the server is closed.

The timeout is given in milliseconds:

  • Default: 120000 milliseconds
  • Unlimited: Use -1

Closure can occur due to the following:

  • The server has closed the connection.
  • close was called on the WebSocket.
  • The optional timeout argument has passed and has expired.

Example:

const socket = new load.WebSocket({
    url: "ws://ws.myhostname.com:8080",
    onMessage: (message) => {
        if (message.data === 'end'){
          socket.close();
        }
    },
});
socket.open();
socket.send("ping", false);
socket.waitForClose(3000);

Back to top

gRPC

The gRCP APIs provide support for the native gRPC communication protocol when replaying DevWeb scripts. (gRPC-Web is not supported.)

Tip: The <DevWeb root folder>\examples\ folder includes a usage example script for gRPC.

GrpcClient

An object that creates a new client that can be used to make RPCs to a gRPC server.

Example:

const client = new load.GrpcClient({
        host: "myHost",
        isInsecure: true,
    });

constructor(options) : GrpcClient

Creates a new GrpcClient instance. The options must include at least a host property; all other properties are optional.

Alternatively, you can call the constructor with a string argument, and then this argument will be the host.

Note: If host does not contain a port number, a default port is added automatically.

Currently supported options are:

host (mandatory) string The host of the gRPC server.
isInsecure (optional) boolean

When true, an unencrypted, plain connection is established with the gRPC server.

Default: false

Default port: For false, port 443; for true, port 80

socket (optional) string

The communication socket that is used for RPC connection. Possible values are tcp or unix.

Default: tcp

ignoreBadCertificate (optional) boolean

When false, the client verifies the server's certificate chain and host name during SSL connection.

Default: true

certificateLocation (optional) string The file path to the client-side certificate file. The file must contain PEM encoded data.
certificateKeyLocation (optional) string The file path to client-side certificate key file. The file must contain PEM encoded data.
defaults (optional) object The object containing all default options that are used as options for any client methods.

Example:

 const client = new load.GrpcClient({
        host: "myHost",
        isInsecure: true,
        defaults: {
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363"
            }
        }
    });

    const client = new load.GrpcClient('myHost');

Methods

unaryRequest(options) : GrpcUnaryRequest

Creates a new gRPC unary service method object instance. You can provide the options argument, which override any client default options.

Currently supported options are:

method (mandatory) string A fully-qualified method name in 'package.Service/method' or 'package.Service.Method' format.
protoFile (mandatory) string The path to the protocol buffer .proto file.
id (optional) integer The ID for the gRPC request.
headers (optional) object

A key value store that maps the header name to its value, gRPC metadata.

Default: {}

returnBody (optional) boolean When true, the body property of the GrpcResponse is populated. Otherwise the body property of the GrpcResponse is set to null.
body (optional) string or object

The body of the method call.

Default: ""

bodyPath (optional) string The path to a file whose content is used as the body of the request. This can be a path relative to the script directory, or an absolute path. This property is used only if the body property is not set.
extractors (optional) array, object

An extractor object, or an array that holds extractor objects, to apply on the response of this GrpcRequest.

For more information, see Extractors.

Example:

const client = new load.GrpcClient('myHost');
const helloMethod = client.unaryRequest({
        id: 1,
        method: "package.Service.Hello",
        protoFile: "./proto/hello.proto"
    });
const response = helloMethod.sendSync();

clientStreamRequest(options) : GrpcClientStreamRequest

Creates a new instance of a gRPC client stream-service method object. You can provide the options argument, which override any client default options.

Currently supported options are:

method (mandatory) string A fully-qualified method name in 'package.Service/method' or 'package. Service.Method' format.
protoFile (mandatory) string The path to the protocol buffer .proto file.
id (optional) integer The ID for the gRPC request.
headers (optional) object

A key value store that maps the header name to its value, gRPC metadata.

Default: {}

returnBody (optional) boolean When true, the body property of the GrpcResponse is populated. Otherwise the body property of the GrpcResponse is set to null.
bodyArray (optional) array, object The body of the method call.
bodyPath (optional) string The path to a file whose content is used as the body of the request. This can be a path relative to the script directory, or an absolute path. This property is used only if the body property is not set.
extractors (optional) array, object

An extractor object, or an array of extractor objects, to apply on the response of this GrpcRequest.

For more information, see Extractors.

Example:

const client = new load.GrpcClient('myHost');
const recordRoute = client.clientStreamRequest({
        id: 3,
        method: "routeguide.RouteGuide.RecordRoute",
        protoFile: "./proto/route_guide.proto",
        bodyArray: [{
            "latitude": 407838351,
            "longitude": -746143763
        },
        {
            "latitude": 415736605,
            "longitude": -742847522
        }]
    });
const response = recordRoute.sendSync();

serverStreamRequest(options) : GrpcServerStreamRequest

Creates a new instance of a gRPC server stream-service method object. You can provide the options argument, which override any client default options.

Currently supported options are:

method (mandatory) string A fully-qualified method name in 'package.Service/method' or 'package. Service.Method' format.
protoFile (mandatory) string The path to the protocol buffer .proto file.
id (optional) integer The ID for the gRPC request.
headers (optional) object

A key value store that maps the header name to its value, gRPC metadata.

Default: {}

returnBody (optional) boolean When true, the body property of the GrpcResponse is populated. Otherwise the body property of the GrpcResponse is set to null.
body (optional) string, object

The body of the method call.

Default: ""

bodyPath (optional) string The path to a file whose content is used as the body of the request. This can be a path relative to the script directory, or an absolute path. This property is used only if the body property is not set.
extractors (optional) array, object

An extractor object, or an array of extractor objects, to apply on the response of this GrpcRequest.

For more information, see Extractors.

Example:

const client = new load.GrpcClient('myHost');
const lotsOfReplies = client.serverStreamRequest({
      id: 1,
      method: "hello.HelloService.LotsOfReplies",
      protoFile: "./proto/hello.proto",
      body: {
        "greeting": `DevWeb hello`
      },
      extractors: [
        new load.JsonPathExtractor("myReply", "$[0].reply")
      ],  
    });
const response = lotsOfReplies.sendSync();

biDirectionalStreamRequest(options) : GrpcBiDirectionalStreamRequest

Creates a new instance of a gRPC bidirectional stream service method object. You can provide the options argument, which will override any client default options.

Currently supported options are:

method (mandatory) string A fully-qualified method name in 'package.Service/method' or 'package. Service.Method' format.
protoFile (mandatory) string The path to the protocol buffer .proto file.
id (optional) integer The ID for the gRPC request.
headers (optional) object

A key value store that maps the header name to its value, gRPC metadata.

Default: {}

returnBody (optional) boolean When true, the body property of the GrpcResponse is populated. Otherwise the body property of the GrpcResponse is set to null.
bodyArray (optional) array, object The body of the method call.
bodyPath (optional) string The path to a file whose content is used as the body of the request. This can be a path relative to the script directory, or an absolute path. This property is used only if the body property is not set.
extractors (optional) array, object

An extractor object, or an array of extractor objects, to apply on the response of this GrpcRequest.

For more information, see Extractors.

Example:

Copy code
const client = new load.GrpcClient('myHost');
const recordRoute = client.biDirectionalStreamRequest({
        id: 3,
        method: "routeguide.RouteGuide.RecordRoute",
        protoFile: "./proto/route_guide.proto",
        bodyArray: [{
            "latitude": 407838351,
            "longitude": -746143763
        },
        {
            "latitude": 415736605,
            "longitude": -742847522
        }]
    });
const response = recordRoute.sendSync();

connect(connectionTimeout) : Promise

Note: The connect function is supported from version 25.3.

Connect to the server. The connectionTimeout is given in milliseconds.

Optional function: Connect is performed automatically on first request to gRPC server, when connection was not established in advance.

Example:

Copy code
const client = new load.GrpcClient('myHost');
const connectingToGRPC = await client.connect();

GrpcUnaryRequest

Creates unary RPC request object.

Methods

sendSync() : GrpcResponse

Performs unary RPC to a gRPC server. When called, the script execution is blocked until a response or error is returned. Returns the resulting GrpcResponse object, or throws an exception.

Example:

const client = new load.GrpcClient('myHost');
const helloMethod = client.unaryRequest({
        id: 1,
        method: "package.Service.Hello",
        protoFile: "./proto/hello.proto"
    });

const response = helloMethod.sendSync();

send() : Promise

Performs async unary RPC to a gRPC server, and returns a promise which is resolved with a GrpcResponse object, or rejected with an unhandled error.

Example:

const client = new load.GrpcClient('myHost');
const helloMethod = client.unaryRequest({
    id: 1,
    method: "package.Service.Hello",
    protoFile: "./proto/hello.proto"
});

helloMethod.send().then(function(response) {
    //Do something with the response  
}).catch(function(error) {
    //Handle the error or throw it
});

GrpcClientStreamRequest

Creates a client-streaming RPC request object.

Methods

sendSync() : GrpcResponse

Performs gRPC client-streaming RPC to a gRPC server. When called, the script execution is blocked until a response or error is returned. Returns the resulting GrpcResponse object or throws an exception.

Example:

const client = new load.GrpcClient('myHost');
const route = client.clientStreamRequest({
        id: 1,
        method: "routeguide.RouteGuide.RecordRoute",
        protoFile: "./proto/route_guide.proto",
        bodyArray: [{
            "latitude": 407838351,
            "longitude": -746143763
        },
        {
            "latitude": 415736605,
            "longitude": -742847522
        }],
    });

const response = route.sendSync();

send() : Promise

Performs async gRPC client streaming to a gRPC server, and returns a promise which is resolved with a GrpcResponse object, or rejected with an unhandled error.

Example:

const client = new load.GrpcClient('myHost');
const route = client.clientStreamRequest({
        id: 1,
        method: "routeguide.RouteGuide.RecordRoute",
        protoFile: "./proto/route_guide.proto",
        bodyArray: [{
            "latitude": 407838351,
            "longitude": -746143763
        },
        {
            "latitude": 415736605,
            "longitude": -742847522
        }],
    });

route.send().then(function(response) {
    //Do something with the response  
}).catch(function(error) {
    //Handle the error or throw it
});

GrpcServerStreamRequest

Creates a server-streaming RPC request object.

Methods

sendSync() : GrpcResponse

Performs gRPC server-streaming RPC to a gRPC server. When called, the script execution is blocked until a response or error is returned. Returns the resulting GrpcResponse object or throws an exception.

Example:

const client = new load.GrpcClient('myHost');
const features = client.serverStreamRequest({
        id: 1,
        method: "routeguide.RouteGuide.ListFeatures",
        protoFile: "./proto/route_guide.proto",
        body: {
            "lo": { "latitude":"407838351", "longitude":"-746143763" },
            "hi": { "latitude":"413700272", "longitude":"-742135189" }
        }
    });

const response = features.sendSync();

send() : Promise

Performs async gRPC server streaming to a gRPC server, and returns a promise which is resolved with a GrpcResponse object, or rejected with an unhandled error.

Example:

const client = new load.GrpcClient('myHost');
const features = client.serverStreamRequest({
        id: 1,
        method: "routeguide.RouteGuide.ListFeatures",
        protoFile: "./proto/route_guide.proto",
        body: {
            "lo": { "latitude":"407838351", "longitude":"-746143763" },
            "hi": { "latitude":"413700272", "longitude":"-742135189" }
        }
    });

features.send().then(function(response) {
    //Do something with the response  
}).catch(function(error) {
    //Handle the error or throw it
});

GrpcBiDirectionalStreamRequest

Creates bidirectional streaming RPC request object.

Methods

sendSync() : GrpcResponse

Performs gRPC bidirectional streaming RPC with a gRPC server. When called, the script execution is blocked until a response or error is returned. Returns the resulting GrpcResponse object, or throws an exception.

Example:

Copy code
const client = new load.GrpcClient('myHost');
const features = client.biDirectionalStreamRequest({
id: 1,
method: "routeguide.RouteGuide.ListFeatures",
protoFile: "./proto/route_guide.proto",
body: {
"lo": { "latitude":"407838351", "longitude":"-746143763" },
"hi": { "latitude":"413700272", "longitude":"-742135189" }
}
});
const response = features.sendSync();

send() : Promise

Performs async gRPC bidirectional streaming with a gRPC server, and returns a promise which is resolved with a GrpcResponse object, or rejected with an unhandled error.

Example:

Copy code
const client = new load.GrpcClient('myHost');
const features = client.biDirectionalStreamRequest({
id: 1,
method: "routeguide.RouteGuide.ListFeatures",
protoFile: "./proto/route_guide.proto",
body: {
"lo": { "latitude":"407838351", "longitude":"-746143763" },
"hi": { "latitude":"413700272", "longitude":"-742135189" }
}
});
features.send().then(function(response) {
//Do something with the response
}).catch(function(error) {
//Handle the error or throw it
});

GrpcResponse

This object is returned as a GrpcRequest result. You do not need to create it.

Properties:

status string The status code of the response.
headers object A key value store of the gRPC metadata sent by the server.
size number The size (in bytes) of the response.
startTime number The UNIX timestamp in milliseconds for when the RPC began.
duration number The invoked round-trip time in milliseconds.
body string

The body of the response.

Note: The body is available only if the request has the property returnBody set to true.

jsonBody object

The body of the response as an object (only applicable when the body is a valid json).

Note: jsonBody is available only if the request has the property returnBody set to true.

extractors object

The results of the extractor applied on the response.

For more information, see Extractor results.

const client = new load.GrpcClient('myHost');
const helloMethod = client.unaryRequest({
        id: 1,
        method: "package.Service.Hello",
        protoFile: "./proto/hello.proto"
    }).sendSync();
load.log(helloMethod.status); 
load.log("Invoke startTime: " + new Date(helloMethod.startTime).toISOString(), load.LogLevel.info); // print invoke start time

Back to top

Extractors

You can specify which values are extracted from the response of a specific WebRequest, the response of a specific gRPC request, or the File read method, by providing the extractors option parameter.

This parameter is an extractor object, or an array of extractor objects, that are created using the helper constructor functions described in Extractor types, below.

Extractor types

BoundaryExtractor(name, leftBoundary, rightBoundary) : ExtractorObject

This constructor creates an extractor object for the boundary extractor. It searches the headers and the body of the response for any string that begins with leftBoundary and terminates with rightBoundary, and returns the first matching string between the two boundaries. If nothing is found, null is returned.

For additional options, use the next constructor version, below.

BoundaryExtractor(name, options) : ExtractorObject

Creates the same ExtractorObject as in the previous call (above), but allows some additional options.

Note: When occurrence is set as All, and there are a high number of returned values, using the converters and/or transform operations may affect performance.

Additional options include:

leftBoundary (mandatory) string The left boundary of the search.
rightBoundary (mandatory) string The right boundary of the search.
occurrence (optional) string/number

The occurrence of the result to return. (This was previously ordinal.) Can be one of:

  • load.ExtractorOccurrenceType.All. All the found occurrences are returned as an array.
  • load.ExtractorOccurrenceType.First. The first occurrence is returned.
  • load.ExtractorOccurrenceType.Last. The last occurrence is returned.
  • A number defining the position of the value to replace, where 0 defines the first occurrence. So, for example, 2 replaces the third occurrence.

If occurrence is not defined, the first occurrence is returned.

caseInsensitive (optional) boolean If set to false,then the search uses case-sensitive comparison. If caseInsensitive is not defined, then the search uses case-insensitive comparison.
includeRedirections (optional) boolean If set to false, then the search is not performed on the headers and body of all pages returned by redirection of the WebRequest.
scope (optional) string

The scope of the search.

  • If scope is not defined, then only the response body is searched.
  • If scope is set to load.ExtractorScope.All, then both the response headers and the response body are searched for text.
  • If scope is set to load.ExtractorScope.Body, then only the response body is searched for text.
  • If scope is set to load.ExtractorScope.Headers, then only the response headers are searched for text.
converters (optional) string

The converters are applied to the extracted value and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

If occurrence is set to All, the converters are applied to all returned values.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

If occurrence is set to All, the transform function is applied to all extracted values.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

const boundaryRule1 = new load.BoundaryExtractor("title", "<title>", "</title>");
const boundaryRule2 = new load.BoundaryExtractor("thirdImage", {
  leftBoundary: "<title>",
  rightBoundary: "</title>",
  occurrence: load.ExtractorOccurrenceType.Last
});
const boundaryRule3 = new load.BoundaryExtractor("someBase64", {
  leftBoundary: 'base64Encoded:"',
  rightBoundary: '",',
  converters: "base64Decode", //The extracted value will be automatically decoded from base64
  transform: (value, request, response) => { 
    if (response.status === 500) { //For response status code 500, we want the extracted value to be "error"
      return "error";
    }
    return value
  }
});
const myPageRequest = new load.WebRequest({
  url: "http://myServer.com/main/product.html",
  method: "GET",
  returnBody: false, //You don't need to return the body to get the extractors
  extractors: [
    boundaryRule1, //Extract the title of the page
    boundaryRule3  //Extract a value and then decode it from base64
  ]
});
const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`The title of the page is ${myResponse.extractors.title}`);

load.log(`The third image is ${myResponse.extractors.thirdImage}`);

RegexpExtractor(name, expression, flags) : ExtractorObject

This constructor creates an extractor object for the regular expression extractor. It searches the headers and the body of the response for a match of the given regular expression, and returns the first match of the first capture group. If nothing is found, null is returned.

For more information about regular expression syntax, see the GitHub Google re2 documentation.

For additional options, use the next constructor version, below.

RegexpExtractor(name, options) : ExtractorObject

Creates the same ExtractorObject as in the previous call (above), but allows some additional options.

Note: When occurrence is set as All, and there are a high number of returned values, using the converters and/or transform operations may affect performance.

Additional options include:

expression (mandatory) string The regular expression to use for the search.
flags (optional) string The regular expression flags.
groupNumber (optional) number

The group number to return as a result (zero-based).

If groupNumber is set to 0, both the full match, and each search group in the regular expression, are returned. The full match is returned as the full property of the result, and each group is represented in the groups array in the result.

If groupNumber is not defined, the first group (1) is returned.

occurrence (optional) string/number

The occurrence of the result to return. (This was previously ordinal.) Can be one of:

  • load.ExtractorOccurrenceType.All. All the found occurrences are returned as an array.
  • load.ExtractorOccurrenceType.First. The first occurrence is returned.
  • load.ExtractorOccurrenceType.Last. The last occurrence is returned.
  • A number defining the position of the value to replace, where 0 defines the first occurrence. So, for example, 2 replaces the third occurrence.

If occurrence is not defined, the first occurrence is returned.

includeRedirections (optional) boolean If set to false, then the search is not performed on the headers and body of all pages returned by redirection of the WebRequest.
scope (optional) string

The scope of the search.

  • If scope is not defined, then only the response body is searched.
  • If scope is set to load.ExtractorScope.All, then both the response headers and the response body are searched for text.
  • If scope is set to load.ExtractorScope.Body, then only the response body is searched for text.
  • If scope is set to load.ExtractorScope.Headers, then only the response headers are searched for text.
converters (optional) string

The converters are applied to the extracted value and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

If occurrence is set to All, the converters are applied to all returned values.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

If occurrence is set to All, the transform function is applied to all extracted values.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

 const regexpRule1 = new load.RegexpExtractor("title","<title>(.*?)</title>","i");
 const regexpRule2 = new load.RegexpExtractor("fullTitle",{
   expression: "<title>(.*?)</title>",
   flags: "i",
   groupNumber: 0
 });
 const regexpRule3 = new load.RegexpExtractor("someImage",{
   expression:"<img>(.*?)</img>",
   flags:"i",
   occurrence:2,
   includeRedirections:true
   });
 const regexpRule4 = new load.RegexpExtractor("someBase64",{
   expression:"<myBase64htmlEncoded>(.*?)</myBase64htmlEncoded>",
   converters:"base64Decode,htmlUnescape",
   transform: (value, request, response)=>{
      if (request.url === "server1"){
        return "fixed "+value;
      }
      return value
     }
   });
 const myPageRequest = new load.WebRequest({ 
      url: "http://myServer.com/main/product.html",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors:[
          regexpRule1,  //Extract only the title of the page (group 0)
          regexpRule2,  //Extract the entire expression and all the groups
          regexpRule3,  //Extract the first group of the third occurrence including redirections
          regexpRule4   //Extract the value then convert it from base64 and unescape the HTML, then if the url was "server1" add a prefix to the value 
        ]
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor.
load.log(`The title of the page is ${myResponse.extractors.title}`);

//Since we want only the title, we will take the extractor result of the first group
load.log(`The title of the page is ${myResponse.extractors.fullTitle.groups[0]}`);
//We can get the full match as well
load.log(`The full matched expression is ${myResponse.extractors.fullTitle.full}`); //This will log <title>Products</title> to the log
//We can retrieve a particular occurrence
load.log(`The third image of the page is ${myResponse.extractors.someImage}`);

JsonPathExtractor(name, path, returnMultipleValues) : ExtractorObject

This constructor creates an extractor object for the JSON path extractor. It searches the body of the response (if it is a valid JSON) and returns the matching objects:

  • If nothing is found, null is returned.
  • If returnMultipleValues is unspecified or is false, it returns only the first result; otherwise, it returns an array with all the results.

For more information on the JSON path extractor, refer to the next constructor version.

JsonPathExtractor(name, options) : ExtractorObject

This constructor creates an extractor object for the JSON path extractor. It searches the body of the response (if it is a valid JSON) and returns the matching objects(s). If nothing is found then null is returned.

Note: When returnMultipleValues is set to true, and there are a high number of returned values, using the converters and/or transform operations may affect performance.

options can include:

path (mandatory) string

The JSON path to use for the search.

returnMultipleValues (optional) boolean If unspecified or is false, returns only the first result; otherwise, returns an array with all results.
converters (optional) string

The converters are applied to the extracted value, and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

If returnMultipleValues is true, the converters are applied to all returned values.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

If returnMultipleValues is true, the transform function is applied to all extracted values.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Currently supported syntax for JSON path:

$.store.book[*].author The authors of all the books in the store.
$.store.* All the items in the store.
$.store.book[?(@.price<10)]

All the books in the store with price lower than 10.

Supported conditionals are:

>,<,==,!=,<=,>= For numeric values
==,!=,~=,=~, contains For string values
==,!= For boolean values
==,~=, contains For arrays
$.store.book[?(@.title=="Jack \"The Rabbit\" Smith")] The book with the title: Jack "The Rabbit" Smith.
$.store.book[0,1] or $.store.book[:2] The first two books. Note that the ":" notation is exclusive to the higher value (for example, 0:2 includes items 0 and 1, but not 2).
$.store.book[-1:] The last book.
$.store.book[?(@.title=~"Jack"] (Non-standard, contains operator.) Books with the word Jack in their title.
$.store.book[?(@.title~="Gone with the Wind"] (Non-standard inverse, contains operator.) Books with titles that are contained in Gone with the Wind.

$.['@odata.context']

$.['\u0040odata.context']

$.['odata.test']

$.['odata']

Elements that include dot sign and @ sign (. , @) in the key name.

Note: Array condition string values must be enclosed in double quotes (") and not other types of quotes (see the example above).

Example:

const productNameExtractor = new load.JsonPathExtractor("productName","$.products[0].name");
 const myPageRequest = new load.WebRequest({ 
      url: "http://myServer.com/main/products.json",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors: productNameExtractor //Extract the name of the first product
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`The name of the first product is ${myResponse.extractors.productName}`); 

XpathExtractor(name, path, returnMultipleValues) : ExtractorObject

This constructor creates an extractor object for the XPath extractor. It searches the body of the response (if it is a valid XML) and returns the matching objects(s). If nothing is found, then null is returned.

If returnMultipleValues is unspecified or is false, it returns only the first result; otherwise it returns an array with all the results.

For more information, refer to the next constructor version.

XpathExtractor(name, options) : ExtractorObject

This constructor creates an extractor object for the XPath extractor. It searches the body of the response (if it is a valid XML) and returns the matching objects(s). If nothing is found, then null is returned.

Note: When returnMultipleValues is set as true, and there are a high number of returned values, using the converters and/or transform operations may affect performance.

options can include:

path (mandatory) string

The XPath to use for the search.

returnMultipleValues (optional) boolean If unspecified or is false, returns only the first result; otherwise, returns an array with all results.
converters (optional) string

The converters are applied to the extracted value and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

If returnMultipleValues is true, the converters are applied to all returned values.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

If returnMultipleValues is true, the transform function is applied to all extracted values.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

 const productNameExtractor = new load.XpathExtractor("productName","/products[0]/name");
 const productNameExtractorSingle = new load.XpathExtractor("firstProductName",{
    path: "/products[*]",
    returnMultipleValues: false
 });

 const myPageRequest = new load.WebRequest({ 
      url: "http://myServer.com/main/products.xml",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors:[
          productNameExtractor, //Extract the name of the first product
          productNameExtractorSingle //Extract the name of the first product 
        ]
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`The name of the first product is ${myResponse.extractors.productName}`);

TextCheckExtractor(name, text, scope) : ExtractorObject

This constructor creates an extractor object for the text check extractor. It returns true if the given text was found in the response, based on the scope argument. If the given text is not found then false is returned.

For more information, refer to the next constructor version.

TextCheckExtractor(name, options) : ExtractorObject

This constructor creates an extractor object for the text check extractor. It returns true if the given text was found in the response, based on the scope argument. If the given text is not found then false is returned.

options can include:

text (mandatory) string The string to search for in the response.
scope (optional) string

The scope of the search.

  • If scope is not defined, then only the response body is searched.
  • If scope is set to load.ExtractorScope.All, then both the response headers and the response body are searched for text.
  • If scope is set to load.ExtractorScope.Body, then only the response body is searched for text.
  • If scope is set to load.ExtractorScope.Headers, then only the response headers are searched for text.
includeRedirections (optional) boolean If set to false, then the search is not performed on the headers and body of all pages returned by redirection of the WebRequest.
failOn (optional) boolean

If defined, the actual result during runtime is compared to this value. If equal, an exception is thrown stopping the script execution, and the error is added to the snapshot.

Note: For the error is added to the snapshot, the log level in the local config.yml must be set to Error or higher.

converters (optional) string

The converters are applied to the extracted value and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

const textCheck1 = new load.TextCheckExtractor("checkBody","hello");
 const textCheck2 = new load.TextCheckExtractor("checkAll",{
   text: "world",
   scope: load.ExtractorScope.All,
   failOn: false
 });

 const myPageRequest = new load.WebRequest({
      url: "http://myServer.com/main/products.json",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors:[
          textCheck1, //Check that response body contains "hello"
          textCheck2  //Check both the body and the headers for the word "world" but fail the iteration if the word isn't found
        ]
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
if (myResponse.extractors.checkBody){
    load.log(`The world "hello" was found in the response body`);
}

HtmlExtractor(name, querySelector, attributeName) : ExtractorObject

This constructor creates an extractor object for the HTML extractor. It searches the body of the response (if it is a valid HTML) and returns all objects matching the given CSS query. If nothing is found, then null is returned.

For more information, refer to the next constructor version.

HtmlExtractor(name, options) : ExtractorObject

This constructor creates an extractor object for the HTML extractor. It searches the body of the response (if it is a valid HTML) and returns all objects matching the given CSS query. If nothing is found, then null is returned.

options can include:

querySelector (mandatory) string The CSS query selector to use for the search.
attributeName (optional) string The attribute whose value is extracted. If not defined, inner text is extracted.
occurrence (optional) string/number

The occurrence of the result to return. (This was previously ordinal.) Can be one of:

  • load.ExtractorOccurrenceType.All. All the found occurrences are returned as an array.
  • load.ExtractorOccurrenceType.First. The first occurrence is returned.
  • load.ExtractorOccurrenceType.Last. The last occurrence is returned.
  • A number defining the position of the value to replace, where 0 defines the first occurrence. So, for example, 2 replaces the third occurrence.

If occurrence is not defined, the first occurrence is returned.

converters (optional) string

The converters are applied to the extracted value and convert it from one format to another. The property value is a comma-separated list of converters, to run sequentially on the extracted value.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value.

Arguments:

value The extracted value.
request The WebRequest from which the value was extracted.
response The WebResponse before the transformation.

Note: The order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

 const productNameExtractor = new load.HtmlExtractor("productName","div[productId=3]","productName");
 const productNameExtractorSingle = new load.HtmlExtractor("lastProductName",{
   querySelector: "div",
   attributeName: "productName",
   occurrence:load.ExtractorOccurrenceType.Last
 });

 const myPageRequest = new load.WebRequest({
      id: 1,
      url: "http://myServer.com/main/products.html",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors:[
          productNameExtractor, //Extract the name of the product with id = 3 via the productName attribute
          productNameExtractorSingle //Extract the value of the productName attribute of the last div that has productName 
        ]
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`The name of the product is ${myResponse.extractors.productName}`);

const webResponse2 = new load.WebRequest({
    id: 2,
    url: "https://myHost/auth/oauth2/grant",
    method: "GET",
    extractors: new load.HtmlExtractor("SAMLRequest", {
            "querySelector": "input[type=hidden][name=SAMLRequest]",
            "attributeName": "value"
        }),
    ],
}).sendSync();

CookieExtractor(name, cookieName, domain, path) : ExtractorObject

This constructor creates an extractor object for the cookie extractor. It searches the cookies of the response with the name specified in cookieName, with domain and path as optional arguments, and returns the first matching cookie. If nothing is found then null is returned.

For additional options, use the next constructor version.

CookieExtractor(name, options) : ExtractorObject

Creates the same ExtractorObject as in the previous call but allows some extra options.

options can include:

cookieName (mandatory) string The cookie name.
domain (optional) string The cookie domain.
path (optional) string The cookie path.
occurrence (optional) string/number

The occurrence (previously Ordinal) of the result to return. If occurrence is not defined then the first occurrence is returned. If occurrence is set to a number, than the result with the given number index is returned. If occurrence is set to load.ExtractorOccurrenceType.All then all the found occurrences are returned as an array.

You may also set occurrence to either load.ExtractorOccurrenceType.First or load.ExtractorOccurrenceType.Last, to retrieve the first or the last occurrence respectively.

includeRedirections (optional) boolean

If set to false, then the search is not performed on the headers and body of all the pages returned by redirection of the WebRequest.

converters (optional) string

The converters are applied to the extracted value, and convert it from one format to another. The property value is a comma-separated list of converters to run sequentially on the extracted value.

Supported converters are: urlEncode, urlDecode, htmlEscape, htmlUnescape, base64Encode, base64Decode, evalString

Note: evalString converts hexadecimal escape sequences (two hexadecimal digits following \x) and Unicode escape sequences (four hexadecimal digits following \u) to plain strings.

transform (optional) function(value, request, response)

If defined, this function is called before the WebReponse is returned by send or sendSync on the extracted value. The arguments are:

value - the extracted value

request - the WebRequest from which the value was extracted

response - the WebResponse before the transformation

Note that the order in which the transformations are called is the same order in which the extractors appear within the WebRequest extractors property.

Example:

 const cookie1 = new load.CookieExtractor("myCookie1", "jsessionid", "go.mic.com");
 const cookie2 = new load.CookieExtractor("myCookie2",{
   cookieName:"jsessionid",
   path:"/",
   occurrence:load.ExtractorOccurrenceType.Last
 });

 const myPageRequest = new load.WebRequest({ 
      url: "http://myServer.com/main/product.html",
      method: "GET",
      returnBody: false, //You don't need to return the body to get the extractors
      extractors:[
          cookie1, //Extract jsessionid cookie with domain go.mic.com value
          cookie2  //Extract jsessionid cookie with path \ value
        ]
  });

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`jsessionid with domain go.mic.com ${myResponse.extractors.cookie1}`);

load.log(`jsessionid with path \ ${myResponse.extractors.cookie2}`);

Extractor results

The results of all the extractors are merged into a single object under the extractors property on the result object. For example, when using extractors on a WebRequest, the resulting extracted values are stored on the extractors property of the WebResponse object created by that request.

The extracted values can be retrieved from the extractors property by using the extractor name. The name is specified as the first argument of the extractor object constructor.

For convenience, each extracted value is also stored on the extractors property of the load namespace, accessible anywhere in the script.

Note: If an extractor object has the same name as another extractor object, only the last extractor result is saved and a warning is printed to the log.

Each extractor object returns the results in a different format. For the particular format, see the particular extractor object definitions in Extractor types.

Example:

const documentTitleExtractor = new load.RegexpExtractor("title","<title>(.*?)</title>","i");
const myPageRequest = new load.WebRequest({
	url: "http://myServer.com/main/product.html",
	method: "GET",
	returnBody: false, //You don't need to return the body to get the extractors
	extractors: [documentTitleExtractor]
});

const myResponse = myPageRequest.sendSync();

//The extractor result value is available under the name of the extractor
load.log(`The title of the page is ${myResponse.extractors.title}`);
//The result is also stored on the load namespace
load.log(`The title of the page is ${load.extractors.title}`);

Back to top

Transactions

Transactions provide the means to measure the time it takes to execute specific, well-defined parts of the script.

constructor(name) : Transaction

Creates a new transaction with the given name.

Note: The new transaction has the NotStarted state. You must call the start() method explicitly to start the transaction.

Example:

let transaction = new load.Transaction("My Transaction");

Properties

Supported properties list:

name string Always set. The name (not empty) of the transaction as it was passed to the constructor.
state string

Always set. Can be one of:

  • load.TransactionState.NotStarted. After the transaction is created but not yet started.
  • load.TransactionState.InProgress. After the transaction was started but not yet ended.
  • load.TransactionState.Ended. After the transaction has ended.
startTime number Set on call to start. The UNIX timestamp (in milliseconds) of the engine time on which the transaction has started.
duration number Set on call to stop, set, or update . The number of milliseconds passed from the call to start until the transaction was ended either by a call to end or by the engine.
status string

Always set but you may need to call update to get the updated value. The current status of the transaction, can be one of:

  • load.TransactionStatus.Passed. If the transaction is currently considered passed.
  • load.TransactionStatus.Failed. If the transaction is currently considered failed.

Methods

start()

Starts the transaction and changes its status to InProgress.

Example:

let transaction = new load.Transaction("My Transaction");
transaction.start();

stop([status])

Stops the transaction and changes its status to the current status of the transaction. If the optional status argument is provided, the stopped transaction will have the given status and not the current transaction status. The valid values for status are Passed and Failed and can be taken from load.TransactionStatus.Passed and load.TransactionStatus.Failed. Calling stop records the transaction duration in the duration property.

Example:

let transaction = new load.Transaction("My Transaction");
transaction.start();
						
// ... later ...
						
transaction.stop();
//transaction.duration is now assigned with the duration

set(status, duration)

Sets the transaction status and duration to the given arguments. The given status must be one of Passed/Failed (from load.TransactionStatus) and the given duration must be a non-negative number of milliseconds for the transaction duration.

Note: You cannot call set on a started transaction.

Example:

let transaction = new load.Transaction("My Transaction");
transaction.set(load.TransactionStatus.Passed, 1000);
//The transaction is now considered successful and the duration is 1 second
//transaction.duration is now assigned with the duration

update() : transaction

Updates the status, state, and duration properties of the transaction object. The transaction must be either started or ended for the call to succeed.

Returns the transaction object for piping.

Example:

let transaction = new load.Transaction("My Transaction");
transaction.start();
						
// ... later ...
						
transaction.update();
if (transaction.duration > 2000) {
	transactionStatus = load.TransactionStatus.Failed;
}
transaction.stop(transactionStatus);

Back to top

Parameters

Parameters are values generated during runtime by the runtime engine and are exposed to the script through the load.params variable.

Each time you use a parameter variable, the next value is loaded automatically based on the next value selection strategy in the parameters definition file.

Example:

var paramValue = load.params.myParam1;
var nextParamValue = load.params.myParam1; //if nextValue is "always" this will be a new value
var someString = `The value of myParam1 is ${load.params.myParam1}`; //You can put it in a string with the standard JavaScript syntax

For more information, see Parameterize values.

Back to top

General methods

log(message, level)

The log function writes a message to the Vuser log. The optional level argument can be one of:

LogLevel.error, LogLevel.warning, LogLevel.info, LogLevel.debug, LogLevel.trace.

Note:  

  • If level is not specified, or if an invalid value is defined, LogLevel.info is used by default.
  • Avoid using console.log. It is not supported.

Example:

load.log("This will be written to the log", load.LogLevel.debug);

sleep(time)

alias: thinkTime

Pauses the running of the script for the specified number of seconds (time can have a fractional part to simulate milliseconds).

Example:

load.sleep(10.5); //Will pause the script for 10 seconds and 500 milliseconds

sleepAsync(time)

alias: thinkTimeAsync

Pauses the running of the script for the specified number of seconds (time can have a fractional part to simulate milliseconds).

This Async version of thinkTime does not block asynchronous activities. For example, asynchronous web requests, WebSocket messaging, and SSE streaming will all continue to work while executing thinkTimeAsync.

Example:

Copy code
    let T00 = new load.Transaction("Sleep");
    let T01 = new load.Transaction("Request");
    
    let webRequest = new load.WebRequest(“https://httpbin.org/delay/6”);

    T00.start();    
    T01.start();
        let webResponse = webRequest.send().then(function (response) {T01.stop()});
        await load.sleepAsync(10.5);  // Will pause the script for 10 seconds and 500 milliseconds without blocking web request execution.
        await webResponse;
    T00.stop();

setUserCredentials(authenticationData)

A function that enables you to specify authentication parameters for HTTP requests that require authentication. The authenticationData can be an authentication record or an array of authentication records. All subsequent requests will try to apply the given authentication data to any request that requires authentication.

An authentication record has the following structure:

username (mandatory) string

The username for the authentication protocol.

password (mandatory) string The password for the authentication protocol.
domain (optional) string The domain for which this authentication record is applicable.
host (mandatory) string

A string specifying the host or hosts to which this authentication record is applied. It may contain an asterisk (*) to indicate any alphanumeric string. You can specify this field as * to match any host.

The host field is the key of the authentication record. Therefore, creating a new authentication record with the same host overwrites the previous one. If two authentication records match the same host (if an asterisk, *, is used) the first one registered is used.

Example:

load.setUserCredentials({
	username: "loader",
	password: "runner",
	host:"*",
});
						
load.setUserCredentials([{
	username: "john",
	password: "smith",
	domain:"mydomain",
	host:"^mfs1*"
},{
	username: "john",
	password: "doe",
	domain:"mydomain",
	host:"^mfs2*"
])

setUserCredentials(AWSAuthentication)

You can set AWS credentials by passing the AWSAuthentication object to the setUserCredentials function.

constructor(providerType, options) : AWSAuthentication

Creates an AWS authentication credentials object that is used for automatic signing of web requests with the awsSigning argument.

The providerType argument is a string and can be one of:

  • static (load.AWSProviderType.Static). AWS static credentials type provider. The options argument has the following properties:

    accessKeyID string AWS access key ID
    secretAccessKey string AWS secret access key
    sessionToken (optional) string AWS session token
  • env (load.AWSProviderType.Env). Credentials retrieved from the environment variables of the running process. Environment variables used:

    * Access Key ID AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
    * Secret Access Key AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
    * Session Token AWS_SESSION_TOKEN

    The options argument does not need to be provided.

  • shared (load.AWSProviderType.Shared). Credentials retrieved from the shared credentials file. The options argument has the following properties:

    fileName (optional) string

    Path to the shared credentials file.

    If empty, it looks for the AWS_SHARED_CREDENTIALS_FILE environment variable. If the environment value is empty, it defaults to the current user's home directory:

    • Linux/macOS: "$HOME/.aws/credentials"
    • Windows: "%USERPROFILE%.aws\credentials"
    profile (optional) string AWS profile to extract credentials from the shared credentials file. If empty, it defaults to the environment variable AWS_PROFILE, or default if the environment variable is also not set.

Example:

 load.setUserCredentials(new load.AWSAuthentication(load.AWSProviderType.Static, {
           accessKeyID: "myKey",
           secretAccessKey: "mySecret",
       }));

    load.setUserCredentials(new load.AWSAuthentication(load.AWSProviderType.Env));

    load.setUserCredentials(new load.AWSAuthentication(load.AWSProviderType.Shared, {
        fileName: "example.ini",
    }));

setUserCertificate(certFilePath, keyFilePath, password)

A function that enables you to specify certificate and key file path for HTTPS requests that require a certificate. The files must contain PEM encoded data. The password argument is optional, and is used to read a password-protected PEM file.

All subsequent requests will try to use the given certificate with any request that requires a certificate.

Example:

   load.setUserCertificate("./cert.pem", "./key.pem");
   load.setUserCertificate("./cert.pem", "./key.pem", "myPass");

exit(exitType, message)

A function that enables you to stop the execution of the script.

The exitType argument is a string and can be one of the following:

iteration

ExitType.iteration

Stops the current iteration and continues to the next one after performing pacing.

stop

ExitType.stop

Stops the current iteration and tries to run the finalization section of the script, then exits.

abort

ExitType.abort

Ends the script run for the current Vuser (does not try to run finalization).

You can specify an optional message argument that will be printed to the log.

Note: Calling load.exit is not supported from asynchronous callback functions, and is ignored by the engine. For example, from the WebSocket callback function for the onMessage event.

Example:

load.log("Before Exit");
load.exit("stop"); //Can also use load.exit(load.ExitType.stop);
load.log("After Abort"); //This message will not be shown!

unmask(maskedValue) : string

A function that enables you to unmask a masked value. The maskedValue argument is a string generated using DevWebUtils executable.

Note: Masking is not secure and anyone is able to unmask it.

Example:

const request = new load.WebRequest({
    url: "http://someHostName",
    headers: {
        "x-secret-key": load.unmask("Tm90IHRoZSBwYXNzd29yZA==")
    }
});

const response = request.sendSync();

unhide(hiddenValue) : string

Note: This functionality is supported from version 25.3.

A function that enables you to reveal a hidden value. The hiddenValue argument is a string generated using DevWebUtils executable.

Note: Hiding a value is not secure and anyone is able to unhide it.

Example:

Copy code
const oracledb = require('oracledb');
let user = load.unhide('TbSWoTLIRZdGfZNm83E2u7SWjFyeV6ni6lukndD//NJBHA==');
let pwd = load.unhide('5/hFQVg9CxIcL6saU+nh9NOr5eF+NZIRbEUth92ND2zddg==');

let connection = await oracledb.getConnection ({
                user : user,
                password : pwd,
                connectString : "<oracle db host>/<oracle db instance>"
});

decrypt(encryptedValue) : string

A function that enables you to decrypt an encrypted value. The encryptedValue argument is an encrypted string generated using DevWebUtils executable.

Note: During runtime, the encryption key file should be supplied.

Example:

const request = new load.WebRequest({
    url: "http://someHostName",
    headers: {
        "x-secret-key": load.decrypt("Tm90IHRoZSBwYXNzd29yZA==")
    }
});

const response = request.sendSync();

exec(options) : ExecutionResult | Promise

Executes a shell command with the permissions of the DevWeb process. Returns either an ExecutionResult object for the synchronous version, or a Promise that is resolved with the ExecutionResult object for the asynchronous version.

The options argument is an object that has the following properties:

command (mandatory) string The executable file to run.
isAsync boolean

If set to true, a Promise is returned. The Promise is resolved with the ExecutionResult, when the process exists.

Default: false

args (optional) string array The command line arguments for the executable.
returnOutput boolean

If set to true, the standard output is returned to the Vuser script (false by default, to reduce memory footprint).

Default: false

returnError boolean

If set to true, the standard errors output is returned to the Vuser script (false by default, to reduce memory footprint).

Default: false

env (optional) string array Additional environment variables to define for the created process, in the format "key=value".
cwd (optional) string The working directory of the created process.
input (optional) string The input that the created process reads from the standard input.

The ExecutionResult object returned has the following properties:

exitCode number The exit code of the created process.
output string The standard output of the created process. It is available only if returnOutput was set to true.
error string The standard error of the created process. It is available only if returnError was set to true.
message string The error message returned from the created process. It is available only if the exit code is not 0.

If an error occurs during the execution of the external command, an exception is thrown. In this case, the ExecutionResult object is sent on the content property of the exception.

You can use the short version of the function that has the signature (also see the following example):

exec(command, args):ExecutionResult

Example:

load.exec("notepad.exe",["myFile.txt"]);

const result = load.exec({
 command: "cmd.exe",
 args: ["/c","dir"],
 returnOutput: true
})

if (result.exitCode === 0) {
 load.log(`The files are ${result.output}`);
} else {
 load.log(`Error running dir ${result.message}`,load.LogLevel.error);
}

const bgPromise = load.exec({
   command: "backgroundCalculation.exe",
   isAsync: true
});
// ... rest of script ...
// at the end of the script:
await bgPromise;

await load.exec({
   command: "always_error.exe",
   isAsync: true
}).catch((error)=>{
  load.log(`The standard error data is ${error.content.error}`);
});

Back to top

Timer

An object that enables you to create a timer that fires after a specified delay. The timer can fire once, or every time the specified delay has passed, until it is stopped.

Example:

load.action("Action", async function () {
    let counter = 0;
    let timer = new load.Timer(() => {
        load.log(counter + ": timer [" + timer.id + "] called", load.LogLevel.info);
        if (counter === 8) {
            load.log("timer expired", load.LogLevel.info);
            timer.stop();
        }
        counter++;
    }, 1000);
    timer.startInterval();
    await timer.wait();
});

constructor(callback, delay) : Timer

Creates a new timer that calls the given callback function after, at least, delay milliseconds.

It is possible to make the timer call the callback only once, or consecutively, using the appropriate methods (see below).

Methods

stop()

Stops the timer.

Example:

    load.action("Action", async function () {
        let timer = new load.Timer(() => {
                timer.stop();
        }, 5000);
        timer.startTimeout();
        await timer.wait();
    });

startTimeout(): Timer;

Starts a timer that calls the callback when the time (in milliseconds) has passed.

Each call to timer.startTimeout() must be followed by timer.wait(), or there may be undefined behavior when the timer delay has elapsed. For example, the iteration might end before the timer fired.

Example:

    load.action("Action", async function () {
        let counter = 0;
        let timer = new load.Timer(() => {
        }, 1000);
        timer.startTimeout();
        await timer.wait();
    });

startInterval(): Timer;

Starts a timer and sets it to call the callback each time the delay (in milliseconds) has passed.

Each call to timer.startTimeout() must be followed by timer.wait(), or there may be undefined behavior when the timer delay has elapsed. For example, the iteration might end before the timer fired.

Example:

 load.action("Action", async function () {
      	 let counter = 0;
        let timer = new load.Timer(() => {
            if (counter === 4) {
               timer.stop();
            }
            counter++;
        }, 5000);
        timer.startInterval();
        await timer.wait();
    });

wait(): Promise;

Waits for the timeout or interval timer to finish before allowing the iteration to continue. It must be accompanied by await, since it returns a promise.

Example:

load.action("Action", async function () {
        let counter = 0;
        let timer = new load.Timer(() => {}, 5000);
        timer.startTimeout();
        await timer.wait();
});

Back to top

Rendezvous

The rendezvous function creates a rendezvous point in a DevWeb script. When this statement is executed, the Vuser stops running and waits for permission to continue.

  • This function can be used only in an action section, and not in an initialize or finalize section.
  • The name parameter (rendezvous_name) that is supplied to the rendezvous function must be without spaces.

Note: This capability is not available when executing scripts locally using OpenText Performance Engineering for Developers.

Example:

load.action("Action", async function () {
        load.rendezvous("rendezvous_name")
    });

Back to top

Global

Changing the properties of the load object is not permitted, but a global object is provided for you to store your data. You can access this object using the load.global property.

Example:

load.global.myData = 1;

// in another file ...

 load.log(`The value of myData is ${load.global.myData}`); 

Back to top

Config

A global configuration object that is used to supply various configuration data to the running Vuser.

Properties

user

A set of properties of the currently running Vuser:

userId number The ID of the currently running Vuser.
args object Map of key-values supplied for command line arguments.

Example:

load.config.user.userId;   //1 for the first user

load.config.user.args["key1"];   //will return the value of key1 or undefined if not supplied
//OR
load.config.user.args.key1;   //will return the value of key1 or undefined if not supplied

script

A set of properties for the script:

name string The name of the script itself that this Vuser runs.
directory string The directory path to the script that this Vuser runs.
fullPath string The full path to the script that this Vuser runs.

Example:

load.config.script.name;  //"MyScript" if the script is located in C:\scripts\MyScript>
load.config.script.directory; //"C:\scripts\MyScript" if the script is located in C:\scripts\MyScript
load.config.script.fullPath;  //"C:\scripts\MyScript\main.js" if the script is located in C:\scripts\MyScript

host

A set of properties for the host machine that runs the script.

name string The name of the machine running the current Vuser.
platform string The platform of the machine running the current Vuser.

Example:

load.config.host.name;   //The name of the machine running the script
load.config.host.platform; // win32 (for Windows), darwin (for iOS), linux (for Linux)

env

An object that contains all the environment variables as key-value pairs.

The keys are case-sensitive, including on Windows.

Example:

load.config.env.Path; // The path of the machine that runs this Vuser

runtime

Runtime properties for the Vuser script.

iteration Number The number of the currently running iteration.

Example:

load.config.runtime.iteration; // Vuser iteration number

Back to top

Utils

The utils object has some useful functions that may help you with common scripting tasks.

Methods

getByBoundary(source, leftBoundary, rightBoundary) : string

Returns the substring within the source string between leftBoundary and rightBoundary.

If leftBoundary is undefined, the beginning of the source string is used as the left boundary.

If rightBoundary is undefined, the end of the source string is used as the right boundary.

If either boundary is not found in the source string or the source string is invalid, null is returned.

Example:

load.utils.getByBoundary("<Foo>","<",">"); // returns Foo
load.utils.getByBoundary("Unbounded Foo>",undefined,">"); // returns Unbounded Foo
load.utils.getByBoundary("<Unbounded Foo","<",undefined); // returns Unbounded Foo
load.utils.getByBoundary("Some String","<",">"); //returns null

reportDataPoint(name, value)

Reports a data point, with the specified name and value, to the results database. The reported value will be in the CustomDataPoints table in the results database. The timestamp and the reporting Vuser ID are automatically added.

Note: The value must be a number.

Example:

load.utils.reportDataPoint("My data point", 42);

base64Encode(value, options) : string

Returns the base64 encoding of value. If options are defined, encoding is based on the options.

options can include:

charset string

Destination character set of encoded value. For example: iso-8859-1, windows-1252

For the supported character sets, see the Internet Assigned Numbers Authority (IANA) site.

Default: utf-8

base64URL boolean

If true, modified Base64 for URL encoding is used.

In Base64 for URL encoding, the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_', so that using URL encoders/decoders is no longer necessary. Base64 for URL encoding is usually used as part of the URL address or file name.

Default: false

noPadding boolean

If true, padding characters '=' are omitted. Some variants allow or require the padding '=' signs to be omitted, to avoid them being confused with field separators.

Default: false

Example:

let value = load.utils.base64Encode("hello");
// Output: aGVsbG8=

let word = load.utils.base64Encode("schön", { charset: "iso-8859-1" });
// Output: c2No9m4=

let test = load.utils.base64Encode("<<???>>", { base64URL: true,  noPadding: true });
// Output: PDw_Pz8-Pg

base64Decode(value, options) : string | Buffer

Returns the string or Buffer represented by the base64 string value. If options are defined, decoding is based on the options.

options can include:

charset string

Source character set of decoded value. For example: iso-8859-1, windows-1252

For the supported character sets, see the Internet Assigned Numbers Authority (IANA) site.

Default: utf-8

base64URL boolean

If true, modified Base64 for URL decoding is used.

In Base64 for URL encoding, the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_', so that using URL encoders/decoders is no longer necessary. Base64 for URL encoding is usually used as part of the URL address or file name.

Default: false

noPadding boolean

If true, padding characters '=' are omitted. Some variants allow or require the padding '=' signs to be omitted, to avoid them being confused with field separators.

Default: false

isBinaryContent boolean

If true, operation response is expected to be binary and therefore is returned in a Buffer.

Default: false

Example:

let value = load.utils.base64Decode("aGVsbG8=");
// Output: hello

let word = load.utils.base64Decode("c2No9m4=", { charset: "iso-8859-1" });
// Output: schön

let test = load.utils.base64Decode("PDw_Pz8-Pg", { base64URL: true,  noPadding: true });
// Output: <<???>>

randomString(size, options) : string

Returns a generated random string of size size. If options are defined, string generation is based on the options.

options can include:

letters (optional) boolean If true, lowercase and uppercase letters are used as part of the generated string.
digits (optional) boolean If true, digits are used as part of the generated string.
specialChars (optional) boolean If true, specialChars [-_@#!$%&(){}] are used as part of the generated string.
hex (optional) boolean If true, the generated string uses hexadecimal base.
custom (optional) string If specified, the generated string is based on a custom character set.

Example:

Copy code
let randomPattern = load.utils.randomString(35);
load.log(`randomPattern: ${randomPattern}`);
// randomPattern: fN6EgMvq8ubHvhi5vmGQPc1K8CysXsN7vqT

let randomNumber = load.utils.randomString(20, { digits: true });
load.log(`randomNumber: ${randomNumber}`);
// randomNumber: 45658007677846724341

let randomNumber = load.utils.randomString(20, { hex: true });
load.log(`randomString: ${randomNumber}`);
// randomString: 123456789abcdef

let customPattern = load.utils.randomString(15, { custom: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });
load.log(`customPattern: ${customPattern}`);
// customPattern: JRGFQGCDRWOEBAD

uuid() : string

Returns a generated v4 uuid string, based on RFC 4122 and DCE 1.1: Authentication and Security Services.

Example:

let uuid = load.utils.uuid();

hash(algorithm, input, outputEncoding) : string

Returns cryptographic hash computation of input string according to selected algorithm.

Supported algorithm types are: md5, sha1, sha256, sha384, sha512

Supported outputEncoding types are:

base64 (default) Standard base64 encoded string representation.
base64Raw Standard base64 encoding without = padding character.
base64URL Base64 for URL encoding string representation.
base64RawURL Base64 for URL encoding encoding without = padding character.
hex Hexadecimal string representation.

Example:

let signing = load.utils.hash(load.HashAlgorithm.sha256, "my text");

let myHash = load.utils.hash(load.HashAlgorithm.sha256, "my text", load.HashOutputEncoding.base64RawURL);

hash(input, options) : string

Same as hash(algorithm, input, outputEncoding) except algorithm and outputEncoding are provided as an object for the options.

Example:

let signing = load.utils.hash("my text",{
  algorithm: load.HashAlgorithm.sha256
});

let myHash = load.utils.hash("my text",{
  algorithm: load.HashAlgorithm.sha256,
  outputEncoding: load.HashOutputEncoding.base64RawURL
});

hmac(algorithm, secret, input, outputEncoding) : string

Returns cryptographic keyed hash (HMAC) computation of input string according to selected algorithm.

Supported algorithm types are: md5, sha1, sha256, sha384, sha512

Supported outputEncoding types are:

base64 (default) Standard base64 encoded string representation.
base64Raw Standard base64 encoding without = padding character.
base64URL Base64 for URL encoding string representation.
base64RawURL Base64 for URL encoding encoding without = padding character.
hex Hexadecimal string representation.

Example:

let signing = load.utils.hmac(load.HashAlgorithm.sha256, "my_big_secret", "hello world!");

let myHmac = load.utils.hmac(load.HashAlgorithm.sha256, "my_big_secret", "hello world!", load.HashOutputEncoding.base64RawURL);

hmac(input, options) : string

Same as hmac(algorithm, secret, input, outputEncoding) except algorithm, secret, and outputEncoding are provided as an object for the options.

Example:

let signing = load.utils.hmac("hello world!",{
  algorithm: load.HashAlgorithm.sha256,
 secret: "my_big_secret"
});

let myHmac = load.utils.hmac("hello world!",{
  algorithm: load.HashAlgorithm.sha256,
  secret: "my_big_secret",
  outputEncoding: load.HashOutputEncoding.base64RawURL
});

samlEncode(value) : string

Returns a SAML encoded string of value. The SAML message must be deflated, and base64 encoded, before sending as part of the WebRequest.

Example:

let samlMessage = `<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" ID=\"ONELOGIN_809707f0030a5d00620c9d9df97f627afe9dcc24\" Version=\"2.0\" ProviderName=\"SP test\" IssueInstant=\"2014-07-16T23:52:45Z\" Destination=\"http://idp.example.com/SSOService.php\" ProtocolBinding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" AssertionConsumerServiceURL=\"http://sp.example.com/demo1/index.php?acs\">
                      <saml:Issuer>http://sp.example.com/demo1/metadata.php</saml:Issuer>
                      <samlp:NameIDPolicy Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\" AllowCreate=\"true\"/>
                      <samlp:RequestedAuthnContext Comparison=\"exact\">
                        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
                      </samlp:RequestedAuthnContext>
                      </samlp:AuthnRequest>`;
let samlEncode = load.utils.samlEncode(samlMessage);
load.log(`samlEncode: ${samlEncode}`);

totp(secret, timestamp): string

Returns a time-based one-time password (TOTP) token with default values: 6 digits based on the SHA1 algorithm.

The TOTP function uses a cryptographic hashing algorithm (default is SHA1) to generate a token based on a secret (in base32 encoded format) and timestamp (Unix time in milliseconds).

See also the IETF article, rfc6238.

Example:

//base32 encoded string: "12345678901234567890"; 
let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";

let totpTimestamp = Date.now();
load.log(`Time now is: ${totpTimestamp}`);

let key = load.utils.totp(secret, totpTimestamp);
load.log(`TOTP Token: ${key}`);

totp(secret, timestamp, options): string

Same as totp(secret, timestamp) but with user-defined TOTP options. The cryptographic hash algorithm is provided as a parameter.

Supported options types:

digits

4, 6, 8

Default: 6

algorithm

sha1, sha256, sha512, md5

Default: sha1

period

Time in seconds that the TOTP token is valid.

Default: 30

skew

Time in seconds that the TOTP device time is allowed to drift in respect to the server time. The default value is rarely changed.

Default: 1

Example:

//base32 encoded string: "12345678901234567890"; 
let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";

let totpTimestamp = Date.now();
load.log(`Time now is: ${totpTimestamp}`);

let key = load.utils.totp(secret, totpTimestamp, {digits: 8, algorithm: load.HashAlgorithm.sha512});
load.log(`TOTP Token: ${key}`);

Chain

This class provides a mechanism to chain calls to other utils functions or custom functions that have one of the signatures: func(), func(value), func(value,options)

constructor(function, options, . . ., function, options)

It is possible to pass as many (function, options) pairs as needed. A function argument can be the name of a function on the utils object, or any other function that takes a value as its first argument and returns a value.

If there is no option to pass to a specific function, omit the argument altogether.

run(value) : any

Runs the chain on the given value.

Example:

const myChain = new load.utils.Chain("base64Encode",(value)=>{ return {encoded:value};});
const myValue = myChain.run("Hello"); //myValue = {"encoded":"SGVsbG8="}

Back to top

Net

The net API provides useful network-related functionality.

lookupService(service, protocol, domain) : string

Returns a target host for an SRV record, according to priority and weight.

The lookup service is the implementation of an algorithm that enables the resolution of a target host, according to the DNS SRV specification.

The API uses three arguments, service, protocol, and domain, and returns hostname (location of the service) based on RFC 2782 (according to priority and weight). This is the same as the command:

nslookup -type=SRV _<service>._<protocol>.<domain>

If several SRV records have the same priority, then the target is selected randomly, taking into account the weight distribution.

See also the IETF article rfc2782.

Example:

let hostname = load.net.lookupService('xmpp-service', 'tcp', 'example.com');

let request = new load.WebRequest({
    id: 1,
    url: `https://${hostname}`,
    method: `GET`
});

getIPList(ipVersion) : string[]

Returns a list of IP addresses available on a local machine, as an array.

ipVersion values:

<empty> Returns IPv4 addresses.
'4' Returns IPv4 addresses.
'6'

Returns IPv6 addresses.

'all'

Returns complete list of addresses.

Example:

Copy code
let IPlist = load.net.getIPList(load.IPType.all);
load.log(`${IPlist.length} IP addresses available: [${IPList}]`);

setIP(ip)

Sets an IP address for the current Vuser. It must be a valid IP, available on the local machine.

Example:

Copy code
// get random IP from the list of available IP addresses

let IPlist = load.net.getIPList('IPv4');
let vuserIP = IPlist[~~(Math.random() * IPlist.length)];
load.net.setIP(vuserIP)
load.log(`IP: [${vuserIP}] assigned to vuser:${load.config.user.userId}`); 

getIP()

Get the IP address for the current Vuser. Can be used only when multiIP is active, or if IP was set by the setIP function.

Example:

Copy code
let vuserIP = load.net.getIP()
load.log(`IP: [${vuserIP}] assigned to vuser:${load.config.user.userId}`); 

Back to top

Azure

Microsoft Azure Key Vault is a cloud service used to securely store and access secrets, meaning confidential data such as passwords, certificates, or cryptographic keys. Azure API functions support access to Microsoft Azure Key Vault. For more information, see Access Azure Key Vault secrets.

getToken(options) : load.azure.KeyVaultTokenOptions

Returns an internal token with the Azure key vault options..

Example:

Copy code
let token = load.azure.getToken({
    vaultName: "test",
    clientSecret: "test",
    tenantId: "test",
    clientId: "test"
    }
);

getSecret(options) : load.azure.KeyVaultSecretOptions

Returns the secret value from the Microsoft Azure Key Vault.

Example:

Copy code
let secretValue = load.azure.getSecret({
    secret: "test",
    token: token
}
);
load.log(`secret: ${secretValue}`);

Back to top

Cookies

This group of functions enable you to add, remove, or clear the cookies used in web requests.

addCookies(cookies)

Takes a cookie object, or an array of cookie objects, and adds them to the engine. The cookies are used when needed according to the URL of the web request.

Example:

const cookie = new load.Cookie({
	name:"myCookie",
	value:"foo"
})
load.addCookies(cookie);

deleteCookies(cookies)

Takes a cookie object, or an array of cookie objects, and deletes them from the engine. No error is returned if one or more of the given cookies does not exist in the engine (meaning that they were not previously added by addCookies).

Example:

const cookie = new load.Cookie({
	name:"myCookie",
	value:"foo"
})
load.addCookies(cookie);

                    // later
						
load.deleteCookies(cookie);

clearCookies()

Deletes all the cookies that were added to the engine by addCookies.

Example:

const cookie = new load.Cookie({
	name:"myCookie",
	value:"foo"
})
load.addCookies(cookie);

//later
                  
load.clearCookies();

Cookie

An object that encapsulates all the fields of a cookie.

constructor(options, mode) : Cookie

Creates a cookie object that can be used in a setCookie call. The mandatory options argument can be an object with the cookie fields or a string. See definitions in the Set-Cookie command definition.

If an object is provided, it can have the following fields:

name (mandatory) string The name of the cookie.
value (mandatory) string The value of the cookie.
expires (optional) string The maximum lifetime of the cookie as an HTTP-date timestamp.
maxAge (optional) number The number of seconds until the cookie expires.
domain(mandatory) string The hosts to which the cookie are sent.
path (optional) string A URL path that must exist in the requested resource before sending the cookie header.
isSecure (optional) boolean Indicates whether the cookie is secure or not.
isHttpOnly (optional) boolean HTTP-only cookies are not accessible with JavaScript.
sameSite (optional) string, one of "strict", "lax" Allows servers to assert that a cookie ought not to be sent along with cross-site requests.

If a string is provided it should be in the Set-Cookie format such as:

qwerty=219ffwef9w0f; Domain=somecompany.co.uk; Path=/; Expires=Wed, 30 Aug 2019 00:00:00 GMT

Example:

const cookie1 = new load.Cookie({
                    name:"myCookie",
                    value:"foo"
                    domain: “somecompany.co.uk”
});
                    
const cookie2 = new load.Cookie("qwerty=219ffwef9w0f; Domain=somecompany.co.uk; Path=/; Expires=Wed, 30 Aug 2019 00:00:00 GMT");

Back to top

VTS

The VTS integration API enables you to connect to a VTS server and perform various operations on it, such as reading and writing from columns, and managing indices.

vtsConnect(options) : VTSClient

Connects to a VTS server using the connection parameters defined in options. Returns a VTSClient object, or throws an exception if the connection fails. You can call vtsConnect multiple times for different servers or with different user credentials.

Possible options are:

server (mandatory) string The name or IP address of the VTS server host. HTTP is assumed by default, unless the URL begins with HTTPS.
port (mandatory) number The port number.
userName (optional) string The user name.
password (optional) string A plain text password.
portInQueryString (optional) boolean If true, the port number is added to the query string, and the requests are sent on httpPort or httpsPort, respectively.
httpPort (optional) int If portInQueryString is set to true, all the HTTP requests are sent on this port.
httpsPort (optional) int If portInQueryString is set to true, all the HTTPS requests are sent on this port.

Example:

const vtsClient = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
});

VTSClient

The VTSClient is responsible for issuing commands to the VTS server. Use it to obtain other VTS-related constructs such as VTSColumn and VTSRow.

The client enables you to perform general operations that affect more than one column or row.

Methods

getColumn(columnName) : VTSColumn

Returns a reference to a column in the VTS server with the specified column name. It does not verify that the column actually exists.

Example:

const vtsClient = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
});
const myColumn = vtsClient.getColumn("myColumn");

getRow(rowIndex) : VTSRow

Returns a reference to a row in the VTS server with the given row index. The index must not be a negative number. This constructor does not verify that the row actually exists.

Example:

const vtsClient = load.vtsConnect({
server: "http://my.server.com",
port: 1234
});
const myRow = vtsClient.getRow(2);

createColumn(columnName) : VTSColumn

Creates a column on the VTS server and returns a reference to the created column.

const vtsClient = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
});
const myColumn = vtsClient.createColumn("myColumn");

popColumns(columnNames) : Object

Pops the first fields from specified columns. columnNames is an array of the column names that are popped. If columnNames is not specified, all the columns are popped.

Returns:

  • an array of the values from the popped columns.
  • an object where each property key corresponds to a column name, and each property value corresponds to the database value.

Example:

const vtsClient = load.vtsConnect({
server: "http://my.server.com",
port: 1234
});
const columnValues = vtsClient.popColumns(["col1","col2"]);
load.log(`The value of col1 is ${columnValues.col1}`);

rotateColumns(columnNames, placementType) : Object

Retrieves the first field from the specified columns and moves the value to the bottom. columnNames is an array of the column names that are rotated. If columnNames is not specified, all the columns are rotated.

placementType must be one of the following:

load.VTSPlacementType.stacked The data is sent to an available field at the bottom of the column.
load.VTSPlacementType.unique

If the value of the first field already exists elsewhere in the column, the top field is retrieved and then discarded.

Otherwise, data is sent to an available field at the bottom of the column.

Returns an object where each property key corresponds to a column name, and each property value corresponds to the database value.

Example:

const vtsClient = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
});
const columnValues = vtsClient.rotateColumns(["col1","col2"], load.VTSPlacementType.unique);
load.log(`The value of col1 is ${columnValues.col1}`);

setValues(columnNames, values, placementType) : Object

Sets the data given in values into the columns given by columnNames. The number of columns must be identical to the number of values provided.

placementType must be one of the following:

load.VTSPlacementType.sameRow Send all the data to the same row.
load.VTSPlacementType.stacked Data is sent to the available fields in each column according to VTS internal logic.
load.VTSPlacementType.unique Data is sent to available fields in each column only if the value does not already exist in the relevant column.

Example:

const vtsClient = load.vtsConnect({
                    server: "http://my.server.com",
                    port: 1234
                    });
                    const columnValues = vtsClient.setValues(["col1","col2"], ["myValue1","myValue2"], load.VTSPlacementType.sameRow);

replaceExistingValue(columnNames, newValue, existingValue)

Replaces the given newValue in all the columns that were specified by columnNames and where the current field value equals existingValue.

Example:

const vtsClient = load.vtsConnect({
         server: "http://my.server.com",
         port: 1234
       });
 vtsClient.replaceExistingValue(["col1","col2"], "myNewValue", "oldValue");

searchRows(columnNames, values, delimiter) : Object

Searches for a row containing specific values in specific columns. If more than one row meets the condition, the data from only one random row is returned.

Example:

const vtsClient = load.vtsConnect({
         server: "http://my.server.com",
         port: 1234
       });
const row = vtsClient.searchRows(["userID"], ["junior5"], ",");
load.log(`row: ${row.useHash}, ${row.userID}, ${row.userPWD}`) // e.g row: 3, junior5, 12345

VTSColumn

This refers to a column on the VTS server. Use this object to perform operations on the underlying column.

Properties

client : VTSClient

The client that contains this row.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                    
                    myColumn.client.createColumn("newColumn");

Methods

clear()

Clears all data in a column.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                   
myColumn.clear();

size() : Number

Returns the number of fields that contain data in a column.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                   
const size = myColumn.size();
load.log(`The size of someColumn is ${size}`);

createIndex()

Creates an index on a column.

  • If a column is not indexed, the time required to execute addUnique() increases with the number of rows.
  • If the column is indexed, the time for send if unique operations is constant.

For large databases, we recommend that you index columns on which you want to perform unique operations.

A column is locked while an index is being built for it. Any function calls that change the column are queued until the index build completes. If the index exists, this function has no effect.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                   
myColumn.createIndex();

dropIndex()

Deletes the index on a column.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                  
myColumn.dropIndex();

addValue(value, ifUnique)

Sets the last field of a column to a value. If there is no empty field in the column, a new row is created.

If ifUnique is true, the function checks that the value does not exist in the column. If the value already exists in the column, the function has no effect.

Note: value must be a string.

If a column is not indexed, the time required to execute addValue() with ifUnique set to true increases with the number of rows. If the column is indexed, the time is constant.

For large databases, we recommend that you use createIndex() to index columns you want to perform this operation on.

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                   
myColumn.addValue("myValue",true); //Will add "myValue" only if it doesn't exist in the column already

clearField(rowIndex)

Clears the data in a field within the column, as defined by the rowIndex.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                 
myColumn.clearField(3); //Will clear row 3 in this column

incrementField(rowIndex, value)

Changes the value in the field within the column defined by the rowIndex, by the amount passed in argument value. If the field value cannot be converted to an integer, or if there is no data in the field, the field value after the call is value.

Note: value must be a number.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                  
myColumn.incrementField(2, 10); //Will increment row 2 in the column by 10

getFieldValue(rowIndex) : string

Retrieves the data in a field. If there is no data in the field, the output is null.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                  
const myValue = myColumn.getFieldValue(2);

setFieldValue(rowIndex, value, existingValue)

Writes the value to the field within the column defined by the rowIndex. If existingValue was specified, and the existingValue and field values match, the field value is overwritten.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                
myColumn.setFieldValue(1, "new value");
                   
myColumn.setFieldValue(1, "even newer value","new value");

pop() : string

Retrieves the value from the field in the top row of the column. All fields below the first row move up one row.

For example, after the call, the value that was in the second row of the column is now in the first row, and the value that was in the third row is now in the second row. The last field in the column is cleared.

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                   
const someValue = myColumn.pop();

rotate(placementType) : string

Retrieves the data in the first field of the column. The data is removed from the first field and moved to the bottom of the column as specified by the placementType parameter. If there is no data in a cell, the output is null.

placementType must be one of the following:

load.VTSPlacementType.stacked The data is sent to an available field at the bottom of the column.
load.VTSPlacementType.unique If the value of the first field already exists elsewhere in the column, the top field is retrieved and then discarded. Otherwise, data is sent to an available field at the bottom of the column.

Example:

const myColumn = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getColumn("someColumn");
                 
const someValue = myColumn.rotate(load.VTSPlacementType.stacked);

VTSRow

This refers to a row on the VTS server. Use this object to perform operations on the underlying row.

Properties

client : VTSClient

The client that contains this row.

Example:

const myRow = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getRow(1);
                    
myRow.client.createColumn("newColumn");

Methods

clear()

Clears the values from all fields in a row. If a cell has a value, clear() sets the value to an empty string. Cells with no value are not affected. Querying such cells returns null before and after the call to clear().

Example:

const myRow = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getRow(1);
                 
                    myRow.clear();

getValues() : Object

Retrieves the data in a row as an object, which has a property that corresponds to each column name. If there is no data in a field, the corresponding output is null.

Example:

const myRow = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getRow(1);
                    
const values = myRow.getValues();
load.log(`The value of myColumn is ${values.myColumn}`);

setValues(columnNames, values)

Sets the data given in values into the columns given by columnNames. The number of columns must be identical to the number of values provided.

placementType must be one of the following:

load.VTSPlacementType.sameRow Sends all the data to the same row.
load.VTSPlacementType.stacked Sends data to available fields in each column according to VTS internal logic.
load.VTSPlacementType.unique Sends data to available fields in each column only if the value does not already exist in the relevant column.

Example:

const myRow = load.vtsConnect({
	server: "http://my.server.com",
	port: 1234
}).getRow(1);
myRow.setValues(["col1","col2"],["value1","value2"]);

Back to top

File

An object that allows file operations on a particular file.

constructor(path) : File

Creates a file object that performs operations on a file at the given path. The engine controls the file lifecycle, therefore you do not need to open/close the file. The path can be an absolute path, or a relative path to the script directory.

Example:

const myFile = new load.File('data.xml');

Methods

read(options): Object

Reads the file and returns the read value based on the given options.

Possible options are:

forceRead (optional) boolean

When set to true, the caching mechanism is ignored, and the file is read from the disk. Use this option only if the read file can change during the script run.

Default: false

returnContent (mandatory) boolean

When true, the entire content of the file is returned (see extractors property for retrieving partial file data).

Default: true

extractors (optional) extractor object or an array of extractor objects

Works the same way as the WebRequest Extractors.

isBinaryContent (optional) boolean

When set to true, the returned data will be binary within a Buffer object.

Default: false

Returns an object that has two properties:

  • content: The entire content of the read file. This property is available only when returnContent is set to true in the options. If isBinaryContent is set to true, then the returned value is a binary representation of the file inside a Buffer object.
  • extractors: The extracted results of the given extractors. See Extractor results for more details.

Example:

const myFile = new load.File('data.xml');
const readResult = myFile.read({
  extractors:[
    new load.RegexpExtractor("title","<customerCode>(.*?)</customerCode>","i")
  ]
});

load.log(`The customer code in data.xml is ${readResult.extractors.title}`);

append(content)

Appends the content to the end of the file. If the content is a Node.js buffer, the appended content will be binary.

Example:

const myFile = new load.File('results.txt');
myFile.append(`vuser ${load.config.user.userId} passed the first page`);

write(content)

Writes the content to the file, overwriting the existing text in the file. If the content is a Node.js buffer, the written content will be binary.

Example:

 const myFile = new load.File('results.txt');
 myFile.write(`vuser ${load.config.user.userId} passed the first page`);

isExists() : boolean

Checks if the specified file exists.

Example:

const myFile = new load.File('results.txt');
myFile.write(`vuser ${load.config.user.userId} passed the first page`);
const isFileExists = myFile.isExists(); // returns true, if the file exists at the given moment.

Back to top

SSE

Server-sent events (SSE) is a server push technology, enabling a client to receive automatic updates from a server through an HTTP connection. The SSE object enables connection to the AUT, and to receive server-sent event notifications.

When creating an SSE instance, you pass an options object with all the required configuration.

constructor(options) : SSE

Creates a new SSE instance. The mandatory options arguments must include url and onMessage. All other arguments are optional.

The supported options are:

url (mandatory) string

The SSE endpoint in http:// or https:// format. This is the URL for the first request that the client initiates.

separator (optional) string

The delimiter that separates between events.

Default: \n\n

headers (optional) object

A key value store that maps the header name to its value.

Default: {}

method string

The HTTP method that will be used for the request.

Default: GET

body string, object, or Buffer

The body of the request, if the method supports a body (for example, POST or PUT).

If a JSON object is provided, it is converted to a data string automatically upon send.

If the body is a Node.js Buffer, then the body will be sent as binary data.

Default: ""

Content-type examples:

  • www-form-urlencoded. If body equals {"foo":"bar","bat":10} it is converted to: foo=bar&bat=10
  • text\plain form. If body equals {"foo":"bar","bat":10} and formDelimiter is a newline character (\r\n), it is converted to: foo=bar
    bat=10

  • application/json. If body equals {"foo":"bar","bat":10} it is converted to:
    '{"foo":"bar","bat":10}'

onMessage (mandatory) functionfault: false

A callback function for the onMessage event. The assigned function has the signature of func(message), where the message contains the event stream sent by the server.

Each message consists of one or more lines of text, listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for the field value.

onError (optional) function

A callback function for the onError event. The assigned function has the signature of func(error), where error is the error message string.

onOpen (optional) function

A callback function for the onOpen event. The assigned function has the signature of func(response), where response contains the following fields:

  • id (string). The unique connection number.

  • status (number). The status code of the response.

  • headers (object). A key value store of the headers in the response sent by the server.

The created SSE instance has an automatically generated and unique id (string) property, indicating the connection number.

Note: The created SSE instance is not automatically connected to the host. To initiate the connection, the open method must be called.

Example:

Tip: The <DevWeb root folder>\examples\ folder includes an example script for SSE.

Copy code
let messageHandler = function (message) {
load.log(`Message received through an event source: >>>>>>>\r\n${message}\r\n<<<<<<<`,load.LogLevel.info);
}
let errorHandler = function (error) {
load.log(error, load.LogLevel.error);
}
let openHandler = function(response){
load.log(`Connection with the event source [${response.id}] is open`);
load.log(JSON.stringify(response,null,4))
};
const sse = new load.SSE({
url: http://myserver:8080,
headers: {
"Token": load.utils.uuid(),
"User-Agent": "DevWeb Vuser"
},
onMessage: messageHandler,
onError: errorHandler,
onOpen: openHandler
});
 
sse.open();
await load.sleepAsync(30);
sse.close();

Methods

open()

Opens the SSE connection to the remote host.

The HTTP request sent to the server contains Accept: text/event-stream header, which indicates that the client can receive the events stream.

After calling this function it is possible to receive events from the server.

close()

Closes the SSE connection to the server.

Back to top

See also: