Flask · Lesson 10 of 15
Testing Flask Apps
pytest, the test client, app context and covering auth and JSON routes.
- Intermediate
- 16 min read
- 3 objectives
Before this lessonLesson 9: File Uploads and Static Media
What you will learn
- Write a fixture
- Post JSON
- Force a login in tests
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
The Flask test client lets you call views without a running server. Combine it with a factory that uses an in-memory database.
Fixtures
import pytest
from myapp import create_app
from myapp.extensions import db
from myapp.config import TestConfig
@pytest.fixture
def app():
app = create_app(TestConfig)
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()JSON and auth
def test_create_task(client):
r = client.post("/api/tasks", json={"title": "write tests"})
assert r.status_code == 201
assert r.get_json()["title"] == "write tests"
def test_private_requires_login(client):
assert client.get("/account").status_code in (302, 401)
def test_account_ok(client, app):
with app.app_context():
u = User(email="ada@example.com")
u.set_password("secret-secret")
db.session.add(u)
db.session.commit()
client.post("/login", data={"email": "ada@example.com", "password": "secret-secret"})
assert client.get("/account").status_code == 200