REST API testing

Note
For this tutorial we will assume you are running Windows, but the steps are almost identical for macOS or Linux.
  1. If you haven’t done it already, please follow the instructions in the installation page, including the quick start section to install OpenTest and create the default configuration files.

    You should now have the following directory structure (we will assume you created the opentest directory in the root of the C: drive; if your path differs, please adjust the commands in the following steps accordingly):

    C:\opentest
    ├── server
    │   └── server.yaml
    ├── actor1
    │   └── actor.yaml
    └── test-repo
        └── ...
  2. Type the following two commands in two separate console windows to start the OpenTest server and actor:

    opentest server C:\opentest\server
    opentest actor C:\opentest\actor1
  3. Open the server’s web UI at http://localhost:3000.

  4. From the menu, select Session > Create Test Session. Select the test named GitHub API test and click Create session. Wait a few seconds for the test to complete. Refresh your browser to view the result of the test session.

The test we just ran consists of two test actions:

  • The first action calls the /repos/facebook/react/branches API on api.github.com and saves the body of the response into a data property in the local data store (the local data store is where you save the data you need to share between test actions).

  • The second test action reads the data from the local data store and validates it by making sure that:

    • some payload was returned;

    • the response payload is an array with at least one element (we’re not being very thorough, just checking that the length property is greater than 0).

Here’s the full source of the test:

test-repo-path/tests/api/GitHub API test.yaml
description: Get repo branches from the GitHub API
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: Call the GET /repos/:owner/:repo/branches API
            action: org.getopentest.actions.HttpRequest
            args:
              url: https://api.github.com/repos/facebook/react/branches
              verb: GET

          - description: Verify that the branches array exists and is not empty
            script: |
              var branches = $output.body;

              if (!branches || branches.length == 0) {
                  $fail("Response body invalid or contains no branch elements.");
              } else {
                  $log($format(
                    "The GitHub API returned {0} branches",
                    branches.length));
              }

API tests are usually much easier to build that UI tests. The formula you’re going to apply over and over (with small variations) is:

  1. Call an API using the the HttpRequest keyword and save the statusCode and/or body output values into a variable.

  2. Add one or more script actions to validate the response payload and/or status code.

Here’s one more example of an API test. This one calls the JSONPlaceholder fake REST API:

description: Creates a new BLOG post and validates the response
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: Create a random post ID
            script: var postId = $random(1000, 99999);

          - description: Send a request to create a new blog post
            action: org.getopentest.actions.HttpRequest
            args:
              url: https://jsonplaceholder.typicode.com/posts
              headers:
                Content-Type: application/json
              verb: POST
              body: |
                $json(
                  {
                    id: postId,
                    title: "My fist post"
                  }
                )

          - description: Save the response payload into a variable
            script: |
              var statusCode = $output.statusCode;
              var postInfo = $output.body;

          - description: Validate the response status code
            script: |
              if (statusCode != 201) {
                $fail($format(
                  "We expected the status code to be {0} but it was {1}",
                  201,
                  statusCode));
              }

          - description: Validate the post ID
            script: |
              if (postInfo.id != postId) {
                $fail($format(
                  "We expected the post ID to be {0} but it was {1}",
                  postId,
                  postInfo.id));
              }

          - description: Validate the post title
            script: |
              if (postInfo.title != "My fist post") {
                $fail($format(
                  "We expected the post title to be '{0}' but it was '{1}'",
                  "My fist post",
                  postInfo.title));
              }

What next?

  • Let’s create and run your first API test. Create a new file named My API test.yaml in the tests directory of the test repo, then copy & paste in it the full contents of this last test we looked at. In the server UI, create a new test session to run the test named My API test. When the test is finished, click on the test session link in the UI to examine the test results and look at the session log to understand the type of information available to you for troubleshooting. For extra points, modify one of the validation steps so that the test fails. Then look at the log again, to understand how the error information is displayed.

  • Look over the documentation for the HttpRequest action to get a general idea of its arguments and capabilities.

  • Create an issue on GitHub and ask a silly question. We don’t care, we answer all of them.