Flask & Deployment
Topic 7 · APIs and models · ⏱ about 3 h

Testing, Configuration & Logging

Test Flask apps with pytest and the test client, keep secrets and settings in environment variables, write useful logs, and run your tests automatically on every push with GitHub Actions.

Show:
In this topic
Beginner

Why test a web app?

Every change can break something you were not looking at. Automated tests let you change code with confidence, and they are what makes it safe to deploy often. Flask's test client sends fake requests to your app without starting a server, so tests are fast. Write tests with pytest (see developer tools).

Beginner

Code: testing with pytest

Save as tests/test_app.py next to an app built with an app factory, then run pytest.

Python (tests/test_app.py)
import pytest
from app import create_app, db

@pytest.fixture
def client():
    app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:"})
    with app.app_context():
        db.create_all()
    return app.test_client()

def test_health(client):
    r = client.get("/health")
    assert r.status_code == 200
    assert r.get_json()["status"] == "ok"

def test_create_and_read_patient(client):
    r = client.post("/api/v1/patients", json={"name": "Sita", "suburb": "Kangaroo Point"})
    assert r.status_code == 201
    pid = r.get_json()["id"]
    assert client.get(f"/api/v1/patients/{pid}").get_json()["name"] == "Sita"

def test_missing_name_is_rejected(client):
    r = client.post("/api/v1/patients", json={"suburb": "Toowong"})
    assert r.status_code == 422

def test_unknown_patient_is_404(client):
    assert client.get("/api/v1/patients/999").status_code == 404
Open in playground ↗
Beginner

What to test

  • Happy paths: the main features work (create, read, predict).
  • Bad input: missing fields, wrong types, huge requests get 4xx, never 500.
  • Permissions: logged-out users get 401; users cannot see each other's data.
  • The model: a few fixed inputs give the expected predictions (within a tolerance), so a retrained or broken model is noticed before release.

Keep tests independent: each one gets a fresh app and an empty test database from the fixture.

Beginner

Configuration and secrets

Follow the twelve-factor rule: configuration lives in the environment, not in the code. The same code runs on your laptop, in tests and in production; only environment variables differ.

import os app.config["SECRET_KEY"] = os.environ["SECRET_KEY"] # fails loudly if missing app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///dev.db") # or load every FLASK_* variable at once: app.config.from_prefixed_env()

For local development, keep variables in a .env file (loaded by the python-dotenv package) and add .env to .gitignore. Never commit secrets to Git; if one leaks, revoke and replace it immediately, because Git history keeps it forever.

Beginner

Logging

On a server nobody watches the terminal. Logs are how you find out what happened. Use app.logger or Python's logging module (not print), with levels (DEBUG, INFO, WARNING, ERROR), and log the request, the outcome and the time taken. Do not log passwords, tokens or unnecessary personal data. Many teams log in JSON so that log tools can search and chart them.

Beginner

Continuous integration with GitHub Actions

CI runs your tests automatically on every push and pull request, so broken code never reaches the main branch. Save this as .github/workflows/tests.yml in your repository:

name: tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - run: pip install -r requirements.txt pytest - run: pytest -q

A green tick on every commit is also a strong signal in a portfolio. Adding a deployment step after the tests gives you continuous deployment (CD).

Check yourself

Quiz

1. What does Flask's test client do?

2. Where should the production database password live?

3. A request with a missing field makes your API return 500. What should a test expect instead?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready