Load Script API Documentation

Introduction

Load scripts are used to program the behavior of simulated clients in a load test. Each user scenario has its own load script that determines exactly what objects the simulated user will load from the target site during the load test. Simulated users in a load test can run different user scenarios and load scripts, allowing the emulation of multiple user types in the same load test.

Load scripts are programs written using the high-level programming language Lua and can be very simple or very complex, depending on the requirements and programming skills of the tester.

Apart from native functionality of the Lua language, load script programmers can also use the Load Impact load script API to write their load scripts. This API consists of a subset of the Lua standard library, plus a number of Load Impact-specific functions and helper routines, all callable from within the Lua load script. This document describes all the API functionality available to the script programmer.

base64 module

Functions to decode/encode data from/to base64.

base64.decode(data)

This function decodes a base64-encoded string into its original form.

Parameters
data string The base64-encoded data to be decoded.

Returns
string or (nil, error message)

base64.encode(data)

This function takes a string variable and base64-encodes it.

Parameters
data string The string to be encoded.

Returns
string or (nil, error message)

Examples


                  
-- Fetch a small PNG image, and send it as a base64-encoded request parameter in a subsequent request
                  
local img_response = http.get( { url="http://test.loadimpact.com//images/logo.png", response_body_bytes=50000 } )
                  
local encoded_image = base64.encode(img_response.body)
                  
local resp = http.get( { url="http://test.loadimpact.com/index.php?image_data=" .. encoded_image } )
                  
                

bit module

This module provides functionality for bit manipulations. It is based on the LuaJIT BitOp module – see http://bitop.luajit.org/api.html for more details about BitOp.

bit.arshift(x, n)

This function performs a bitwise, arithmetic right-shift of the first argument (x) by the number of bits given by the second argument (n).

Parameters
x number The integer to be bit-shifted.
n number The number of bit positions to shift.

Returns
number

bit.band(x1, x2, [...])

This function performs a logical and on all arguments supplied. The number of arguments can be more than two.

Parameters
x1 number The first value.
x2 number The second value.
... number More values.

Returns
number

bit.bnot(x)

This function returns the bitwise not of its argument (x).

Parameters
x number The value to return bitwise not of

Returns
number

bit.bor(x1, x2, [...])

This function performs a logical or on all arguments supplied. The number of arguments can be more than two.

Parameters
x1 number The first value.
x2 number The second value.
... number More values.

Returns
number

bit.bswap(x)

This module provides functionality for bit manipulations. It is based on the LuaJIT BitOp module – see http://bitop.luajit.org/api.html for more details about BitOp.

Parameters
x number The integer whose bytes we want swapped.

Returns
number

bit.bxor(x1, x2, [...])

This function returns the bitwise xor on all arguments supplied. The number of arguments can be more than two.

Parameters
x1 number The first value.
x2 number The second value.
... number More values.

Returns
number

bit.lshift(x, n)

This function performs a bitwise, logical left-shift of the first argument (x) by the number of bits given by the second argument (n).

Parameters
x number The integer to be bit-shifted.
n number The number of bit positions to shift.

Returns
number

bit.rol(x, n)

Returns the bitwise left rotation of its first argument (x) by the number of bits given by the second argument (n). Bits shifted out on one side are shifted back in on the other side. Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).

Parameters
x number The integer to be rotated.
n number The number of bit positions to rotate.

Returns
number

bit.ror(x, n)

Returns the bitwise right rotation of its first argument (x) by the number of bits given by the second argument (n). Bits shifted out on one side are shifted back in on the other side. Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).

Parameters
x number The integer to be rotated.
n number The number of bit positions to rotate.

Returns
number

bit.rshift(x, n)

This function performs a bitwise, logical right-shift of the first argument (x) by the number of bits given by the second argument (n).

Parameters
x number The integer to be bit-shifted.
n number The number of bit positions to shift.

Returns
number

Examples


                  
-- Get 16 high-order bits from a 32-bit integer (we use the return value from os.time()), hex-encode and print those bits
                  
local x = os.time()
                  
x = bit.lshift(x, 16)
                  
local hex_str = bit.tohex(x, 4)
                  
log.info(hex_str)
                  
                

client module

Functions to control execution and extract information surrounding the current client/VU.
See also the test module to access test-wide settings and data.

client.get_id()

Get the ID of the client/VU who calls this function. The client/VU ID is essentially just the number of the client/VU out of all the clients/VUs running in the current load generator instance – i.e. in the current user scenario on the current load generator host. For example, you might have a test with 3 clients/VUs running user scenario X from Ashburn, Virginia, and 4 clients running the same scenario but from Dublin, Ireland. The clients/VUs in Ashburn will have the IDs 1, 2 and 3 and the clients in Dublin will have the IDs 1, 2, 3 and 4.

Returns
number or (nil, error message)


                  
-- Have only client #1 add an entry to the log
                  
-- This can be very useful if you run a load test with 1,000 simulated clients and
                  
-- want to avoid getting your log swamped with 1,000 copies of the same log message
                  
if client.get_id() == 1 then log.info("Hello world!") end
                  
                  

client.get_load_generator_id()

Get the ID of the load generator where this client/VU is running. The load generator ID number is an integer that is unique for every running instance of our load generator application that is assigned to the current load test. The total number of running load generator instances is determined by several factors: the amount of simulated clients in the test, the number of geographic locations the test is run from, the number of unique user scenarios in the test, and the number of source IP addresses the test has been configured to use. The load generator ID is useful together with the client.get_id() function as a way of getting a test-wide, unique ID for a client (see 3.2. Client/VU module examples for an example).

Returns
number or (nil, error message)


                  
-- Get ID of client
                  
local client_id = client.get_id()
                  
-- Get ID of load generator
                  
local loadgen_id = client.get_load_generator_id()
                  
