0
0
Flaskframework~5 mins

Coverage reporting in Flask

Choose your learning style9 modes available
Introduction

Coverage reporting helps you see which parts of your Flask app's code are tested. It shows what is covered by tests and what is not.

You want to check if your Flask app has enough tests.
You want to find untested parts of your code to improve quality.
You want to measure test progress during development.
You want to ensure critical routes and functions are tested before release.
Syntax
Flask
coverage run -m pytest
coverage report
coverage html

coverage run -m pytest runs tests while tracking coverage.

coverage report shows coverage summary in the terminal.

coverage html creates a detailed HTML report you can open in a browser.

Examples
Run your Flask tests with coverage tracking.
Flask
coverage run -m pytest
See a summary of which files and lines were tested.
Flask
coverage report
Generate a detailed HTML report to view coverage visually.
Flask
coverage html
Sample Program

This Flask app has two routes: '/' and '/about'. The test only checks the '/' route. Running coverage will show that '/about' is not tested.

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, world!'

@app.route('/about')
def about():
    return 'About page'

# test_app.py
import pytest

from app import app

@pytest.fixture
def client():
    with app.test_client() as client:
        yield client

def test_home(client):
    response = client.get('/')
    assert response.data == b'Hello, world!'

# Run coverage commands in terminal:
# coverage run -m pytest
# coverage report
# coverage html
OutputSuccess
Important Notes

Make sure to install coverage with pip install coverage.

Run coverage commands from your project root where your Flask app and tests are.

Use the HTML report to easily see which lines are missing tests.

Summary

Coverage reporting shows which parts of your Flask app are tested.

Use coverage run -m pytest to run tests with coverage.

Check results with coverage report or coverage html.