2019-02-02

API/REST testing like Chuck Norris with pytest play using YAML


In this article we will see how to write HTTP API tests with pytest using YAML files thanks to pytest-play >= 2.0.0 (pytest-play provides support for Selenium, MQTT, SQL and more. See third party pytest-play plugins).

The guest star is Chuck Norris thanks to the public JSON endpoint available at https://api.chucknorris.io/ so you will be able to run your test by your own following this example.

Obviously this is a joke because Chuck Norris cannot fail so tests are not needed.

Prerequisites and installation

Installation is not needed, the only prerequisite is Docker thanks to https://hub.docker.com/r/davidemoro/pytest-play.

Inside the above link you'll find the instructions needed for installing Docker for any platform.

If you want to run this example without docker install pytest-play with the external plugin play_requests based on the fantastic requests library (play_requests is already included in docker container).

Project structure

You need:
  • a folder (e.g., chuck-norris-api-test)
  • one or more test_XXX.yml files containing your steps (test_ and .yml extension matter)
For example:

As you can see each scenario will be repeated for any item you provide in test_data structure.

The first example asserts that the categories list contains some values against this endpoint https://api.chucknorris.io/jokes/categories; the second example shows how to search for category (probably Chuck Norris will find you according to this Chuck Norris fact "You don't find Chuck Norris, Chuck Norris finds you!")

Alternatively you can checkout this folder:
 Documentation and options:

Usage

Visit the project folder and run the following command line command:

docker run --rm -v $(pwd):/src davidemoro/pytest-play


You can append extra standard pytest variables like -x, --pdb and so on. See  https://docs.pytest.org/en/latest/

Homeworks

It's time to show off with a GET roundhouse kick! Ping me on twitter @davidemoro sharing your pytest-play implementation against the random Chuck Norris fact generator by category!

GET https://api.chucknorris.io/jokes/random?category=dev
{
    "category": ["dev"],
    "icon_url": "https:\/\/assets.chucknorris.host\/img\/avatar\/chuck-norris.png",
    "id": "yrvjrpx3t4qxqmowpyvxbq",
    "url": "https:\/\/api.chucknorris.io\/jokes\/yrvjrpx3t4qxqmowpyvxbq",
    "value": "Chuck Norris protocol design method has no status, requests or responses, only commands."
}

Do you like pytest-play?

Let's get in touch for any suggestion, contribution or comments. Contributions will be very appreciated too!
Star

No comments:

Post a Comment

Note: only a member of this blog may post a comment.