-- Create a test-wide, unique client ID from the above two IDs
                  
local unique_client_id = loadgen_id * 1000000 + client_id
                  
                  

client.get_repetition()

Get the current repetition (load script iteration) number of the client/VU that calls the function.

Returns
number or (nil, error message)


                  
-- Get ID of client
                  
local client_id = client.get_id()
                  
-- Get ID of load generator
                  
local loadgen_id = client.get_load_generator_id()
                  
-- Create a test-wide, unique client ID from the above two IDs
                  
local unique_client_id = loadgen_id * 1000000 + client_id
                  
local client_repetition = client.get_repetition()
                  
log.info(unique_client_id.." has run the script "..client_repetition.." times")
                  
                  

client.get_sleep_time()

Get the total amount of time (in seconds) the client/VU has spent sleeping up until now.
[Note: during a script validation, all sleep operations are ignored in order to speed up the validation procedure.]

Returns
number or (nil, error message)


                  
..
                  
client.sleep(0.5)
                  
..
                  
client.sleep(0.5)
                  
local total_time = client.get_time_since_start()
                  
local sleep_time = client.get_sleep_time()
                  
local execution_time = total_time - sleep_time
                  
log.info("Total time: "..total_time.." Execution time: "..execution_time);
                  
                  

client.get_source_ip()

Get the source IP address this client/VU is using.

Returns
string or (nil, error message)


                  
log.info("IP "..client.get_source_ip())
                  
                  

client.get_time_since_start()

Get the time elapsed (in seconds) since this client/VU was started.

Returns
number or (nil, error message)


                  
..
                  
client.sleep(0.5)
                  
..
                  
client.sleep(0.5)
                  
local total_time = client.get_time_since_start()
                  
local sleep_time = client.get_sleep_time()
                  
local execution_time = total_time - sleep_time
                  
log.info("Total time: "..total_time.." Execution time: "..execution_time);
                  
                  

client.get_user_scenario_name()

Get the name of the user scenario the client/VU is executing.

Returns
string or (nil, error message)

client.sleep(interval, [unit])

Pause client execution for interval * (1/unit) seconds.
[Note: during a script validation, all sleep operations are ignored in order to speed up the validation procedure.]

Parameters
intervalx The interval of unit time to sleep for.
unit The unit of time to use. The default value is 1 (second).

Returns
true or (nil, error message)


                  
-- Sleep client script for specified time
                  
client.sleep(2.5) -- Sleep for 2.5 seconds
                  
client.sleep(0.5)
                  
client.sleep(1, 1000) -- Sleep for 1 millisecond
                  
client.sleep(0.001) -- also sleep for 1 millisecond
                  
                  

datastore module

The Datastore modules provides functionality to interact with uploaded data stores (CSV files), allowing easy data parameterization in load scripts. The load script writer creates a named data store in the Load Impact user scenario editor interface, then uploads a text data file, in CSV format. The text data file should consist of a number of rows, where each row contains one or more column fields, separated by an arbitrary separator string (or character). The load script writer is then able to use the functions in this module to access the data store, retrieving individual rows from it. The rows retrieved will be returned as Lua tables.

datastore.open(name)

Initialize a data store object inside the load script. This function returns a data store object whose member functions can be used to access the rows of data in the data store.

Parameters
name string The name of the data store we want to initialize. Currently, only one data store per user scenario is allowed, and the data store opened through the use of datastore.open() must be the one associated with the particular user scenario that is running.

Returns
datastore.datastore or (nil, error message)

datastore.datastore

The Datastore object represents a named data store. The load cript writer can use member functions of the Datastore object to query the data store, or to retrieve data rows from it.

datastore:get(index)

Returns a specific row from the data store object. The data store object must first have been initialized through the use of datastore.open.

Parameters
index number The index of the row to retrieve from the data store.

Returns
table or (nil, error message)


                      
-- Initialize the data store named "my data store"
                      
local ds = datastore.open("my data store")
                      
-- Fetch row #43 from the data store
                      
local row = ds:get(43)
                      
local first_column = row[1]
                      
local second_column = row[2]
                      
                      

datastore:get_length()

Returns the number of rows in the data store. Before using get_length(), the data store object must first have been initialized through the use of datastore.open.

Returns
number or (nil, error message)


                      
-- Initialize the data store named "my data store"
                      
local ds = datastore.open("my data store")
                      
for i=1,ds:get_length() do
                      
  local row = ds:get(i)
                      
  local first_column = row[1]
                      
  ....
                      
end
                      
                      

datastore:get_random(unique)

Returns a random row of data from the data store object. The optional parameter unique is a boolean that defaults to false, and which causes rows to only be returned once. I.e. repeated calls to get_random() with the unique parameter set to true will never return the same row from the data store more than once. Before using get_random(), the data store object must first have been initialized through the use of datastore.open. [Note that the unique parameter only makes rows unique within the same client execution context. I.e. client #1 and client #2 may get the same data if they both call get_random() using the unique flag.]

Parameters
unique boolean Controls whether the function should return unique rows or not. Defaults to false.

Returns
table or (nil, error message)


                      
-- Initialize the data store named "my data store"
                      
local ds = datastore.open("my data store")
                      
-- Fetch row #43 from the data store
                      
local row = ds:get_random()
                      
local first_column = row[1]
                      
local second_column = row[2]
                      
                      

Notes

html module

The HTML module provides functions to make the interaction with HTML and its DOM easier, specifically forms.

html.build_form_request(selector, html, url, [fields, ][request_options])

Builds a form request (to use with the http.request_batch related APIs) by parsing form fields from an HTML document and replacing certain fields with data passed in by the user.

Parameters
selector string CSS query to run against DOM.
html string HTML whose DOM to query against.
url string URL of the HTML document.
fields table Table with form fields you wish to override or insert.
request_options table Table with extra http.request params.

Returns
table or (nil, error message)

html.build_form_request_from_response(selector, response, [fields, ][request_options])

Builds a form request (to use with the http.request_batch related APIs) by parsing form fields from an HTML document and replacing certain fields with data passed in by the user.

Parameters
selector string CSS query to run against DOM.
response http.response http.response whose body to run CSS query against.
fields table Table with form fields you wish to override or insert.
request_options table Table with extra http.request params.

Returns
table or (nil, error message)


                  
-- Request a sign in page
                  
local response = http.request({"GET", "http://example.com/signin", response_body_bytes=1000000})
                  
-- Submit sign in form, setting username and password (overriding any default form field values)
                  
response = http.request_batch({
                  
  html.build_form_request_from_response("#my-form-id", response, {username="test", password="1234"}, {response_body_bytes=1000000})
                  
})
                  
-- Make sure sign in is successful by looking for special string
                  
if string.find(response[1].body, "signed in as 'test'") then
                  
    log.info("Success!")
                  
else
                  
   log.error("Failed to sign in!")
                  
end
                  
                  

html.css_query(selector, html or response, [options])

Extracts HTML/XML node based on CSS selector.

Parameters
selector string CSS query to run against DOM.
html or response string or http.response HTML or http.response whose DOM to run CSS query against.
options table Option flags, like whether to return a single (first) node or an iterator function to iterate over all matching nodes. Note that options are passed to this function as a table like so: { html.CSS_QUERY_SINGLE_MATCH }

Returns
iterator function of html.node or html.node or (nil, error message)


                  
-- Request a page
                  
local response = http.request({"GET", "http://example.com/", response_body_bytes=1000000})
                  
-- Query the HTML DOM for matching anchor elements and print href attribute
                  
for n in html.css_query("nav a[lang^='en']", response) do
                  
    log.info(n.attributes['href'])
                  
end
                  
                  

html.extract_form(selector, html or response)

Extract HTML form fields of form matched by specified CSS query. Return a table of form fields.

Parameters
selector string CSS query to run against DOM.
html or response string or http.response HTML or http.response whose DOM to run CSS query against.

Returns
table or (nil, error message)


                  
-- Request a sign in page
                  
local response = http.request({"GET", "http://example.com/signin", response_body_bytes=1000000})
                  
-- Extract a form and submit it (equivalent but longer version of example 5a above)
                  
local form_fields = html.extract_form("#my-form-id", response, {username="test", password="1234"})
                  
response = http.request_batch({
                  
    { "POST", "http://example.com/signin", headers={["Content-Type"]="application/x-www-form-urlencoded"} data=url.build_query_string(form_fields), response_body_bytes=1000000 }
                  
})
                  
-- Make sure sign in is successful by looking for special string
                  
if string.find(response[1].body, "signed in as 'test'") then
                  
    log.info("Success!")
                  
else
                  
   log.error("Failed to sign in!")
                  
end
                  
                  

html.html.parse(html or response)

Parse provided HTML and return a document object.

Parameters
html or response string or http.response HTML to parse.

Returns
html.document or (nil, error message)


                  
-- Request a page
                  
local response = http.request({"GET", "http://example.com/", response_body_bytes=1000000})
                  
-- Parse the HTML into an html.document
                  
local doc = html.parse(response)
                  
-- Print all footer links
                  
for n in doc:xpath_query("//footer/ul/li/a") do
                  
    log.info(n.attributes["href"])
                  
end
                  
                  

html.document

alias of xml.document

html.node

alias of xml.node

ENUMS

  • CSS_QUERY_SINGLE_MATCH: Flag to use with html.css_query to limit return to a single xml.node instead of an iterator function.

http module

This module provides the core functionality of generating outbound HTTP requests and making HTTP responses available to the script writer for optional further processing.

http.delete(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP DELETE request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)


                  
http.delete("https://some.domain.com/api")
                  
// --or
                  
http.delete({
                  
  url="https://some.domain.com/api",
                  
  response_body_bytes=1000000
                  
})
                  
                  

http.get(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP GET request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)


                  
-- Request a sign in page
                  
local response = http.get("http://example.com/signin")
                  
--or
                  
local response = http.get({
                  
  url="http://example.com/signin",
                  
  response_body_bytes=50000
                  
})
                  
                  

http.head(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP HEAD request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)

http.options(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP OPTIONS request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)

http.page_end(name)

Marks the end of measurement for a page metric with specified name (must match the name specified in a previous call to http.page_start). This function is useless without its peer http.page_start which marks where the page metric start measurement is made. Our proxy recorder, as well as out Google Chrome recorder extension, will automatically detect page boundaries during a recording and insert http.page_start and http.page_end calls in the appropriate places.

Parameters
name string The name of the page (will be used as the result name on the test result page). Can be a maximum of 512 characters long.

Returns
void


                  
-- Log page metric
                  
http.page_start("My page")
                  
responses = http.request_batch({
                  
    { "GET", "http://loadimpact.com/" },
                  
    { "GET", "http://loadimpact.com/style1.css" },
                  
    { "GET", "http://loadimpact.com/image1.jpg" },
                  
    { "GET", "http://loadimpact.com/image2.jpg" }
                  
})
                  
http.page_end("My page")
                  
                  

http.page_start(name)

Marks the start of measurement for a page metric. This function is useless without its peer http.page_end which marks where the page metric end measurement is made. Our proxy recorder, as well as out Google Chrome recorder extension, will automatically detect page boundaries during a recording and insert http.page_start and http.page_end calls in the appropriate places.

Parameters
name string The name of the page (will be used as the result name on the test result page). Can be a maximum of 512 characters long.

Returns
void


                  
-- Log page metric
                  
http.page_start("My page")
                  
responses = http.request_batch({
                  
    { "GET", "http://loadimpact.com/" },
                  
    { "GET", "http://loadimpact.com/style1.css" },
                  
    { "GET", "http://loadimpact.com/image1.jpg" },
                  
    { "GET", "http://loadimpact.com/image2.jpg" }
                  
})
                  
http.page_end("My page")
                  
                  

http.patch(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP PATCH request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
data string The body data of the request. Only valid for "POST/PUT/PATCH" requests, this parameter is ignored for other request types.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
base64_encoded_body boolean If set to true, indicates that the data parameter contains base64 encoded data.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)

http.post(url, [ip, ][headers, ][data, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][base64_encoded_body, ][report_results])

Send an HTTP POST request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
data string The body data of the request. Only valid for "POST/PUT/PATCH" requests, this parameter is ignored for other request types.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
base64_encoded_body boolean If set to true, indicates that the data parameter contains base64 encoded data.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)


                  
-- JSON encode a data structure
                  
