Testing Flask Apps
6 min read Quiz at the end
Test Flask apps with pytest: fixtures for app, client, auth headers, and JSON assertions.
Testing Flask Applications
import pytest
from app import create_app, db
@pytest.fixture
def app():
app = create_app("testing")
with app.app_context():
db.create_all()
yield app
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def auth_headers(client):
# Login and return auth headers
resp = client.post("/api/auth/login", json={"email":"test@test.com","password":"pass"})
token = resp.get_json()["access_token"]
return {"Authorization": "Bearer " + token}
def test_get_users(client):
resp = client.get("/api/users")
assert resp.status_code == 200
assert "data" in resp.get_json()
def test_create_user(client, auth_headers):
resp = client.post("/api/users",
json={"name":"Alice","email":"alice@test.com"},
headers=auth_headers
)
assert resp.status_code == 201
assert resp.get_json()["email"] == "alice@test.com"
Topic Quiz · 2 questions
Test your understanding before moving on
1. How do you send a JSON POST in Flask tests?
💡 client.post(url, json=data) sends JSON with Content-Type: application/json.
2. How do you parse the JSON response in Flask tests?
💡 response.get_json() parses the response body as JSON.