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. 32
      tests/test_custom_api.py

32
tests/test_custom_api.py

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

Loading…
Cancel
Save