Testing Flask with Pytest and Test Client
Checking routes one by one in a browser is manageable while an application has two pages. Once forms, login, a database, and an API arrive, manual testing can easily miss important cases. Automated tests record expected behavior as code and run it again whenever the application changes.
Flask provides a test client that sends requests directly to the application. The development server does not need to run, and no network port is opened. From the route’s perspective, the request still behaves like a normal one.
Install Pytest and Add Testing Config
Install pytest inside the project virtual environment:
# File: terminal
python -m pip install pytest
To let tests replace the database and other settings before extensions initialize, update the factory to accept an optional configuration dictionary:
# File: app.py
from flask import Flask
from models import db
from routes.api import api_bp
from routes.notes import notes_bp
def create_app(test_config=None):
app = Flask(__name__)
app.config.from_object("config.Config")
if test_config is not None:
app.config.update(test_config)
db.init_app(app)
app.register_blueprint(notes_bp)
app.register_blueprint(api_bp)
return app
The test configuration is applied before db.init_app(app), ensuring SQLAlchemy reads the test database URI rather than the development database.
Create App and Client Fixtures
Pytest fixtures prepare objects that several tests can reuse. The tmp_path fixture provides a separate temporary folder for a test run, keeping test data out of the development app.db.
# File: tests/conftest.py
import pytest
from app import create_app
from models import db
@pytest.fixture()
def app(tmp_path):
database_path = tmp_path / "test.db"
app = create_app({
"TESTING": True,
"SECRET_KEY": "test-secret",
"SQLALCHEMY_DATABASE_URI": f"sqlite:///{database_path}",
})
with app.app_context():
db.create_all()
yield app
with app.app_context():
db.session.remove()
db.drop_all()
@pytest.fixture()
def client(app):
return app.test_client()
The code before yield performs setup. After a test finishes, execution resumes to remove the session and drop the tables. This keeps tests repeatable without relying on leftover data from an earlier run.
The test folder now looks like this:
# File: test-structure.txt
tests/
├── conftest.py
├── test_pages.py
└── test_api.py
Pytest discovers fixtures in conftest.py automatically, so test files do not import client directly.
Start with an HTML Route
# File: tests/test_pages.py
def test_home_page_returns_success(client):
response = client.get("/")
assert response.status_code == 200
assert b"Hello, Flask!" in response.data
def test_unknown_page_returns_not_found(client):
response = client.get("/page-that-does-not-exist")
assert response.status_code == 404
The first assertion checks the status code. The second inspects the response body as bytes because response.data has not been decoded into a string. Use response.get_data(as_text=True) when text comparisons are more convenient.
The test name describes protected behavior rather than an implementation detail. If the route moves into a Blueprint but keeps the same response, the test does not need to change.
Test the JSON Endpoint
Passing json={...} automatically serializes the dictionary and adds the Content-Type: application/json header:
# File: tests/test_api.py
def test_create_note(client):
response = client.post("/api/notes", json={
"title": "Test the Flask API",
})
assert response.status_code == 201
assert response.get_json()["data"]["title"] == "Test the Flask API"
def test_create_note_rejects_empty_title(client):
response = client.post("/api/notes", json={"title": " "})
assert response.status_code == 422
body = response.get_json()
assert body["error"]["code"] == "validation_error"
def test_create_note_requires_json(client):
response = client.post("/api/notes", data="title=Note")
assert response.status_code == 415
These tests cover the happy path and two failures promised by the endpoint. Checking an error code is more meaningful than only confirming that the response body is non-empty.
Run and Read the Test Results
Run the full suite from the project root:
# File: terminal
python -m pytest -v
The -v option prints every test name. To run one file, use python -m pytest tests/test_api.py -v.
Good tests do not depend on one another. test_create_note_rejects_empty_title should pass when run alone or in a different order. Avoid using the real development database because a test can damage its data and become dependent on local state.
After these examples pass, add tests for form redirects, login-required routes, a missing note detail, and delete. Not every line needs a test, but the most important paths and likely failures should have protection.
Related Articles
Keep reading within the same topic.
Deploying Flask: Gunicorn, Environment, and Production Checklist
Prepare Flask for production with Gunicorn, environment variables, database migrations, static files, logging, health checks, and a release checklist.
Flask JSON APIs: Request Bodies, jsonify, and Status Codes
Build a Flask JSON API that reads request bodies, validates payloads, stores notes, and returns consistent responses and status codes.
Flask Authentication: Login, Sessions, and Logout
Build Flask authentication with password hashes, login sessions, a current user, protected routes, and logout without storing plaintext passwords.
Flask CRUD with SQLAlchemy: Create, Read, Update, Delete
Build Flask and SQLAlchemy CRUD to create, read, update, and delete notes with validation, forms, and redirects.