-- and send it as the body of a POST request
                  
local json_string = json.stringify({ login_credentials = { username = "joe", password = "secret" } })
                  
http.post("https://some.domain.com/login.php", nil, nil, json_string)
                  
// --or
                  
http.post({
                  
  url="https://some.domain.com/login.php",
                  
  data=json_string
                  
})
                  
                  

http.put(url, [ip, ][headers, ][data, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][base64_encoded_body, ][report_results])

Send an HTTP PUT request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
data string The body data of the request. Only valid for "POST/PUT/PATCH" requests, this parameter is ignored for other request types.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
base64_encoded_body boolean If set to true, indicates that the data parameter contains base64 encoded data.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)


                  
-- JSON encode a data structure
                  
-- and send it as the body of a PUT request
                  
local json_string = json.stringify({ login_credentials = { username = "joe", password = "secret" } })
                  
http.put("https://some.domain.com/login.php", nil, nil, json_string)
                  
// --or
                  
http.put({
                  
  url="https://some.domain.com/login.php",
                  
  data=json_string
                  
})
                  
                  

http.request(method, url, [ip, ][headers, ][data, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][base64_encoded_body, ][report_results])

Send an HTTP request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request_batch.

Parameters
method string The HTTP request method to use when sending the request. Can be any of "GET", "PATCH", "POST", "PUT", "HEAD", "DELETE", "OPTIONS" or "TRACE".
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
data string The body data of the request. Only valid for "POST/PUT/PATCH" requests, this parameter is ignored for other request types.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
base64_encoded_body boolean If set to true, indicates that the data parameter contains base64 encoded data.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)


                  
-- Make a a single HTTP request
                  
response = http.request("GET", "http://loadimpact.com/",
                  
  nil,
                  
  { ["X-Myheader"]="Something"})
                  
response = http.request({
                  
  method="GET",
                  
  url="http://loadimpact.com/",
                  
  headers={ ["X-Myheader"]="Something" } } )
                  
-- An equivalent request could also be made using the shorthand http.get() function:
                  
response = http.get({
                  
  url="http://loadimpact.com/",
                  
  headers={ ["X-Myheader"]="Something" } } )
                  
-- Display some response data in the console log:
                  
log.info("DNS lookup time: " .. response.dns_lookup_time)
                  
                  

http.request_batch(requests)

Performs a number of HTTP requests, using multiple concurrent TCP connections (when allowed to do so). This function is blocking and will only return once all transfers have been completed. This function, and its derivatives, supports both positional as well as named arguments when specifying individual request arguments, see the http.examples section for examples on usage.

Parameters
requests table A table of requests to send. Each request item is by itself a table containing http.request parameters for the request.

Returns
[http.response] or (nil, error message)


                  
-- Execute a batch of HTTP requests, set special HTTP headers in some of them
                  
responses = http.request_batch({
                  
    { "GET", "http://loadimpact.com/", nil, { ["X-Myheader"]="Something" } },
                  
    { "GET", "http://loadimpact.com/image1.jpg" },
                  
    { "POST", "http://loadimpact.com/login_ajax.php", nil, { ["X-Anotherheader"]="Something Else" }, "login=test&password=test" }
                  
 })
                  
-- Using only positional arguments
                  
responses = http.request_batch({
                  
    { "GET", "http://loadimpact.com/", nil, { ["X-Myheader"]="Something" }, nil, true, false, 1024, false },
                  
    { "POST", "http://loadimpact.com/login_ajax.php", nil, { ["X-Anotherheader"]="Something Else" }, "login=test&password=test", true, false, 0, false }
                  
})
                  
-- Making the exact same requests using only named arguments
                  
responses = http.request_batch({
                  
    { method="GET", url="http://loadimpact.com/", headers={ ["X-Myheader"]="Something" }, response_body_bytes=1024 },
                  
    { method="POST", url="http://loadimpact.com/login_ajax.php", headers={ ["X-Anotherheader"]="Something Else" }, data="login=test&password=test" }
                  
})
                  
-- Using mixed positional and named arguments
                  
responses = http.request_batch({
                  
    { "GET", "http://loadimpact.com/", headers={ ["X-Myheader"]="Something" }, response_body_bytes=1024 },
                  
    { "POST", "http://loadimpact.com/login_ajax.php", headers={ ["X-Anotherheader"]="Something Else" }, data="login=test&password=test" }
                  
})
                  
                  

http.set_max_connections(max_connections, max_connections_per_host)

Sets the maximum number of connections a single VU may have open at any one time.
em:[Note that this function used to be called ua.set_max_connections() in API version 1.0.]

Parameters
max_connections number The total maximum number of concurrent TCP connections that the VU may open during script execution.
max_connections_per_host number The total maximum number of concurrent TCP connections that the VU may open to a specific host during script execution.

Returns
true or (nil, error message)


                  
-- IE6 uses max 34 connections in total, and max 2 per host (*)
                  
http.set_max_connections(34, 2)
                  
