Integration test with Flask Api

Jozimar Back
3 min readOct 17, 2021

Implementing integration tests on our Api is a good practice. If we test with integration tests instead manually, tests step can be speeded up and when we have to modify the system and retest the code it’s faster. In this post I want to show an example of implementing integration tests with Flask Api.

Photo by Mohammad Rahmani on Unsplash

The Flask Api

For this tutorial I made a simple Flask Api with person topic route. There are REST methods to interact with api and the data is stored in memory.

The code bellow creates and expose the routes for interaction with api.

The structure of the project is very similar to the following image.

Implementing Tests

To create integration tests you can use Flask-Testing. To install this package on project run pip on command line:

pip install Flask-Testing

In integration tests, you must have an instance from the web app to access the routes. To do it, with flask_testing package, you must create a class that inherit from TestCase. In the class body, define create_app method and return the flask aplication instance. Then, this class can be used on the class tests you want to build.

The implementation of the test can be made in a class that inherit from BaseClass. In this tutorial, to test the route /person/{id} with GET method, was built the method test_get_person_by_id. When calling api route we want to verify if it return status 200 and if the json returned for id 1 didn’t change since the creation of the app.

Running the test in the console you will receive a feedback with failure or success. In pycharm, is easier to run tests. Opening the class you have a run button that help you to run just a method or the entire class methods.

Using Flask-Testing you can build not just test for Api, but for web app too. And implement verifications on html templates, navigate from url’s and so on. From this point you can continue and implement your own tests.

The code of this tutorial is on my GitHub account and you can take a look. Thanks 😉

--

--

Jozimar Back

I write articles about my experience in Data Engineering.