Browse Source

🎨 [pre-commit.ci] Auto format from pre-commit.com hooks

pull/13938/head
pre-commit-ci[bot] 2 weeks ago
parent
commit
e6164a272b
  1. 26
      tests/test_custom_api.py

26
tests/test_custom_api.py

@ -2,12 +2,13 @@
自定义API测试 自定义API测试
这是一个示例测试文件展示如何在FastAPI项目中编写测试 这是一个示例测试文件展示如何在FastAPI项目中编写测试
""" """
from typing import Optional
import pytest import pytest
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from pydantic import BaseModel from pydantic import BaseModel
from typing import Optional
# 创建一个简单的FastAPI应用用于测试 # 创建一个简单的FastAPI应用用于测试
app = FastAPI() app = FastAPI()
@ -74,11 +75,7 @@ class TestCustomAPI:
def test_create_item(self): def test_create_item(self):
"""测试创建商品""" """测试创建商品"""
item_data = { item_data = {"name": "Test Item", "price": 99.99, "is_offer": True}
"name": "Test Item",
"price": 99.99,
"is_offer": True
}
response = client.post("/items/", json=item_data) response = client.post("/items/", json=item_data)
assert response.status_code == 200 assert response.status_code == 200
response_data = response.json() response_data = response.json()
@ -93,11 +90,14 @@ class TestCustomAPI:
assert response.status_code == 200 assert response.status_code == 200
assert response.json() == {"user_id": 123, "username": "user_123"} assert response.json() == {"user_id": 123, "username": "user_123"}
@pytest.mark.parametrize("item_id,expected_id", [ @pytest.mark.parametrize(
"item_id,expected_id",
[
(1, 1), (1, 1),
(42, 42), (42, 42),
(999, 999), (999, 999),
]) ],
)
def test_read_item_parametrized(self, item_id, expected_id): def test_read_item_parametrized(self, item_id, expected_id):
"""参数化测试:测试不同的商品ID""" """参数化测试:测试不同的商品ID"""
response = client.get(f"/items/{item_id}") response = client.get(f"/items/{item_id}")
@ -114,7 +114,7 @@ class TestCustomAPI:
invalid_data = { invalid_data = {
"name": "Test Item", "name": "Test Item",
# 缺少必需的price字段 # 缺少必需的price字段
"is_offer": True "is_offer": True,
} }
response = client.post("/items/", json=invalid_data) response = client.post("/items/", json=invalid_data)
assert response.status_code == 422 # 验证错误 assert response.status_code == 422 # 验证错误
@ -139,11 +139,7 @@ def test_openapi_schema():
@pytest.fixture @pytest.fixture
def sample_item(): def sample_item():
"""测试用的示例商品数据""" """测试用的示例商品数据"""
return { return {"name": "Sample Item", "price": 50.0, "is_offer": False}
"name": "Sample Item",
"price": 50.0,
"is_offer": False
}
def test_with_fixture(sample_item): def test_with_fixture(sample_item):

Loading…
Cancel
Save