Saturday, December 12, 2020

API Testing

Summary

I'll be discussing various methods for testing an API in this post.  This will include the usage of the AWS Distributed Load Testing tool.

Test Architecture

Below is the overall test architecture.  The left side represents various methods for System/QA type testing.  The right side represents a load testing option.



Web Services

Diagram below of the notional REST API system to be tested.  The scenario here is a service that tracks hit counts for web pages.


API Schema

Screen-shot of the OpenAPI schema created in Swagger's editor.




Server Snippet

A snippet of the 'create' service below.
//create
app.post('/page', (req, res) => {
    logger.debug('post request received');
    const pageId = req.body.pageId;
    if (pageId) {
        if (pageId in hitCounter) {
            res.status(400).json({error : 'page already exists'});
        }
        else {
            hitCounter[pageId] = 1;
            res.status(201).json({'pageId': pageId, 'hitCount': hitCounter[pageId]});
        }
    }
    else {
        res.status(400).json({error : 'missing pageId'});
    }
});


cURL Test Client

cURL 'create' command line and output below.
echo '***CREATE***'
curl -i -w "\n%{time_total} sec" -H "Content-Type: application/json" -d '{"pageId":"testpage"}' http://localhost:8888/page
echo '\n************\n'
***CREATE***
HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 34
ETag: W/"22-2+hqei/ocIIynyLdm2zE/SJrQ/Q"
Date: Sun, 13 Dec 2020 00:45:57 GMT
Connection: keep-alive

{"pageId":"testpage","hitCount":1}
0.024595 sec
************


Custom Test Client

Custom nodejs client for the same 'create' endpoint.

async function createTest(url, body) {
    console.log(`Create Test: ${url}, ${JSON.stringify(body)}`);

    const start = Date.now();
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {'Content-Type': 'application/json'}
    });
    const finish = Date.now();
    const respTime = finish - start;

    let result;
    try {
        result = JSON.stringify(await response.json());
    }
    catch (err) {
        result = err;
    }
    console.log(`Response status: ${response.status}`);
    console.log(`Response value: ${result}`);
    console.log(`Response time: ${respTime} ms`);
    console.log('****************');
}
Create Test: http://localhost:8888/page, {"pageId":"testpage"}
Response status: 201
Response value: {"pageId":"testpage","hitCount":1}
Response time: 39 ms
****************


Postman Test Client

This client can be automatically created by importing the OpenAPI 3.0 schema.




Load Testing

AWS has a pre-built architecture for generating load on REST clients here.  Screenshots of the build and execution of that tool.







Source


Copyright ©1993-2024 Joey E Whelan, All rights reserved.