Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 72 ยท Testing, Quality and Production

Testing Flask Apps with pytest

Test Flask applications with pytest. Learn test_client, fixtures for the app factory and a test database, sessions, JSON, redirects, CLI commands and parametrize.

Every Flask example in this tutorial has used app.test_client() to prove that it works. That client is also the foundation of real test suites: it calls your app in the same process, without a network, a server or a browser, so tests are fast and deterministic. A suite that runs in a few seconds is a suite people actually run.

In this lesson you will learn the pieces of a professional Flask test setup: fixtures that build a fresh app and a fresh database for every test, the test client's API (JSON, redirects, cookies, sessions), testing command-line commands, and how pytest ties it together. A browser page cannot run the pytest program itself (it discovers files on disk), so the runnable examples use plain functions and a tiny runner that works like pytest's fixture system. The commands and files for a real project are shown read-only, and they behave identically.

The shape of a test

Every test follows the same three steps: arrange (build the app, the data), act (make a request), assert (check the response and the new state).

flowchart LR
    F["fixture: create_app(test config)"] --> A["fixture: client"]
    A --> T["test: client.post(...)"]
    T --> S["assert on response<br/>and on the database"]
    S --> D["teardown: close and discard the app"]

Each test gets its own app and in-memory database, so no test can break another.

Tests in pytest are plain functions named test_* that use plain assert. There are no self.assertEqual methods to remember. When an assert fails, pytest rewrites it to show both sides of the comparison.

Python Plain test functions and the test client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Useful members of the response object in tests: status_code, data (bytes), get_data(as_text=True), get_json(), headers, location and content_type. Bytes in response.data need a b"..." literal on the right.

Fixtures: a fresh app for every test

The global app above is fine for a demo, but a real project uses the application factory from The Application Factory. A test can then build a new app with test settings every time: TESTING=True (exceptions propagate instead of becoming 500 pages), an in-memory database, and a fixed secret key.

pytest gives you fixtures for this: functions decorated with @pytest.fixture whose return value is injected into every test that names the fixture as a parameter. A fixture that uses yield runs the code after the yield as teardown. Fixtures can depend on other fixtures the same way (the client fixture asks for app).

Here are the files of a real project (read-only; conftest.py is a special file pytest loads automatically, so its fixtures are available to every test):

Python
# conftest.py
import pytest
from myapp import create_app, db


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


@pytest.fixture
def client(app):
    return app.test_client()
Python
# tests/test_notes.py
def test_create_note(client):
    response = client.post("/api/notes", json={"text": "hello"})
    assert response.status_code == 201


def test_list_starts_empty(client):
    assert client.get("/api/notes").get_json() == []

You run them with pytest (or pytest -q for terse output, pytest tests/test_notes.py::test_create_note for one test, pytest -k create to select by name, pytest -x to stop at the first failure).

To see how this works under the hood, the next example implements a tiny fixture system (about twenty lines) and runs a real Flask app with a real SQLite database through it. It is not a replacement for pytest; it is the same idea made visible.

Python A mini fixture runner: fresh app and database per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the structure. run looks at the parameter names of each test (client), finds the fixture of that name, builds its dependencies first (app), and runs the teardown after the test, even when it fails. This is exactly why test_each_test_has_its_own_database passes: the app fixture is rebuilt for every test, so the earlier test's note is gone. The last test fails on purpose to show the failure format; real pytest would print a detailed comparison.

More of the test client

The client keeps cookies between requests like a browser, which makes login flows testable. Three other tools you will use all the time:

  • client.session_transaction() lets you read or set the session directly, so a test can start already logged in without going through the login form.
  • app.test_request_context() and app.app_context() give you url_for, current_app and g outside a request.
  • app.test_cli_runner() invokes your @app.cli.command() functions and captures their output.
Python Sessions, exceptions and CLI commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Parametrized tests and monkeypatching

Two pytest features remove most repetition. @pytest.mark.parametrize runs one test body for many inputs (each case is reported separately). The built-in monkeypatch fixture temporarily replaces an attribute or environment variable and puts it back after the test. Both are read-only here, because they belong to the pytest program:

Python
import pytest


@pytest.mark.parametrize("payload, expected_status", [
    ({"text": "ok"}, 201),
    ({"text": ""}, 400),
    ({}, 400),
    ({"text": "x" * 500}, 422),
])
def test_create_validates_input(client, payload, expected_status):
    assert client.post("/api/notes", json=payload).status_code == expected_status


def test_sends_welcome_email(client, monkeypatch):
    sent = []
    monkeypatch.setattr("myapp.mail.send", lambda to, body: sent.append(to))
    client.post("/register", data={"email": "[email protected]"})
    assert sent == ["[email protected]"]

The second test shows the golden rule of testing external effects: never send real email, call real payment APIs or hit the network in tests. Replace the function that does it and assert it was called. Hooks, Application Context and g shows where such seams live.

The same parametrize idea works without pytest. This runnable version loops over cases, which is how the idea looks stripped to its core:

Python The idea behind parametrize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What to test, and how much

  • Every route gets at least a happy-path test and a failure test (bad input, missing login, 404).
  • Test behaviour through the HTTP interface (status, body, headers, database effects), not private functions. Such tests survive refactoring.
  • Test the rules that cost you money or trust: permissions (Roles and Permissions), validation, calculations.
  • Keep tests independent and in any order. If a test needs data, it creates it, usually through a fixture.
  • Use TESTING=True, an in-memory or temporary database, and fixed secrets. Never point tests at a development or production database.
  • Measure coverage with pytest --cov=myapp (plugin pytest-cov), but treat the number as a hint about untested corners, not a goal.
  • Run the suite in continuous integration on every push, so a broken change is caught before it is deployed (Deployment).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does pytest decide which fixture to pass to a test function?

    Writing def test_x(client): asks pytest for the fixture called client. Fixtures can ask for other fixtures the same way.
  2. 2. What does TESTING = True change in a Flask app?

    With TESTING on, an unhandled exception reaches the test client call so the test fails with a clear traceback. It does not switch databases for you; your test config does that.
  3. 3. What is the purpose of the code after the yield in a fixture?

    Everything before yield is setup, the yielded value is given to the test, and the code after yield is cleanup.
  4. 4. Why should each test get its own app and in-memory database?

    Independent tests are reliable tests. Shared state makes failures depend on test order and is very hard to debug.
  5. 5. A view sends a welcome email on registration. What is the right way to test it?

    Tests must not have real side effects. Swap the sender for a fake and check how it was called.

Summary

  • app.test_client() calls your app in-process; use json=, data=, headers=, follow_redirects=True and read status_code, get_json() and data.
  • Build the app with a factory and test settings (TESTING=True, in-memory database, fixed secret key) inside a fixture; make a client fixture from it.
  • Fixtures are injected by parameter name; code after yield is teardown; conftest.py shares fixtures across files.
  • session_transaction(), test_request_context() and test_cli_runner() cover sessions, url_for and CLI commands.
  • @pytest.mark.parametrize repeats a test for many cases; monkeypatch replaces slow or dangerous dependencies.
  • Test behaviour through HTTP, keep tests independent, run them in CI.

Next, learn what to do when something goes wrong in production: Logging and Debugging.