FastAPI 教程

22.7 测试策略与部署

FastAPI电子商务API:完整测试策略与部署实战教程

FastAPI 教程

本教程详细指导如何使用FastAPI构建电子商务API,涵盖测试策略如单元测试和集成测试,以及部署到云平台如AWS或Heroku。适合新手学习FastAPI实战开发。

推荐工具
PyCharm专业版开发必备

功能强大的Python IDE,提供智能代码补全、代码分析、调试和测试工具,提高Python开发效率。特别适合处理列表等数据结构的开发工作。

了解更多

综合项目实战:FastAPI电子商务API测试策略与部署

介绍

FastAPI是一个现代、快速的Python Web框架,适合构建REST API。在电子商务项目中,API的可靠性和安全性至关重要。本教程将引导你创建一个简单的电子商务API,重点讲解测试策略和部署方法,帮助新手快速上手。

项目概述

我们将构建一个基础的电子商务API,包括以下功能:

  • 用户管理:注册、登录、身份验证
  • 产品管理:创建、读取、更新、删除产品
  • 订单管理:用户下单、查看订单历史
  • 使用数据库(如SQLite或PostgreSQL)存储数据

项目结构示例:

ecommerce_api/
├── main.py           # 主FastAPI应用
├── models.py         # 数据库模型
├── schemas.py        # Pydantic数据验证模型
├── routers/          # 路由模块
│   ├── users.py
│   ├── products.py
│   └── orders.py
├── crud.py           # CRUD操作
├── dependencies.py   # 依赖注入
├── config.py         # 配置文件
├── tests/            # 测试文件
└── requirements.txt  # 依赖包列表

测试策略

测试是确保API质量的关键。我们采用测试金字塔,从底层到高层进行测试。

1. 单元测试 (Unit Testing)

单元测试针对最小代码单元(如单个函数或方法)。使用pytest框架和FastAPI的TestClient。

示例:测试用户注册路由

# tests/test_users.py
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_create_user():
    response = client.post("/users/", json={"email": "test@example.com", "password": "password123"})
    assert response.status_code == 200
    assert response.json()["email"] == "test@example.com"

安装pytest:pip install pytest,运行测试:pytest tests/

2. 集成测试 (Integration Testing)

集成测试检查多个组件协同工作。例如,模拟数据库连接或外部API调用。

示例:使用pytest-fixtures设置测试数据库

# conftest.py
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, Base, get_db

TEST_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(TEST_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@pytest.fixture(scope="module")
def test_db():
    Base.metadata.create_all(bind=engine)
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()
        Base.metadata.drop_all(bind=engine)

@pytest.fixture(scope="module")
def client(test_db):
    def override_get_db():
        try:
            yield test_db
        finally:
            pass
    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()

# 在测试文件中使用
# tests/test_products.py
def test_create_product(client):
    response = client.post("/products/", json={"name": "Laptop", "price": 1000.0})
    assert response.status_code == 200

3. 端到端测试 (End-to-End Testing)

端到端测试模拟真实用户场景,例如使用Selenium或类似工具测试前端与API交互。对于API,可以通过脚本模拟完整业务流。

示例:测试下单流程

# tests/test_e2e.py
def test_order_flow(client):
    # 注册用户
    client.post("/users/", json={"email": "user@example.com", "password": "pass"})
    # 登录获取令牌
    login_response = client.post("/token", data={"username": "user@example.com", "password": "pass"})
    token = login_response.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    # 创建产品
    client.post("/products/", json={"name": "Phone", "price": 500.0}, headers=headers)
    # 下单
    order_response = client.post("/orders/", json={"product_id": 1, "quantity": 2}, headers=headers)
    assert order_response.status_code == 200

部署

部署API到生产环境确保高可用性和可扩展性。我们将介绍本地部署和云部署。

1. 本地部署

使用Uvicorn运行FastAPI应用。

在项目根目录运行:

uvicorn main:app --host 0.0.0.0 --port 8000 --reload
  • --reload 用于开发热重载。
  • 访问 http://localhost:8000/docs 查看API文档。

2. 云部署

选项A:使用Heroku(简单)

  1. 安装Heroku CLI并登录。
  2. 创建Procfile:web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-8000}
  3. 推送到Heroku:
git init
heroku create ecommerce-api-fastapi
git add .
git commit -m "Initial commit"
git push heroku main

选项B:使用AWS或Docker容器化(高级)

  • Docker化:创建Dockerfile,构建镜像并推送到Docker Hub或云容器服务。

示例Dockerfile:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

构建和运行:

docker build -t ecommerce-api .
docker run -p 8000:8000 ecommerce-api

3. CI/CD流水线

使用GitHub Actions自动化测试和部署。

示例.github/workflows/deploy.yml:

name: Deploy to Heroku
on:
  push:
    branches:
      - main
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.9'
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        run: pytest tests/
      - name: Deploy to Heroku
        if: success()
        env:
          HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}
        run: |
          heroku container:login
          heroku container:push web -a your-app-name
          heroku container:release web -a your-app-name

总结

本教程涵盖了FastAPI电子商务API的构建、测试策略和部署。通过单元测试、集成测试确保代码质量,并结合云平台如Heroku或Docker实现高效部署。新手可以逐步实践,加深对FastAPI的理解。未来可扩展添加更多功能如支付集成、监控等。

扩展学习

  • 阅读FastAPI官方文档:https://fastapi.tiangolo.com/
  • 学习pytest进阶用法
  • 探索更多部署选项如Kubernetes

快乐编码!

开发工具推荐
Python开发者工具包

包含虚拟环境管理、代码格式化、依赖管理、测试框架等Python开发全流程工具,提高开发效率。特别适合处理复杂数据结构和算法。

获取工具包