测试应用
在本页中,你将运行扩展应用中 layered 级别 shop 项目的测试,阅读这些测试的构建方式,并编写一个自己的测试。你将了解 FastAPI 的 TestClient 如何在不启动服务器的情况下调用应用,pytest fixture 如何为每个测试做准备,app.dependency_overrides 如何把依赖项替换成测试用的版本,以及如何检查校验和错误响应。你还会看到 fastkit 自带哪些测试,以及 Coverage 测试选项如何衡量这些测试覆盖了多少代码。
运行测试
fastkit 的每个级别都自带测试,fastkit addroute 也会为它添加的每个资源编写测试。在 shop 中用 pytest 运行它们:
$ uv run pytest -q
...
tests/test_config.py ...................................... [ 41%]
tests/test_item_store.py ..... [ 47%]
tests/test_items.py ......................... [ 74%]
tests/test_main.py ...... [ 81%]
tests/test_users.py ................. [100%]
============================= 91 passed in 10.42s ==============================
pytest 会收集 tests/ 下所有的 test_*.py 文件,并运行其中名称以 test_ 开头的每个函数。每个点代表一个通过的测试。test_config.py 检查设置的规则(例如在开发环境之外对 SECRET_KEY 的检查),test_item_store.py 检查基于文件的条目存储,test_items.py 和 test_main.py 检查 HTTP 端点,test_users.py 则是 fastkit addroute users 写入的文件。
测试客户端是怎样构建的
TestClient 不启动 uvicorn,直接把请求发送给应用对象。你调用 client.get(...) 或 client.post(..., json=...),就会得到一个带有 status_code、headers 和 json() 的响应。pytest fixture 是用 @pytest.fixture 标记的函数。如果测试把某个 fixture 写成参数,就会收到这个 fixture 的值;如果 fixture 使用了 yield,yield 之后的代码会在测试结束后运行。tests/conftest.py 存放所有测试文件共用的 fixture:
@pytest.fixture
def store(tmp_path: Path) -> ItemStore:
"""Item store on a temporary file, so tests never touch src/mocks."""
path = tmp_path / "items.json"
path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8")
return ItemStore(path)
@pytest.fixture
def client(store: ItemStore) -> Generator[TestClient, None, None]:
app.dependency_overrides[get_item_store] = lambda: store
# TestClient sends requests straight to the app, without starting a server.
# https://fastapi.tiangolo.com/tutorial/testing/
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
端点从依赖项 get_item_store 获取条目存储(见扩展应用)。app.dependency_overrides 是应用上的一个字典:键是依赖项函数,值是 FastAPI 改为调用的函数。在这里,测试中的每个请求拿到的都是一个基于临时文件、预置了两个条目的存储,因此测试永远不会改动 src/mocks/mock_items.json。tmp_path 是 pytest 内置的 fixture,会为每个测试提供一个新的临时目录。测试结束后,clear() 会移除这个覆盖。FastAPI 指南使用覆盖测试依赖项讲解了这种技巧。
阅读一个测试
一个测试发送一个请求,并用 assert 检查响应。下面这个来自 tests/test_items.py 的测试检查对未知 id 返回的 404 响应:
def test_get_item_not_found(client: TestClient) -> None:
response = client.get(f"{ITEMS_URL}/999")
assert response.status_code == 404
assert response.json() == {"detail": "Item not found"}
ITEMS_URL 的值是 /api/v1/items,由 conftest.py 根据设置拼出。其他测试也遵循同样的模式:test_create_item_returns_201_and_location 检查 201 状态码,并检查 Location 头部能否指回新建的条目;test_create_item_validates_input 发送无效的请求体(名称为空、价格为负数、缺少价格),并期望得到 422。由于请求体与 ItemCreate 模型不符,FastAPI 会在端点运行之前就返回这个 422。
编写一个测试
fastkit addroute 添加的 users 资源把记录保存在内存中,存放在 UserRepository 里,端点通过依赖项 get_user_repository 获取它(定义在 src/crud/users.py 中;src/api/deps.py 把它包装成 UserRepositoryDep)。请创建 tests/test_users_override.py,它的 fixture 会给端点提供一个已经存有一个用户的仓储:
from collections.abc import Iterator
import pytest
from fastapi.testclient import TestClient
from src.crud.users import UserRepository, get_user_repository
from src.main import app
USERS_URL = app.url_path_for("list_users")
@pytest.fixture
def client() -> Iterator[TestClient]:
repository = UserRepository()
repository.add({"name": "Ada"})
app.dependency_overrides[get_user_repository] = lambda: repository
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_lists_the_users_of_the_test_repository(client: TestClient) -> None:
response = client.get(USERS_URL)
assert response.status_code == 200
assert response.json()["items"] == [{"id": 1, "name": "Ada", "description": None}]
def test_rejects_an_empty_name(client: TestClient) -> None:
response = client.post(USERS_URL, json={"name": ""})
assert response.status_code == 422
assert response.json()["detail"][0]["loc"] == ["body", "name"]
app.url_path_for("list_users") 会查找端点函数 list_users 的路径,所以即使前缀改变,这个测试也能照常运行。第二个测试读取 422 响应的响应体:detail 是一个错误列表,loc 指出无效值所在的位置(请求体中的 name 字段)。再次运行测试,加上这两个新测试,总数变为 93:
$ uv run pytest -q
...
============================== 93 passed in 0.90s ==============================
衡量覆盖率
覆盖率告诉你测试运行了代码中的哪些行。hello 之后的每个级别都自带 pytest-cov,pyproject.toml 设定了要衡量的范围([tool.coverage.run]、source = ["src"])。在 shop 中运行:
$ uv run pytest --cov
...
Name Stmts Miss Cover Missing
----------------------------------------------------------
...
src/api/deps.py 8 1 88% 14
...
src/main.py 11 1 91% 24
...
----------------------------------------------------------
TOTAL 350 4 99%
============================== 93 passed in 1.25s ==============================
Miss 统计没有被任何测试运行到的行数,Missing 列出这些行:src/api/deps.py 的第 14 行是 get_item_store 的函数体,而测试总是用覆盖把它替换掉。
FastAPI 文档
下一步
迁移到领域结构和数据库把 shop 带到 domain 级别,在那里条目保存在 SQL 数据库中。