Post-response Scripts

API Monitoring & Testing: Post-response Scripts

Post-response Scripts allow you to evaluate the response from an individual request, typically to make assertions to validate the data. You can also extract information from the response headers or body content and store in a variable for later use. Lastly, Post-response scripts can modify HTTP request and responses to remove sensitive information before it is stored.

Defining Assertions

Scripts allow for complex assertion definitions that are not possible to define in the test editor. Assertions are defined using the assert module of the Chai Assertion Library which is included for every script. Both the request and response data objects are available to use in your assertions.

Common Assertion Syntax Reference

assert(expression, message)
Write your own test expressions.
assert('foo' !== 'bar', 'foo is not bar');
assert(Array.isArray([]), 'empty arrays are arrays');
assert.ok(object, [message])
Asserts that object is truthy with an optional descriptive message.
assert.ok('everything', 'everything is ok');
assert.ok(false, 'this will fail');
assert.notOk(object, [message])
Asserts that object is falsy with an optional descriptive message.
assert.notOk('everything', 'this will fail');
assert.notOk(false, 'this will pass');
assert.equal(actual, expected, [message])
Asserts non-strict equality (==) of actual and expected.
assert.equal(3, '3', '== coerces values to strings');
assert.notEqual(actual, expected, [message])
Asserts non-strict inequality (!=) of actual and expected.
assert.notEqual(3, 4, 'these numbers are not equal');

Additional Assertion Syntax Options

Chai offers additional assertion options including checking for nulls, strict equality comparisons, type checking, regex matching, deep object comparisons and more. The library also includes should and expect assertion styles.

View Complete Assertion Syntax Documentation

Examples

// check for specific status code
assert.equal(response.status, 200, "status was 200 OK");
// parse JSON response body into object
var data = JSON.parse(response.body);
// check for specific JSON attribute value
assert.ok(data.is_admin, "customer is an admin")
// check an array for the presence of an item
var exists = false;
var customers = data.customers;
for (var customer in customers) {
    if (customers[customer].id === 123) {
        exists = true;
        break;
    }
}
assert.ok(exists, "customer 123 exists");
// check that all items in a list contain a numeric id with regex and Underscore.js library
assert(_.every(data.customers, function(customer) { return customer.id.match(/^\d+$/); }), "IDs are all numeric");
// check for existence of key named id with Underscore.js library
assert(_.has(data, "id"), "contains 'id' key");
// check that a timestamp is less than now with Moment.js library
var created_at = moment.unix(data["created_at"]);
var now = moment();
assert(now.isAfter(created_at), "create date before now"); 

Getting and Setting Variables

Scripts have access to all Variables that have been defined in Initial Variables/Initial Script, the test editor (see: Execution Order) and previous scripts through the variables global object. Setting a variable value will make it available to subsequent scripts and requests.

Getting a Variable Value

var id = variables.get("id");

Setting a Variable Value

// grab a newly-created user ID and store for later
var data = JSON.parse(response.body);
variables.set("id", data.id);

Removing Sensitive Data from HTTP Requests and Responses

You can also use Post-response Scripts to remove data from the HTTP request and response before being stored for viewing. Edit the request and response objects directly to remove sensitive data like API keys:

// clear out Authorization header
request.headers.Authorization = "";
// redact customer phone numbers
var data = JSON.parse(response.body);
for (var customer in data.customers) {
    customer.phone_number = customer.phone_number.slice(0, -4) + "XXXX";
}
response.body = JSON.stringify(data);

Extracting Variable Data from Text Body

You can use Post-response Scripts to extract data from Text Body by defining the start and end boundaries of extraction.

For instance, if you wish to extract the value QEJ342834982389dDJD from the following response:

<html lang="en">
<head>
    <meta charset="utf-8">
    <title> BlazeDemo</title>
    <meta name="description" content="BlazeMeter demo app">
    <meta name="sage" content="flights app">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script src="/assets/bootstrap.min.js"></script>
	<script>var a = 22; var b = 30; EncryptedString = "QEJ342834982389dDJD"</script>
    <script src="/assets/bootstrap-table.js"></script>
    <link href="/assets/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="/assets/bootstrap-table.css" rel="stylesheet" media="screen">
    <style type="text/css">
        body {
            background: #f5f5f5);
        }
        .hero-unit {
            background-color: #fff;
        }
        .center {
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
</html>

You can run the following extractor script:

var ResponseVar = variables.get("Response");
var extractedtext;
var leftboundary = "EncryptedString = \"";
var rightboundary = "\";</script";
extractedtext = ResponseVar.substring(
ResponseVar.lastIndexOf(leftboundary) + leftboundary.length, 
ResponseVar.lastIndexOf(rightboundary)
);
variables.set("SecretCode", extractedtext);
console.log(extractedtext);

Which results in:

QEJ342834982389dDJD