How to add a basic unit test to a Python Flask app using Pytest

Carlos V.
Globant
Published in
2 min readJul 21, 2022

Are we all agree that we need to add some tests to our apps, right? If you are not convinced, please check out this post about unit tests and refactoring. In this small post, we will show you how to add a single test to a pretty basic Flask application using Pytest.

BONUS: we will also show you how to add Github Actions CI to your repo.

Let’s say we have a simple hello world response in our home (/) route, just like:

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index():
return jsonify({'hello': 'world'})


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

So let’s begin by creating a tests directory and the conftest.py file with the following content:

import pytestfrom app import app as flask_app
@pytest.fixture
def app():
yield flask_app
@pytest.fixture
def client(app):
return app.test_client()

This file will initialize our Flask app and all fixtures you need.

Now, Pytest will discover all your test files, let’s create some test files with test_ prefix in the same directory. In this case, we will test that the route responds with the expected hello world dict.

import json
def test_index(app, client):
res = client.get('/')
assert res.status_code == 200
expected = {'hello': 'world'}
assert expected == json.loads(res.get_data(as_text=True))

And that’s it! Now you can run the tests with this line:

python -m pytest

The reason why the above command looks atypical to you is that we need to add the directory to the current sys.path.

BONUS

To setup GitHub actions and get your precious badge for your readme file, you just need to add the following tasks to your YAML file

- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run Tests
run: |
python -m pytest

You can see the complete YAML file in this sample repo if you want to use it as a reference for your app.

We hope this small tutorial can be useful when you bootstrap a new project or just add tests to an existing application.

--

--

Carlos V.
Globant
Writer for

Software Engineer at Globant | Community Leader | Writer & Speaker | he/him.