Recently, I need to do load tests for a set of REST APIs under Node.js environment. After studying some online articles, I decided to give it a go with AutoCannon. My scenario is that I have already had a sets of requests setup in Postman, and I do not want to rewrite everything for the load test. Luckily, I found a solution that exactly match my requirement (listed below), but I still want to write my own version from a AutoCannon fresher’s perspective and hopefully will be useful for future readers.

Step.1 Export A Collection of Requests from Postman

As shown below, left click the “…” button at the right side of the requests collection. Then choose “Export” in the popup menu.

Trulli
Fig.1 - Export Requests Collection
Afer this step, we should receive a JON file contains all the information of the REST APIs we would like to test.

Step.2 Write Code for Load Testing

We need to create a sepearte xxx.js file that tells AutoCannon what to do.

  • Load request data from exported JSON file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const autocannon = require('autocannon');
const fs = require('fs/promises');

// read array of items from exported .json file from postman
let entries = undefined;

async function getRequests() {
const data = await fs.readFile(
'./youtube_clone_proj.postman_collection.json',
'UTF-8'
);

entries = JSON.parse(data).item;
return true;
}
  • Set up AutoCannon for Each Request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
entries.map(async (entry) => {
// there are multi request in item
entry.item.filter((ele) => {
// filter the empty request
return ele.request.url !== undefined;
}).map(async (ele) => {
console.log(ele.request.method + " " + ele.request.url.raw);
const result = await autocannon({
url: ele.request.url.raw,
method: ele.request.method,
connections: 100,
workers: 50,
duration: 5,
body: ele.request.body === undefined? null : JSON.stringify(ele.request.body),
// read other options here: https://github.com/mcollina/autocannon#autocannonopts-cb
}, finishedBench);

// track process
autocannon.track(result, {renderProgressBar: false});

// this is used to kill the instance on CTRL-C
process.once('SIGINT', () => {
result.stop()
})

function finishedBench (err, res) {
console.log('finished bench', err, res)
}
});

Launch the test

In the terminal window, run the following

1
node xxx.js

Then we should able to see output like this for each invidual request:

Trulli
Fig.2 - API1 result
Trulli
Fig.3 - API2 result
For sure, there are more details left to discover, e.g. settings of _autocannon_, but that is left for reading and searching the official document :)

reference

Benchmark express apis with autocannon from postman collection

Comment and share

  • page 1 of 1
Author's picture

Jingjie Jiang


Find a place I love the most