DEV Community

Carlos Villavicencio
Carlos Villavicencio

Posted on • Updated on

How to add 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? 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__)


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


if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

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

import pytest

from app import app as flask_app


@pytest.fixture
def app():
    yield flask_app


@pytest.fixture
def client(app):
    return app.test_client()
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

And that's it. Now you can run the tests with this line:

python -m pytest
Enter fullscreen mode Exit fullscreen mode

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.

BONUS

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
Enter fullscreen mode Exit fullscreen mode

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.

Setup

Create and activate the virtual environment

virtualenv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Run the server

python app.py
Enter fullscreen mode Exit fullscreen mode

Run the tests

python -m pytest
Enter fullscreen mode Exit fullscreen mode

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

Requirements

Python >= 3.6

License

MIT

Discussion (2)

Collapse
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
Enter fullscreen mode Exit fullscreen mode

instead of

import pytest
Enter fullscreen mode Exit fullscreen mode
Collapse
po5i profile image
Carlos Villavicencio Author

Good catch! Fixed.

Thank you.