Flask interview question · Most asked

How do you test a Flask application?

Summary

Create the app via the factory with a testing config in a pytest fixture, use app.test_client() to make requests, app.test_cli_runner() for CLI commands, and set up an isolated database per test.

Longer Answer

TESTING = True propagates exceptions to the test. Use with client: to keep the request context for inspecting session or g after a request. For DBs, create tables in a temporary SQLite DB or run each test in a rolled-back transaction against Postgres.

Code Example

import pytest
from myapp import create_app
from myapp.extensions import db

@pytest.fixture
def app():
    app = create_app("myapp.config.TestConfig")
    with app.app_context():
        db.create_all()
        yield app
        db.drop_all()

@pytest.fixture
def client(app):
    return app.test_client()

def test_create_item(client):
    r = client.post("/items", json={"name": "Pen"})
    assert r.status_code == 201
    assert r.get_json()["name"] == "Pen"

Key Points

  • Factory + test config fixture
  • test_client() and test_cli_runner()
  • Isolated DB per test
  • TESTING=True

More most-asked Flask questions

← All Flask questions