Javascript API Test Scripting Guide

Prev Next

Catchpoint's API test type supports Javascript ES6 and the Selenium Scripting Language. This article details the options available when creating scripts using Javascript. For more information on scripting using Selenium, see the Selenium Scripting Guide.

Catchpoint API Test Javascript Verbs and Macros:

Open()

open(url, method, sendData)

Arguments:

url Required URL to open request for
method Optional HTTP method to use (default = GET if sendData is null, default = POST if sendData provided)
sendData Optional Data to send in the POST request

Example:

open("http://www.catchpoint.com")
open("https://requestbin.com/r/en3ojstsxdcv", "POST", "some string data")     

openChild()

openChild(url, method, sendData)

Arguments:

url Required URL to open child request for
method Optional HTTP method to use (default = GET if sendData is null, default = POST if sendData provided)
sendData Optional Data to send in the POST request

Examples:

open("http://www.catchpoint.com")
openChild("http://www.google.com")
open("http://www.catchpoint.com")
openChild("http://www.google.com", "POST", "some string data")
open("http://www.catchpoint.com")
openChild("http://www.google.com", null, "some string data")
open("http://www.catchpoint.com")
openChild("http://www.google.com", "PUT", "some string data")
open("http://www.catchpoint.com")
openChild("http://www.google.com", "DELETE")

setStepName()

Using this verb provides the ability to provide a custom name to a step in the API transaction which makes reading charts and waterfalls easier.

setStepName(data)

Arguments:

name Required Name of the step

Examples:

open("http://www.catchpoint.com")
setStepName("Step -1 Catchpoint Page")
open("http://www.portal.catchpoint.com")
setStepName("Step -2 Portal Page")

Catchpoint.startStep()

This verb also provides the ability to provide a custom name to a step in the API transaction which makes reading charts and waterfalls easier. This verb should be used at the start of a step.

Catchpoint.startStep(name)

Arguments:

name Required Name of the step

Examples:

Catchpoint.startStep("01. Open Google")
open("https://www.google.com")
Catchpoint.startStep("02. Open Amazon")
open("https://www.amazon.com")

setNavigatePostData()

setNavigatePostData(data)
setNavigatePostData(data, encodingType)

Arguments:

data Required Data to send in the POST request
encodingType Optional The encoding type of the data. Default is utf-8

Note: when setNavigatePostData is used, the open is automatically considered a POST request.

Examples:

setNavigatePostData("some string data");
open("http://www.catchpoint.com");
setNavigatePostData("some string data", "utf-16");      
open("http://www.catchpoint.com");

Catchpoint.extract() / Catchpoint.extractChild()

Extracts a value from the source using the pattern (a string of regex expression)

Catchpoint.extract(sourceType, pattern)
Catchpoint.extractChild(sourceType, pattern)

Arguments:

sourceType Required Format
req-header : Request Headers
resp-header : Response Headers
resp-content : Response Content
Yes Regular Expression (valid escaped regex string)

Note: When using Regular Expression, any backslashes in the RegEx will need to be doubly escaped.

Example:

//Step - 1
setHeader("Cookie", "foo=bar");     
open("http://example.com/channel/a58231f29bc5423aafd2edf246da5d48.m3u8");
var url = Catchpoint.extract('resp-content','https:///[\\w/\\-\\.\\?=&%]+');

//Step - 2
open(`${url}`) 

Extracts a value from a child request using an index range

extract(sourceType, startIndex, endIndex)
extractChild(sourceType, startIndex, endIndex)

Arguments:

sourceType Required Format
req-header : Request Headers
resp-header : Response Headers
resp-content : Response Content
Yes String
startIndex Yes Integer
endIndex No Integer

setHeader()

setHeader(key, value)

Arguments:

key Required Name of the key
value Optional Value of the key

The key options are as follows:

Header Name Remarks
Accept
Accept-Charset
Accept-Encoding
Accept-language
Cache-Control
Connection
Cookie Using multiple times will append the values
Host
Pragma
Referer
User-Agent
<Custom> Any header name can be supplied
Dns-Override
Request-Override
Sni-Override
Request-Delay
Request-Block
DNS-Resolver-Override

Example:

setHeader("Cookie", "foo=bar");
open("http://www.example.com");

setTracepoint() / setIndicator()

setTracepoint(<insight token>, "tracepoint value")
setIndicator(<insight token>, <number value>)

Example:

setTracepoint('some token', "some override value")
setIndicator('some token', 12345)

Catchpoint.hash()

Catchpoint.hash(algorithm, dataToHash, HMACsecret)

Arguments:

