Enhance Flask App and API Testing with Pytest Unit Tests

Posted by


Unit testing is a crucial part of software development as it helps ensure that individual components of an application work as expected. In this tutorial, we will explore how to add unit tests to a Flask app and API using Pytest, a popular testing framework for Python.

Step 1: Setting Up a Flask App and API
First, let’s create a simple Flask app and API that we can test. Create a new directory for your project and navigate into it. Then, create a new Python file called app.py and add the following code:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(message='Hello, World!')

if __name__ == '__main__':
    app.run()

Save the file and run the Flask app by executing python app.py in your terminal. Open your web browser and navigate to http://127.0.0.1:5000/ to see the ‘Hello, World!’ message.

Step 2: Installing Pytest
Next, we need to install Pytest. Open your terminal and run pip install pytest to install the Pytest package.

Step 3: Writing Unit Tests
Now, let’s create a new directory called tests in your project directory. Inside the tests directory, create a new Python file called test_app.py. This file will contain our unit tests for the Flask app.

Add the following code to test_app.py:

import pytest

from app import app

@pytest.fixture
def client():
    with app.test_client() as client:
        yield client

def test_hello_world(client):
    response = client.get('/')
    assert response.status_code == 200
    assert response.json['message'] == 'Hello, World!'

In this test, we are using Pytest fixtures to create a test client for the Flask app and then making a request to the root route (‘/’) to check if the response status code is 200 and the response message is ‘Hello, World!’.

Step 4: Running the Unit Tests
To run the unit tests, navigate to your project directory in the terminal and run pytest. Pytest will automatically discover your test files and execute the unit tests. If everything is working correctly, you should see an output indicating that the test passed.

Step 5: Adding More Unit Tests
You can add more unit tests to test_app.py to test different routes and functionalities of your Flask app. Here’s an example of adding a test for a new route /about:

def test_about(client):
    response = client.get('/about')
    assert response.status_code == 200
    assert 'about' in response.json['message'].lower()

Step 6: Test Organization
It’s a good practice to organize your tests into multiple test files based on different functionalities of your Flask app. You can create new test files in the tests directory and use Pytest fixtures to share common resources across test files.

Step 7: Continuous Integration
To ensure that your unit tests are always run before deploying your Flask app, you can set up a continuous integration (CI) pipeline using tools like GitHub Actions, Travis CI, or Jenkins. This will automatically run your unit tests whenever there is a new commit to your repository.

Congratulations! You have successfully added unit tests to your Flask app and API using Pytest. By writing and running unit tests, you can ensure the reliability and functionality of your application as it evolves and grows. Happy testing!

0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@stevenpillay6725
1 month ago

Thanks man!

@alexanderantonio5239
1 month ago

i have a question if I am working on a project with multiple people can i have a requirements.txt file to where each person can have access to the project/edit the project. I am using ./env/Scripts/activate for env

@edboss36
1 month ago

thanks

@lynx-feeder281
1 month ago

really great video, Vincent, thanks!

@mohammedmoosasharieff1816
1 month ago

This is exactly what I needed. Thank you Vincent 🙂