全书目录

第二十九篇:Flask 完全指南 —— 轻骑兵微服务街区宇宙

第十四章:测试 —— 轻骑兵机动快,不代表可以盲冲

1 分钟 249 字 第 531 / 962 个阅读单元

Flask 官方测试文档到 2026-03-28 仍然非常稳定,核心工具就是:

  • app.test_client()
  • app.test_cli_runner()

一个典型的 pytest 结构:

py
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:

py
from flask import session

def test_login_sets_session(client):
    with client:
        client.post("/login", data={"username": "ada"})
        assert session["username"] == "ada"

如果你要提前改会话:

py
def test_seed_session(client):
    with client.session_transaction() as sess:
        sess["user_id"] = 7

而 CLI 命令也能测:

py
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 这几套东西,天然就能拼成一条完整测试链。