Demonstrating and unit testing the RESTful services

For proper unit testing, we want a more formal exchange between a client and a server. The Flask framework provides test_client(), which gives us the features required to make requests of a Flask server to be sure that the responses are correct. Once a test client object has been created, we can make our get, post, put, patch, and delete requests to confirm that a function behaves correctly. 

The doctest module will locate Python examples inside document strings for a module or function. This makes it easy to include examples inside the definition of the relevant function. Here's an example of using the doctest features to test a Flask module:

@app.route("/openapi.json")
def openapi() -> Dict[str, Any]:
"""
>>> client = app.test_client()
>>> response = client.get("/openapi.json")
>>> response.get_json()['openapi']
'3.0.0'
>>> response.get_json()['info']['title']
'Chapter 13. Example 2'
"""
return jsonify(OPENAPI_SPEC)

This test code uses app.test_client() to create a client. Then, client.get() is used to execute a GET request to the /openapi.json path. The results can be examined to be sure that an Open API specification document really will be provided by the defined route. This test case depends on the value of app being the Flask application module. This is usually true, because this code is in the same module where the app object is defined.

There are a variety of approaches to packaging unit tests:

  • In a separate tests package: This will contain a number of test modules. If the filenames all begin with test_, then tools such as pytest can locate and execute these tests. This is appropriate when tests are relatively complex. This often happens when mock objects must be provided.
  • In module and function docstrings: This is the technique that was shown previously. The doctest tool can locate examples within docstrings and execute these tests. The doctest module can also locate tests as the values of a global __test__ dictionary. This is appropriate when the tests are relatively simple and the setup for each test is easily accomplished through application configuration.

The preceding test can be executed from the command line by using a command such as the following:

$ python3 -m doctest ch13_ex2.py

This command runs the doctest module. The command-line argument is the module to be examined. All Python examples marked with >>> will be executed to confirm that the function operates properly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset