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 章。下一章:部署与运维

🌟 欢迎大家来观看!

相关推荐
fanstuck3 小时前
1M 上下文能怎么用?我用 Seed Evolving 做了一个招标文件版本差异审查器
服务器·人工智能·数据分析·开源·aigc
墨舟的AI笔记5 小时前
React 组件库的 Tree Shaking:按需加载与副作用的工程化治理
人工智能
曦尧5 小时前
Microsoft Ontology Playground:用纯前端工具打通 Fabric IQ 本体论学习通路
ai·自动化
qq_589666055 小时前
TypeScript 完整入门教程
前端·javascript·typescript
WoooChi5 小时前
DailyTech-20260724
人工智能·科技·业界资讯
zh路西法6 小时前
【CAM Grad-CAM Grad-CAM++】深度学习模型可解释性:从原理到YOLOv8部署实战
人工智能·深度学习·yolo·yolov8·grad-cam·cam
雨辰AI6 小时前
全集实战:企业级大模型服务化部署全栈指南|FastAPI 封装 + Nginx 负载均衡 + 高可用架构 从单机到生产一步到位
人工智能·ai·负载均衡·fastapi·ai编程
触底反弹6 小时前
Vibe Coding 不写 Git,等于悬崖边飙车
人工智能·git·面试
北龙云海6 小时前
案例分享 | 面向公网业务系统境内访问白名单配置实操方案
运维·网络·安全·网络安全·告警·数据泄露·入侵攻击
FoldWinCard6 小时前
D5 Linux 网络及端口命令
linux·运维·服务器