-- Use the IE6 User-Agent string
                  
http.set_user_agent_string("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)")</i>
                  
--
                  
-- Any HTTP requests made from here on in the script will now emulate IE6
                  
                  

http.set_option(name, value)

Set a default behavior for HTTP requests sent after the call was made to this function. An option default value set using this function can usually be overridden in an individual HTTP request, when necessary.
[Note: this is not to be confused with the http.options function, which is used to transmit HTTP OPTIONS requests.]

Parameters
name string The name of the option to set default value of.
value mixed The default option value to set.
Options
Name Value
auto_cookie_handling boolean Turn automatic cookie handling on and off.
auto_decompress boolean Turn on and off automatic inclusion of Accept-Encoding headers in requests with value "gzip, deflate".
connect_timeout number Override default connection timeout in seconds. The default is 120 seconds.
follow_redirects boolean Turn automatic redirect handling on and off globally (can also be controlled per request).
redirect_post_302 boolean Whether 302 responses for a POST request should be redirected as POST (true) or GET (false).
force_sslv2 boolean Force SSL connections to use SSLv2.
force_sslv3 boolean Force SSL connections to use SSLv3.
force_tlsv1 boolean Force SSL connections to use TLS (the most appropriate version will be selected based on server support).
force_tlsv1_0 boolean Force SSL connections to use TLSv1.0.
force_tlsv1_1 boolean Force SSL connections to use TLSv1.1.
force_tlsv1_2 boolean Force SSL connections to use TLSv1.2.
report_results boolean Overrides default. If set to false, no individual results will be reported for URLs though it will still contribute to aggregate results like user load time, bandwidth etc.
response_body_bytes number Overrides default value that specifies how many bytes of body data from the server's reply to save for each request. Default is 0.
timeout number Override default read/write timeout in seconds. The default is 120 seconds.

Returns
true or (nil, error message)


                  
-- Disable redirect handling for all the following requests
                  
http.set_option("follow_redirects", false)
                  
                  

http.set_user_agent_string(ua_string)

