FastAPI 自动化测试

FastAPI 入门

Matt Eckerle

Software and Data Engineering Leader

什么是自动化测试?

单元测试

  • 重点:隔离的代码
  • 目的:验证代码功能
  • 范围:函数或方法
  • 环境:独立的 Python 环境
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

系统测试

  • 重点:独立的系统操作
  • 目的:验证系统功能
  • 范围:端点
  • 环境:运行应用的 Python 环境
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
FastAPI 入门

使用 TestClient

TestClient:用于 pytest 的 HTTP 客户端

# 导入 TestClient 和 app
from fastapi.testclient import TestClient
from .main import app

# 在应用上下文中创建测试客户端
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
FastAPI 入门

测试错误或失败响应

应用

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        raise HTTPException(
            status_code=404, 
            detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}

测试

def test_delete_nonexistent_item():
    response = client.delete(
        "/items",
        json={"id": -999})
    assert response.status_code == 404
    json = response.json()
    assert json == {"detail":
                    "Item not found."}
FastAPI 入门

让我们来练习!

FastAPI 入门

Preparing Video For Download...