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()andtest_cli_runner()- Isolated DB per test
TESTING=True
More most-asked Flask questions
- How do you access request data and build responses in Flask?
- How do Flask sessions work and what are their security implications?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?