Sets the User-Agent HTTP header used by the VU in all following HTTP requests.
The default user agent string looks as follows:
LoadImpactRload/X.Y.Z (Load Impact; http://loadimpact.com);
em:[Note that this function used to be called ua.set_string() in API version 1.0.]

Parameters
ua_string string The user agent string to send along with each following HTTP request as client identification.

Returns
true or (nil, error message)


                  
-- IE6 uses max 34 connections in total, and max 2 per host (*)
                  
http.set_max_connections(34, 2)
                  
-- Use the IE6 User-Agent string
                  
http.set_user_agent_string("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)")
                  
-- Any HTTP requests made from here on in the script will now emulate IE6
                  
                  

http.trace(url, [ip, ][headers, ][auto_redirect, ][auto_decompress, ][response_body_bytes, ][report_results])

Send an HTTP TRACE request and wait for a response from the remote server. This function is blocking and will only return once the transfer has completed. This is a wrapper function around http.request

Parameters
url string The URL for the resource we are requesting.
ip string IP to connect to. This allows the script writer to bypass DNS lookups for individual requests. It offers the same functionality as util.dns_remap but with more fine-grained control.
headers table A table of custom HTTP headers to send along with the request.
auto_redirect boolean If set to true, redirects will be handled automatically (the client will follow them). If set to false, any redirect will result in the completion of this request, which means that any subsequent requests that follow the redirect path have to be issued by the script programmer through new http.request() calls. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
auto_decompress boolean If set to true, compressed content will be automatically decompressed upon reception. Defaults to false. The default value can also be changed through the use of the http.set_option() functionality.
response_body_bytes number Specifies how many bytes of body data from the server's reply to save. Defaults to zero (0). The default value can also be changed through the use of the http.set_option() functionality.
report_results boolean If set to false, no individual results will be reported for this URL though it will still contribute to aggregate results like user load time, bandwidth etc. Defaults to true. The default value can also be changed through the use of the http.set_option() functionality.
connect_timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.
timeout number Connection timeout in seconds. Defaults to 120 seconds. The default value can also be changed through the use of the http.set_option() functionality.

Returns
http.response or (nil, error message)

http.response

The http.response class is a data structure that contains information about a completed HTTP transaction.

Attributes
Name Data type Description
body string The HTTP response body.
body_size number The size of the HTTP response body in bytes.
compressed boolean A boolean that indicates whether the body of the HTTP response was compressed or not.
compressed_body_size number The size of the HTTP response body, in bytes, if the HTTP response body was compressed, otherwise -1.
connect_time number The time, in decimal seconds, it took to establish a TCP connection with the server.
content_type string The content type reported by the server in the HTTP response.
cookies table The cookies sent by the server in the HTTP response.
dns_lookup_time number The time, in decimal seconds, it took to perform a hostname->IP lookup for the server host.
download_time number The time, in decimal seconds, it took from reading the first byte of data and until the entire resource was downloaded from the server.
header_size number The size of the HTTP response headers in bytes.
headers table The HTTP response headers.
ip string The IP address of the host to which the request was sent.
redirect_time number The time, in decimal seconds, that was spent redirecting. This is the roundtrip time (RTT) for the HTTP messages. Excluding DNS lookup time and TCP connection time.
request_method string The HTTP request method used by the original HTTP request that led to this HTTP response – can be "GET", "PATCH", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE".
request_size number The size of the sent HTTP request in bytes.
request_url string The URL of the original HTTP request that led to this response.
ssl_handshake_time number The time, in decimal seconds, it took to perform the SSL handshake for an HTTPS request.
status_code number The HTTP return status code.
status_msg string The HTTP return status line.
time_to_first_byte number The time, in decimal seconds, until the first byte of the HTTP response was received from the server.
total_load_time number The total load time for this resource.
url string The effective URL that the initial request ended up pointing to, after redirects.

                        
local response = http.get({
                        
  url="http://api.loadimpact.com/xxxx"
                        
  response_body_bytes=50000
                        
})
                        
if response.status_code ~= 200 then
                        
  log.error('login API error')
                        
  test.abort()
                        
end
                        
log.info("load time "..response.total_load_time)
                        
local data = json.parse(response.body)
                        
                      

json module

This module provides functionality for encoding to and decoding from JSON format. Important to note is that this module currently doesn't support null values.

json.parse(string)

This function takes a JSON string, parses it, and returns a matching Lua table with all the JSON objects.

Parameters
string string JSON string to parse into Lua data structure.

Returns
table or (nil, error message)


                  
-- Login via POST and parse the response
                  
local response = http.request({"POST",
                  
        "https://api.xxx.com/login",
                  
        headers = {["Content-Type"] = "application/json"},
                  
        response_body_bytes=1000000})
                  
local token = json.parse(response.body).token.value
                  
                  

json.stringify(table)

This function takes a Lua table and generates a JSON string from it.

Parameters
table table Table to encode into a JSON string.

Returns
table or (nil, error message)


                  
-- JSON encode a data structure and send it as the body of a POST request
                  
local json_string = json.stringify({ login_credentials = { username = "joe", password = "secret" } })
                  
http.post({
                  
  url="https://some.domain.com/login.php",
                  
  data=json_string
                  
})
                  
                  

log module

Functions to log things during a test run. Logged messages will end up on the test result page during a load test or shown validation window during validation runs.

log.debug(message)

Parameters
message mixed The message you want to log

Returns
void

log.error(message)

Logs a text message that is stored in the results database and which will be displayed in the logging section of the test results page, or in the output window during a validation run. The background color is slightly different for debug messages, making them easy to separate from normal "info" messages.

Parameters
message mixed The message you want to log

Returns
void

log.info(message)

Parameters
message mixed The message you want to log

Returns
void

log.log(message)

Parameters
level string Log level
message mixed The message you want to log

Returns
void

ENUMS

  • DEBUG: Debug log level
  • ERROR: Error log level
  • INFO: Info log level

Examples


                  
-- Add an entry to the log
                  
log.info("Hello world!")
                  

                  
-- Have only client #1 add an entry to the log
                  
-- This can be very useful if you run a load test with 1,000 simulated clients and
                  
-- want to avoid getting your log swamped with 1,000 copies of the same log message
                  
if client.get_id() == 1 then log.info("Hello world!") end
                  
                

regex module

This module provides powerful regular expression (regex) functionality based on the widely used PCRE C library.

regex.compile(pattern, [flags])

Initialize a regex.compiledregex, pre-compiling the provided pattern. The returned object's member functions can be used to perform regex searches/matches on a subject and then access matched strings.

Parameters
pattern string The regex pattern to compile and base future matches on.
flags table Optional table of flags.

Returns
regex.compiledregex or (nil, error message)

regex.gmatch(pattern, subject, [flags, ]offset)

This function creates and returns a generator-style iterator function that is meant to be used in a for-loop to find all pattern matches in the specified subject.

Parameters
pattern string The regex pattern to look for.
subject string The subject to search for occurrences of pattern.
flags table Optional table of flags.
offset number Numeric offset in subject where to start looking for pattern. Defaults to 1.

Returns
iterator function of regex.match

regex.match(pattern, subject, [flags, ]offset)

This function looks for the first occurrence of pattern in the specified subject.

Parameters
pattern string The regex pattern to look for.
subject string The subject to search for occurrences of pattern.
flags table Optional table of flags.
offset number Numeric offset in subject where to start looking for pattern. Defaults to 1.

Returns
regex.match or (nil, error message)

regex.sub(pattern, replacement, subject, [flags])

This function searches the subject for pattern matches and replaces them with the replacement string. The replacement string can contain references to capture groups using the format "1" (sans quotes).

Parameters
pattern string The regex pattern to look for.
replacement string The replacement string, can contain capture group references.
subject string The subject to search for occurrences of pattern.
flags table Optional table of flags.

Returns
regex.match or (nil, error message)

regex.compiledregex

A wrapper around a compiled regex pattern. Provides the same match and gmatch methods as those available as freestanding functions in the regex module, the difference being that the compiledregex pre-compiled the pattern and thus speeds up repeated uses of the same pattern.

compiledregex:captures()

Returns number of possible captures in regex pattern.

Returns
number or (nil, error messages)

compiledregex:gmatch(subject, offset)

This method creates and returns an iterator function that is meant to be used in a for-loop to find all pattern matches in the specified subject.

Parameters
subject string The subject to search for occurrences of pattern.
offset number Numeric offset in subject where to start looking for pattern. Defaults to 1.

Returns
iterator function of regex.match

compiledregex:match(subject, offset)

This function looks for the first occurrence of pattern in the specified subject.

Parameters
subject string The subject to search for occurrences of pattern.
offset number Numeric offset in subject where to start looking for pattern. Defaults to 1.

Returns
regex.match or (nil, error message)

regex.match

The regex match object represents the result of a regex match operation.

match:capture(index or name)

Returns captured string identified by capture index or name. Capture index 1 is the full match.

Parameters
index or name number or string Either the index of a capture or the name if a named capture was specified in the pattern.

Returns
string or (nil, error message)

match:capture_end(index)

Returns end offset of specified capture in subject.

Parameters
index number The index of capture for which to get end offset.

Returns
number or (nil, error message)

match:capture_start(index)

Returns start offset of specified capture in subject.

Parameters
index number The index of capture for which to get start offset.

Returns
number or (nil, error message)

match:captured()

Returns number of captures in match.

Returns
number or (nil, error message)

ENUMS

Examples


                  
-- Find and print first word
                  
local m = regex.match("\w+", "hello world")
                  
print(m:capture(1))
                  

                  
-- List of data items to match
                  
local items = {
                  
    "aabbcc",
                  
    "123456",
                  
    "ddeeff",
                  
    "123456",
                  
    "gghhii",
                  
    "123456",
                  
}
                  
-- Compile a regex pattern for repeated use, to match data items containing only characters of the alphabet
                  
local r = regex.compile("[a-z]+")
                  
-- Loop over data items, printing the ones that match
                  
for i, d in ipairs(items) do
                  
    if r:match(d) then
                  
        print(d)
                  
    end
                  
end
                  

                  
-- HTML body
                  
local body = [[
                  
    <html>
                  
        <head>
                  
            <title>Example</title>
                  
        <head>
                  
        <body>
                  
            <input name="firstname" value="john">
                  
            <input name="surname" value="doe">
                  
        </body>
                  
    </html>
                  
]]
                  
-- Compile regex before use
                  
local r = regex.compile("<([a-z]+)[^>]*>")
                  
-- Find all elements
                  
for m in r:gmatch(body) do
                  
    -- Print tag name
                  
    print(m:capture(2))
                  
end
                  
                

Notes

  • See PCRE for more detailed information of the regular expression engine behind the API.

result module

The result module contains functionality for controlling the aggregation and storage of metric data. For example, the result.custom_metric function allows you to store arbitrary result metrics during a load test.

result.custom_metric(name, value)

This function allows you to store your own, custom result metrics. You can create any metric you like, give it a name, and use this function to store result values throughout your load test. Custom metrics are graphable on the test result page, and are included in CSV load test result exports, just like our standard metrics.

Parameters
name string The name of your custom metric. This is used to aggregate all data points belonging to the same metric. It is case-sensitive and can be a maximum of 512 characters long.
value number An individual data point of the metric. Store as many of these as you like, but be aware that results are aggregated every 3 seconds. This means that if you store e.g. 5 individual data points per second, totaling 15 data points in 3 seconds, the system will compute aggregate values from your 15 data points and store those values as the data point for the 3-second sampling interval.

Returns
true or (nil, error message)


                  
-- Measure the time it takes to complete several HTTP requests,
                  
-- and then store that time as the result metric "total_load_time"
                  
start_time = util.time()
                  
http.request_batch({
                  
    { "GET", "http://loadimpact.com", nil, { ["X-Myheader"]="Something" } },	{ "GET", "http://loadimpact.com/image1.jpg" },
                  
    { "POST", "http://loadimpact.com/login_ajax.php", nil, { ["X-Anotherheader"]="Something Else" }, "login=test&amp;password=test" }
                  
 })
                  
end_time = util.time()
                  
result.custom_metric("total_load_time", end_time - start_time)
                  
                  

test module

The test module provides APIs to access test-wide settings and data.
See also the client module to extract information surrounding the current client/VU.

test.abort()

Aborts the currently running load test.

Returns
void


                  
local response = http.get({
                  
  url="http://api.loadimpact.com/xxxx",
                  
  response_body_bytes=50000
                  
})
                  
if response.status_code ~= 200 then
                  
  log.error('response API failed')
                  
  test.abort()
                  
end
                  
local data = json.parse(response.body)
                  
                  

test.get_name()

Get the name of the currently running load test.

Returns
string or (nil, error message)


                  
local test_name = test.get_name()
                  
-- use test_name convention for your scenario
                  
local is_smoke_test = string.match(test_name, "SMOKE")
                  
if is_smoke_test then
                  
  log.info('running a SMOKE test')
                  
else
                  
  log.info('running a normal test')
                  
end
                  
                  

test.get_clients()

Get the max number of VUs in the load test.

Returns
number


                  
local response = http.get({
                  
  url="http://api.loadimpact.com/xxxx",
                  
  response_body_bytes=50000
                  
})
                  
local threshold_x = 0.5
                  
if test.get_clients() > 1000 then
                  
   -- increase threshold when large load
                  
   threshold_x = 0.9
                  
end
                  
if response.total_load_time > threshold_x then
                  
  log.error('threshold X fails')
                  
  test.abort()
                  
end
                  
                  

test.get_time_since_start()

Get the elapsed time since the load test was started.

Returns
string or (nil, error message)


                  
..
                  
..
                  
if test.get_time_since_start() > 180 then
                  
  -- do something after 3 minutes since the load test was started
                  
..
                  
end
                  
                  

test.is_validation

Check whether this load script is being run in a validation or load test.

Returns
boolean or (nil, error message)


                  
if test.is_validation() then
                  
  log.info('running a validation')
                  
end
                  
                  

url module

Functions to compose and decompose URLs and other miscellaneous URL functionality.

url.build(components)

Assemble a URL string from a table of URL components, e.g. created with url.parse().

Parameters
components table Table with URL components, see url.parse for list of valid components.

Returns
string or (nil, error message)


                  
-- Parse a URL, print parts of the URL, and then reassemble it
                  
local parsed = url.parse("http://example.com/")
                  
print(parsed.schema)
                  
print(parsed.host)
                  
print(parsed.path)
                  
local urlstr = url.build(parsed)
                  
                  

url.build_query_string(query_params)

Assemble table of query string parameters into a string.

Parameters
query_params table Table with query parameters.

Returns
string or (nil, error message)


                  
local form_fields = {
                  
  mail = url.escape("admin@hola.com"),
                  
  password = url.escape("mypassword")
                  
}
                  
http.request({
                  
  method="POST",
                  
  url="http://loadimpact.com/",
                  
  headers={ ["Content-Type"]="application/x-www-form-urlencoded" },
                  
  data=url.build_query_string(form_fields)
                  
})
                  
                  

url.escape(url_string, [safe_chars])

Percent-encodes all characters in a string (that are not reserved) into an escaped hexadecimal representation.

Parameters
url_string string The string to encode.
safe_chars string A string with characters to exclude from encoding.

Returns
string or (nil, error message)


                  
local strViewstate = string.match(response[1].body,'id="__VIEWSTATE" value="(.-)"' )
                  
http.request_batch({
                  
  {"POST", "http://my.example.se/Pages/Booking",
                  
  headers={["Content-Type"]="application/x-www-form-urlencoded"},
                  
  data="__VIEWSTATE=" ..url.escape(strViewstate)
                  
  auto_decompress=true,
                  
  response_body_bytes = 124000}
                  
})
                  
                  

url.join(base_url, second_url)

Compose a single URL by joining a base URL and a second URL.

Parameters
base_url string The base URL.
second_url string The URL to join with the base URL.

Returns
string or (nil, error message)


                  
-- Join a base URL with a path
                  
local result = url.join("http://example.com/", "/a/b/../c")
                  
                  

url.normalize(url_string)

Normalize a URL, preserving the semantics.

Parameters
url_string string The string to normalize.

Returns
string or (nil, error message)

url.parse(url_string)

Parse URL into key/value table.

Parameters
url_string string The string to be parsed.

Returns
table or (nil, error message)


                  
local parsed = url.parse("http://example.com/")
                  
print(parsed.schema)
                  
print(parsed.host)
                  
print(parsed.path)
                  
                  

url.unescape(url_string)

Decodes all percent-encoded characters into their unescaped representations.

Parameters
url_string string The string to decode.

Returns
string or (nil, error message)

util module

The Util module contains miscellaneous functionality that can be useful in a load script, such as time functions etc.

util.dns_remap(host, ip)

Adds an entry to a hostname lookup table that will be checked before querying DNS when the client needs to lookup a hostname. If any other port than the default port 80 is targeted the port number has to be specified. For https this means the port 443 must be specified.
Note: this function used to be called dns.remap() in API version 1.0

Parameters
host{:port} string The hostname and optionally port number to store a lookup table entry for.
ip string The IP address that the hostname should resolve to.

Returns
true or (nil, error message)

util.pprint(...)

The pprint() function pretty-prints the passed arguments using print() (same as log.debug()).

Parameters
.. mixed All arguments passed will be pretty-printed one after the other.

Returns
void

util.time()

The time() function returns the number of seconds since Unix EPOCH as a number value, which means it includes fractional seconds with fairly high (microsecond-) precision. If you are a programmer with previous Lua experience, you can think of util.time() as a higher-precision version of the Lua standard os.time() function (which is also available, by the way – see os.time).

Returns
number

util.unique()

Returns a string guaranteed to be unique across all executing client threads in a load test. The string is based on current time, client ID and client source IP

Returns
string

Examples


                  
-- Make sure clients that load things from loadimpact.com (port 80 and 443) connects to 123.123.123.123
                  
util.dns_remap("loadimpact.com", "123.123.123.123")
                  
util.dns_remap("loadimpact.com:443", "123.123.123.123")
                  

                  
-- Find out how long it took to perform a sequence of requests
                  
starttime = util.time()
                  
http.request_batch({
                  
    { "GET", "http://loadimpact.com" },
                  
    { "GET", "http://loadimpact.com/image1.jpg" },
                  
    { "GET", "http://loadimpact.com/image2.jpg" },
                  
})
                  
 http.request_batch({
                  
    { "GET", "http://loadimpact.com/page2/image3.jpg" },
                  
    { "GET", "http://loadimpact.com/page2/image4.jpg" },
                  
})
                  
endtime = util.time()
                  
elapsed_time = endtime - starttime
                  
                

xml module

This module provides functionality to parse and query XML.

xml.parse(xml_string)

Parse a string of XML data.

Parameters
xml_string string The string of XML to parse.

Returns
xml.document or (nil, error message)

xml.document

The XML document object represents a parsed XML document and provides methods to traverse and inspect the document tree.

document:xpath_query(query, [options])

Executes an XPath query against the XML document tree returning an interator function to iterate over the matched nodes. There is also an option to only return the first matched node, in which case it will be the return value of the method instead of an iterator function.

Parameters
query string The XPath query to execute.
options table Table with options.

Returns
iterator function of xml.node or xml.node or (nil, error message)

xml.node

The XML node object represents a single node in a parsed XML document and provides methods to retrieve its name, attributes, content and children.

Attributes
Name Data type Description
attributes table Retrieve the tag attributes of the node.
children table Retrieve a table with the child nodes of the node.
content string Retrieve the text content of the node.
name string Retrieve the tag name of the node.

ENUMS

  • XPATH_QUERY_SINGLE_MATCH: Flag to use with xml.document.xpath_query to limit return to a single xml.node instead of an iterator function.

Examples


                  
-- Parse XML document
                  
local doc = xml.parse("<?xml version="1.0"><books><book><author>Load Impact</author><title>Load testing with XML</title></book></books></xml>")
                  
-- Print title of all books
                  
for node in doc:xpath_query("//books/book/title") do
                  
    print(node.content)
                  
end
                  

                  
-- Parse XML document
                  
local doc = xml.parse("<?xml version="1.0"><books><book><author>Load Impact</author><title>Load testing with XML</title></book></books></xml>")
                  
-- Print title of first matched book
                  
local node = doc:xpath_query("//books/book/title", { xml.XPATH_QUERY_SINGLE_MATCH })
                  
print(node.content)
                  

                  
-- Parse XML document
                  
local doc = xml.parse("<?xml version="1.0"><books><book><author>Load Impact</author><title>Load testing with XML</title></book></books></xml>")
                  
-- Print title of all books
                  
for node in doc.root.children do
                  
    for node2 in node.children do
                  
        if node2.name == "title" then
                  
            print(node2.content)
                  
        end
                  
    end
                  
end