API testing with DevWeb

Your DevWeb scripts can be used for API performance testing. To shorten scripting time, you can use the DevWeb Offline Script Generator to convert Swagger API documentation into JavaScript functions, providing a format that is easy to read and maintain. The generated functions can be called from DevWeb scripts.

Note:  

About API functions with DevWeb scripts

Swagger is an open specification used to describe and document RESTful APIs.

To enable API testing with DevWeb scripts, LoadRunner Developer provides a method to convert the API calls in Swagger definition files (swagger.json format) into functions that can be called from DevWeb tests.

This functionality is supported with Swagger Specification 2.0.

Using Swagger mode to generate swaggerApi.js

You use the Offline Generator in Swagger mode to generate the required files. When you add the path or URL for a swagger.json file as an argument to the Offline Generator, the resulting output is a JavaScript file, swaggerApi.js, containing auto-generated JavaScript functions.

Note: Swagger mode also generates (or regenerates) a main.js file, but without the API function calls inside.

Each function includes parameters, and represents an API call in the Swagger definition file. The function can connect with the server to execute the operation described by the API call.

After generating the swaggerApi.js, you can import the file to the folder for a DevWeb script. From the script, you can then call the function you want to test, using the required parameters. Implementation is inside the swaggerApi.js. When the function is called, it generates an API call on the application, and returns a web request.

Using Swagger mode with a HAR file

Your swagger.json may be very large, with hundreds of operations, and you may not want to test them all. Instead, you have the option to directly generate a DevWeb script based on a HAR file, containing just the relevant operations. This is the recommended way to create your API test script; it is quicker and easier than editing a script manually to call the functions.

When you add the HAR path (and the swagger.json path or URL) to the arguments for the Offline Generator using Swagger mode, the tool generates a main.js file containing the relevant function calls, in addition to creating the swaggerApi.js file.

The creation of each function call in the main.js is based on the Offline Generator finding a single, unique match between the HAR entry and the generated JavaScript function in the swaggerApi.js. If there is a match, it creates a function call for that function. If a match is not found, or there are multiple matches, it generates a regular DevWeb WebRequest send call.

Back to top

Example

A pet store application is described using the pet_swagger.json file. The JSON contains various different operations for the pet store.

pet_swagger.json file:

The JSON section below defines an API operation for adding a pet to the store, with operationID "addPet". It should be called via a POST request with an argument in its body. The parameter name is "body".

"/pet": {
            "post": {
                "tags": [
                    "pet"
                ],
                "summary": "Add a new pet to the store",
                "description": "",
                "operationId": "addPet",
                "consumes": [
                    "application/json"
                ],
                "produces": [
                    "application/json",
                    "application/xml"
                ],
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "Pet object that needs to be added to the store",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/Pet"
                        }
                    }
                ],
                "responses": {
                    "405": {
                        "description": "Invalid input"
                    }
                },

swaggerApi.js file:

When the Offline Generator generates the swaggerApi.js file, it contains the corresponding generated function for addPet. It has a parameter named body, as used in the JSON file, and the parameter description from the JSON file.

The function creates a WebRequest to call the API, and returns the request. In the body, the function used the parameter.

main.js file:

When the Offline Generator generates the main.js file, it contains a call to the addPet function in the swaggerApi.js, using the value taken from the HAR file. The function uses the returned WebRequest and sends it. The return value of the send is a WebResponse, which is assigned to a variable.

Tip: The <DevWeb root folder>\examples\ folder includes the following API testing example scripts:

  • APITestingPetStore
  • APITestingAdvantageOnlineShopping

Back to top

Parameters

  • Swagger describes several locations of function parameters: Path, Headers, Query, Form Data, and Body.

    The generated function accepts the parameters defined for the operation in the swagger file, and used in the function body, inside the generated WebRequest. For example, Path parameters are used in the WebRequest URL, Query parameters are used in the WebRequest query.

  • A parameter has a required property in its schema which can be equal to true or false. All parameters are generated, whether required or not. The Offline Generator ignores this property.
  • The functions getSchema and getHost (that return the Schema and Host parameters respectively) are used in the WebRequest URL.
  • If the swagger.json is missing the Host property, the generated getHost function returns an empty string, and the script will fail with an error. To avoid this, the main.js file includes an override option for getHost, to prompt you to add your host name:

Back to top

Correlations for API testing functions

The API functions calls may include correlation extractors and appliers, where relevant. When the record scan and rules scan are enabled and find correlation values, the values are added to the generated API function calls.

Extractors

When generating API function calls, the relevant extractors (defined by the correlation record or rule scan) are automatically generated in the main.js file.

Example:

let webRequest1 = swaggerApi.createSomething("1001", "1002", `{
          "data": [{
                  "description": "DevWeb API test1",
                  "name": "Created by Some User"
              },
      		{
                  "description": "DevWeb API test2",
                  "name": "Created by Some User"
              }
          ],
          "exceeds_total_count": false,
          "total_count": 2
      }
      `);
    webRequest1.extractors = [
        // Source='Rule' Original value="2001"
        new load.BoundaryExtractor("test1", {
                leftBoundary: "[{\"type\":\"test\",\"id\":\"",
                rightBoundary: "\"},{\"type\":\"test\",\"id\":\"2002"
            }), 
        // Source='Rule' Original value="2002"
        new load.BoundaryExtractor("test2", {
                leftBoundary: ",{\"type\":\"test\",\"id\":\"",
                rightBoundary: "\"}],\"exceeds_total_count"
            }), 
    ]
    const webResponse1 = await webRequest1.send();

Appliers for values exposed in the script

For the API function call parameters that are exposed, where you see the values in the main.js, the applier simply replaces the correlated value.

Example:

A function call has a parameter requiring a correlated value for an API key. This was extracted from an earlier web response:

let webRequest = swaggerApi.deletePet(`API_KEY_11122FFFFF`, "123");

After a record scan or rule scan, it becomes:

let webRequest = swaggerApi.deletePet(`${earlierResponse.extractors['api_key']}`, "123");

Appliers for attributes not exposed in the script

When generating API function calls, there are web request attributes that do not appear in the parameters, and are therefore not exposed in the main.js. For example, some headers or query strings.

If these attributes have values that need to be correlated, they are accessed directly by the record or record scan, and generated in the main.js like an assignment, using the request name. The appropriate applier is then applied to the appropriate field.

Example:

 let webRequest4 = swaggerApi.addPet(`{
        "id": 10,
        "authCookie": "${webResponse2.extractors['authCookie']}",
        "category": {
          "id": 0,
          "name": "string"
        },
        "name": "Dog",
        "photoUrls": [
          "string"
        ],
        "tags": [
          {
            "id": 0,
            "name": "string"
          }
        ],
        "status": "available"
      }`);
    webRequest4.headers["my_session"] = `${webResponse2.extractors['SessionId']}`
    webRequest4.queryString["authCookie"] = `${webResponse2.extractors['authCookie']}`
    const webResponse4 = await webRequest4.send();

Back to top

Generate files from Swagger definitions

The following steps describe how to generate swaggerApi.js and main.js files using Swagger mode.

To generate files from Swagger:

Prerequisite: A swagger.json file created with Swagger Specification 2.0

  1. If you want to generate a DevWeb script for specific API operations in Swagger, record and create a HAR file (refer to Using Swagger mode with a HAR file, above). Record while invoking the API calls you want to test.

    Use the Proxy Recorder or another recording method - for details, see Record and generate a DevWeb script.

  2. Run the Offline Script Generator from the command line or from your IDE, with the relevant argument.

    To generate the swaggerApi.js (plus main.js without the API function calls):

    OfflineGenerator.exe –mode=swagger <swagger.json path> <script directory path>

    To generate the swaggerApi.js, without regenerating the main.js file:

    OfflineGenerator.exe -mode=swagger -generateScript=false <swagger.json path> <script directory path>

    To generate swaggerApi.js and main.js using HAR file (generated in step 1 above):

    OfflineGenerator.exe –mode=swagger -level=pages -har=<path to har file> <swagger.json path> <script directory path>

    The key values are as follows:

    -mode The mode type (swagger), to indicate the format of the source definition file.
    -generateScript=false

    When the flag is defined as false, it instructs DevWeb to regenerate the API functions for the swaggerApi.js, without regenerating the main.js. This is useful if you do not want to overwrite manual edits in the main.js.

    • This is relevant for simple swagger mode only (when generating functions from the JSON file, without a HAR file).
    • If a main.js does not exist (for example, when generating swaggerApi.js for the first time), then a main.js file is generated.

    -level (Optional)

    The script level to generate: a url-based script, or pages with a resource-based script.

    Value: url (default) or pages

    -har (Optional)

    The path to the recorded HAR file from which to generate the main.js file for the script.

    <swagger.json path> The full path or URL for the source swagger.json file.
    <script directory path> The full path to the directory in which to save the generated files.

    Example:

    OfflineGenerator.exe -mode=swagger -level=pages -har=..\ScriptFolder\swagger_pet_store\mypc.ny.net.har http://mypc.ny.net:8080/v2/swagger.json ..\ScriptFolder\swagger_pet_store

    For more information on using the Offline Generator, see DevWeb Offline Script Generator tool.

Back to top

See also: