Globant
Published in

Globant

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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Carlos Villavicencio

Carlos Villavicencio

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