DEV Community


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

po5i profile image Carlos Villavicencio Updated on ・2 min read

Are we all agree that we need to add some tests to our apps, right? In this small post, I'll show you how to add test to a pretty basic Flask app using Pytest. BONUS: I'll show you how to add Github Actions CI to your repo.

Let's say we have a simple "hello world" response in our / route, just like:

from flask import Flask, jsonify

app = Flask(__name__)

def index():
    return jsonify({'hello': 'world'})

if __name__ == '__main__':

So let's begin by creating a tests directory and there the file:

import pytest

from app import app as flask_app

def app():
    yield flask_app

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 I'll test that the route responds with my 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 command looks like the above instead of just pytest is becase we need to add the directory to the current sys.path.


To setup github actions and get your precious badge for your readme file, you just need to add the following tasks to you 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 my sample repo if you want to use it as reference for your app:

Mini example of Flask and Pytest

Actions Workflow

This is a examle repository for my article.


Create and activate the virtual environment

virtualenv venv
source venv/bin/activate

Run the server


Run the tests

python -m pytest

The server will be up on http://localhost:5000.


Python >= 3.6



Discussion (2)

Editor guide
jsalvador profile image
Juanjo Salvador

Nice! I have a lot of experience coding Python but not the same for testing (unit, functional o integration) with Flask. It's cool to see this.

You have a typo on the second codeblock

mport pytest

instead of

import pytest
po5i profile image
Carlos Villavicencio Author

Good catch! Fixed.

Thank you.