algorithm Required Supported Algorithm: md5,sha1,sha256,sha384,sha512
dataToHash Required Data to be Hased
HMACsecret Optional HMAC secret

Example:

open("https://www.google.com")
var foo = Catchpoint.hash("sha1", "abc@123%", "63727970746969");

//step 2
open(`http://sqa.3genlabs.net/hawksyntheticpageserver/?=${foo})`)

Username/Password/Token

Catchpoint.username("<credentialName>");
Catchpoint.password("<credentialName>");
Catchpoint.token("<credentialName>");

Here the variables would get the values for a username, password, or token configured in the Credentials Library and added to the test in the Requests Section. The credential name corresponds to the name defined for the credential in the Credentials Libarary.

Example:

var token = Catchpoint.token('JS_API_Test_Token');
open(`https://www.google.com/?token=`+token);

storeGlobalVariable()

storeGlobalVariable(value, globalVariableName)

// Step - 1
open("https://www.google.com/");
var a1 = Catchpoint.extract('req-header','user-agent:\\\\s+(\\\\w+)');
var a2 = Catchpoint.extract('req-header','accept-language:\\\\s+(\\\\S+)');
storeGlobalVariable(a1, "global_ua");
storeGlobalVariable(a2,"global_al");

Base64()

Catchpoint.base64(utf8string)

This macro will return Base64 format.


Hex()

Catchpoint.hex(utf8string)

This macro will return the hex string.


Encode()

Catchpoint.encode(utf8string, "hex")
Catchpoint.encode(utf8string, "base64")

  • Hex: This macro will encode the content into Hex format.
  • Base64: This macro will encode the content in the Base64 format.

Decode()

Catchpoint.decode(hexString, "hex")
Catchpoint.decode(base64String, "base64")

This macro will return the format utf8 string.


pause()

pause(integer)

  • This action tells the agent to pause for a set amount of time. The pause's wait time parameter can range from 50 to 30,000 ms.

assert()

assert(boolean)

// Step - 1      open("https://www.example.com/");
var resFirstRequest = Catchpoint.extract('resp-content','(?s).*');
var assertFlag = false;
if (resFirstRequest.indexOf('submitted for processing')!=-1) {
    assertFlag = true;
}
assert(assertFlag);

Other Examples :

JSON Parsing with JavaScript

