FastAPI 全栈后端(七):测试与自动化

创作者: Yardon | GitHub: github.com/YardonYan | 版本: v1.0 |



测试框架 pytest

bash 复制代码
pip install pytest pytest-asyncio httpx
python 复制代码
# test_main.py
def test_root():
    assert True

def test_add():
    assert 1 + 1 == 2
bash 复制代码
pytest test_main.py -v

FastAPI TestClient

python 复制代码
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_login_success():
    response = client.post(
        "/api/v1/auth/token",
        data={"username": "yardon", "password": "secret123"},
    )
    assert response.status_code == 200
    assert "access_token" in response.json()

def test_login_wrong_password():
    response = client.post(
        "/api/v1/auth/token",
        data={"username": "yardon", "password": "wrong"},
    )
    assert response.status_code == 401

TestClient 让同步测试不需要启动真实服务器,响应速度极快。


异步测试

python 复制代码
import pytest
from httpx import AsyncClient, ASGITransport
from main import app

@pytest.mark.asyncio
async def test_list_users():
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        response = await ac.get("/api/v1/users")
    assert response.status_code == 200

Fixture 与依赖覆盖

python 复制代码
from pytest import fixture
from main import app
from db import get_db, override_get_db

@fixture
def test_db():
    # 创建测试数据库
    Base.metadata.create_all(bind=test_engine)
    yield
    Base.metadata.drop_all(bind=test_engine)

def test_with_db(test_db):
    app.dependency_overrides[get_db] = override_get_db
    # 测试结束后清理
    app.dependency_overrides.clear()

本章小结

pytest + TestClient 是 FastAPI 测试的核心组合。记住:用 fixture 管理测试数据,用 override_get_db 隔离数据库测试。


📌 创作者: Yardon | 🏠 个人网站: GlimmerAI.top

📖 本章是「FastAPI 全栈后端 」系列的第 7 章。下一章:部署与运维

🌟 欢迎大家来观看!

相关推荐
FII工业富联科技服务6 小时前
工业AI自治的演进趋势:从内容生成到Agent驱动的工厂运营范式转变
人工智能
波波0076 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
云和数据.ChenGuang6 小时前
fastapi的参数剖析
人工智能·深度学习·机器学习·语言模型·状态模式·fastapi
日常筹谋记6 小时前
技术研究:数据中心HVDC系统直流保护配合与ABB电气产品参数解析
人工智能·创业创新·业界资讯
元岳数字人小元6 小时前
AI数字人系统赋能场景升级,数字人一体机实现服务提效降本
人工智能
Sammyyyyy6 小时前
如何在不停项目不停机的情况下切换AI大模型
大数据·人工智能
Brown.alexis6 小时前
es6知识点1-自备使用
前端·ecmascript·es6
poiu12346576 小时前
客户沟通音视频素材提炼会议纪要,主流AI工具横向实测对比
人工智能
咖啡星人k7 小时前
想私有化部署 AI 开发平台?MonkeyCode 给出的答案是开源 + 离线
人工智能·大模型·ai编程·monkeycode
NineData7 小时前
DTCC 2026 预告|NineData CEO& 创始人叶正盛:面向 AI Agent 的数据库 DevOps 与数据复制实践
数据库·人工智能·数据库开发·devops·ninedata·数据库技术·dtcc