Flask 官方测试文档到 2026-03-28 仍然非常稳定,核心工具就是:
app.test_client()app.test_cli_runner()
一个典型的 pytest 结构:
import pytest
from riderhub import create_app
@pytest.fixture()
def app():
app = create_app({
"TESTING": True,
"SECRET_KEY": "test",
})
yield app
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def runner(app):
return app.test_cli_runner()
def test_healthz(client):
response = client.get("/healthz")
assert response.status_code == 200
assert response.get_json() == {"status": "ok"}如果你要在测试里继续访问 session 或上下文对象,要用 with client::
from flask import session
def test_login_sets_session(client):
with client:
client.post("/login", data={"username": "ada"})
assert session["username"] == "ada"如果你要提前改会话:
def test_seed_session(client):
with client.session_transaction() as sess:
sess["user_id"] = 7而 CLI 命令也能测:
def test_init_db_command(runner):
result = runner.invoke(args=["init-db"])
assert "initialized the database" in result.output这套测试体验为什么顺手?
因为 Flask 的 app factory、context、CLI、request client 这几套东西,天然就能拼成一条完整测试链。