HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

08-FastAPI 项目为什么要尽早上异步测试和 Ruff

第 18 / 26 段:搭好异步测试基础设施

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Testing、Ruff、DX

搭好异步测试基础设施(续)

# tests/test_users.py
import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
    response = await client.post("/users", json={
        "email": "test@example.com",
        "username": "testuser",
        "password": "secret123",
    })

    assert response.status_code == 201
    data = response.json()
    assert data["email"] == "test@example.com"
    assert "password" not in data

@pytest.mark.asyncio
async def test_create_user_duplicate_email(client: AsyncClient):
    payload = {"email": "dup@example.com", "username": "user1", "password": "pass"}

    await client.post("/users", json=payload)
    response = await client.post("/users", json=payload)

    assert response.status_code == 409
    assert response.json()["code"] == "email_exists"

pytest 配置

# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]