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)
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()
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.
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
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
This is a examle repository for my article.
Setup
Create and activate the virtual environment
virtualenv venv
source venv/bin/activate
Run the server
python app.py
Run the tests
python -m pytest
The server will be up on http://localhost:5000.
Requirements
Python >= 3.6
License
Update: Also crossposted on Globant's Medium.
Top comments (3)
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
instead of
Good catch! Fixed.
Thank you.
I am getting
not tests ran, despite having tests written and code working.