// Step - 1
open("https://jsonplaceholder.typicode.com/todos/1");
var res = Catchpoint.extract(resp-content,(?s).*)
obj = JSON.parse(res); var res1 = obj.title;     
open(http://sqa.3genlabs.net/hawksyntheticpageserver/?q=${res1});

Macros

${globalVariable}

  • Syntax: ${globalVariable}
  • Purpose: Returns the name of global varaible in the test.
  • Explanation: Used to print the global variable value which we store with the help of storeGlobalVariable().
  • Example: To use the stored variable in a different test under the same division or to print the value.
setHeader('Location', '${globalVariable}')
open(http://www.google.com?=${globalVariable(variablename)})

${LocationName}

  • Syntax: ${LocationName}
  • Purpose: Returns the name of the node used to run the test.
  • Explanation: Used to get the name of the node used to run the test. This can be very useful where a value has to be selected based on the name of the node.
  • Example: Choose a search string based on node location.
setHeader('Location', '${LocationName}')
open("http://www.google.com")

${LocationId}

  • Syntax: ${LocationId}
  • Purpose: Returns the ID of the node used to run the test.
  • Explanation: Used to get the ID of the node used to run the test. This can be very useful where a value has to be selected based on the ID of the node.
  • Example: Choose a search string based on node ID.
setHeader('Location', '${LocationId}')
open("http://www.google.com")

${TimeTrim}

  • Syntax: ${TimeTrim(<format>)}
  • Purpose: To modify and format the date/time. Will also cut off leading 0's (eg 01:00 would be trimmed to 1:00)
  • Explanation: This macro uses the current time by default. you can modify the date using the sub macros sub() to subtract or add() to add time. The number of time units should be prefixed with the date unit. Days are denoted with d, months are denoted with mo, and years are denoted with y. In addition, hours are denoted with h and minutes are denoted with mi.
  • Example: ${TimeTrim(MM/DD/YYYY,add(d5))}

${Time}

  • Purpose: To modify and format the date/time.
  • Explanation: It returns a UTC time stamp for the time at the node where the test ran, in YYYYMMDDHHMISSMSC format (17 characters long). This macro takes up to three parameters:
    • The third parameter (optional, defaults to the 2nd parameter value) refers to the end-range.
    • The second parameter (optional, defaults to current time) refers to the start-range.
    • If none, then the current UTC time in YYYYMMDDHHMISSMSC will be returned otherwise, the first parameter specifies the format.

This macro uses the current time by default. You can modify the date using the sub macros sub() to subtract or add() to add time. The number of time units should be prefixed with the data unit. Days are denoted with d, months are denoted with mo, and years are denoted with y. In addition, hours are denoted with h and minutes are denoted with mi.

  • Examples:
  • ${Time(MM/DD/YY,sub(y4))} [Returns the date in MM/DD/YY format by subtracting year by 4]
  • ${time('YYYY/MM/DD', '2', '4')} [Returns a random date between 2 days in advance to 4 days in advance. In format YYYY/MM/DD ]
  • ${time('YYYY/MM/DD')} [Returns date in format YYYY/MM/DD]
  • ${time} : 20150930165523136 [current UTC time in YYYYMMDDHHMISSMSC]

Note - ${Time} - This macro is a scheduler macro, so it gets executed by the scheduler and not the node. This will not take the time of execution on the node rather it takes the time that is executed on the scheduler.

You can use this Chrome script and can check the screenshot and you will see the difference in Time taken by Catchpoint scheduler and time for Javascript.

open("www.google.com")
runScript("document.getElementsByName('q')[0].value = 'Time(s) macro in CP : '+'${Time(SS)}'+', Time(s) in javascript : '+new Date().getSeconds();")

mceclip1.png

${TimeFormat}

  • Syntax: ${timeFormat}
  • Purpose: To show the current date with time.
  • Explanation: This macro uses the current time by default. You can modify the date using the sub macros sub() to subtract or add() to add time. The number of time units should be prefixed with the data unit. Days are denoted with d, months are denoted with mo, and years are denoted with y. In addition, hours are denoted with h and minutes are denoted with mi.
  • Examples:
  • ${timeFormat(YYYYMMDDHHMI,201301010101,201501010101)} [Returns a random date between given 2 dates]
  • ${timeFormat(YYYYMMDD)}"); [Returns date in format YYYY/MM/DD]
  • ${timeFormat} : 20210218130617015 [current UTC time in YYYYMMDDHHMISSMSC]

${timeEpoch}

  • Syntax: ${timeEpoch}
  • Purpose: To modify and format the date/time to Epoch time.
  • Explanation: The epoch time stamp for the time at the node where the test ran. The epoch timestamp is the number of seconds since 01/01/1970 12AM UTC. The format for the epoch timestamp is 1234567890.
  • Example: open("http://www.google.com?=${timeEpoch}");

${token}

  • Syntax: ${token}
  • Purpose: To include a configured authentication token with a request.
  • Explanation: Will be replaced with the value of the authentication token at runtime. The token must be configured in the test's Request's section.
  • Example: setHeader("authorization", "Bearer ${token}")

${ispId}

  • Syntax: ${ispId}
  • Purpose: Returns the ISP provider ID of the node used to run the test.
  • Explanation: Used to get the ISP provider ID of the node used to run the test. This can be very useful where a value has to be selected based on the ISP provider ID of the node.
  • Example: open("http://www.google.com?=${ispId}");

${ispName}

  • Syntax: ${ispName}
  • Purpose: Returns the ISP provider name of the node used to run the test.
  • Explanation: Used to get the ISP provider Name of the node used to run the test. This can be very useful where a value has to be selected based on the ISP provider Name of the node like Airtel, Jio, Telecom, BSNL etc
  • Example: open("http://www.google.com?=${ispName}");

${cityName}

  • Syntax: ${cityName}
  • Purpose: Returns the city name of the node used to run the test.
  • Explanation: Used to get the city name of the node used to run the test.
  • Example: open("http://www.google.com?=${cityName}");

${testId}

  • Syntax: ${testId}
  • Purpose: Returns the test ID of your scheduled test.
  • Explanation: Used to get the test ID of your scheduled test.
  • Example: open("http://www.google.com?=${testId}");

${random(min, max)}

  • Syntax: ${random(min, max)}
  • Purpose: Returns a random number between two given numbers.
  • Explanation: Random number between the number range defined by the min and max values.
  • Example: open("http://www.google.com?q=${random(5, 50}");

${randomList}

  • Syntax: ${randomList(num1, num2, num3......)}
  • Purpose: Returns a random number from the given list of numbers.
  • Explanation: Used to return a random number every time among the given list of numbers.
  • Example: open("http://www.google.com?${randomList(1,2,3,4,5,6)}");

${randomGuid}

  • Syntax: ${randomGuid}
  • Purpose: Returns random GUID string.
  • Explanation: Used to return random GUID string (36 characters long). For example, 0f8fad5b-d9cb-469f-a165-70867728950e.
  • Example: open("http://www.google.com?${randomGuid}");