2026-05-19 03:01:30 +00:00
|
|
|
"""基础测试模块,测试核心业务逻辑和 API 端点。"""
|
2026-05-14 08:04:47 +00:00
|
|
|
|
|
|
|
|
import pytest
|
2026-05-19 03:01:30 +00:00
|
|
|
from httpx import AsyncClient, ASGITransport
|
2026-05-14 08:04:47 +00:00
|
|
|
from app.main import app
|
2026-05-19 03:01:30 +00:00
|
|
|
from app.services import get_greeting, get_system_info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TestServices:
|
|
|
|
|
"""服务层单元测试。"""
|
|
|
|
|
|
|
|
|
|
def test_get_greeting_default(self):
|
|
|
|
|
"""测试无参数时返回默认问候语。"""
|
|
|
|
|
result = get_greeting()
|
|
|
|
|
assert result == "Hello, World!"
|
|
|
|
|
|
|
|
|
|
def test_get_greeting_with_name(self):
|
|
|
|
|
"""测试传入名字时返回个性化问候语。"""
|
|
|
|
|
result = get_greeting("FastAPI")
|
|
|
|
|
assert result == "Hello, FastAPI!"
|
|
|
|
|
|
|
|
|
|
def test_get_system_info_structure(self):
|
|
|
|
|
"""测试系统信息返回正确的字段结构。"""
|
|
|
|
|
info = get_system_info()
|
|
|
|
|
assert "message" in info
|
|
|
|
|
assert "timestamp" in info
|
|
|
|
|
assert "service" in info
|
|
|
|
|
assert "version" in info
|
|
|
|
|
assert info["message"] == "Hello, World!"
|
|
|
|
|
assert info["service"] == "Simple Hello API"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
|
class TestAPI:
|
|
|
|
|
"""API 端点集成测试。"""
|
|
|
|
|
|
|
|
|
|
async def test_root_endpoint(self):
|
|
|
|
|
"""测试根路径返回正确的系统信息。"""
|
|
|
|
|
transport = ASGITransport(app=app)
|
|
|
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
|
|
|
response = await client.get("/")
|
|
|
|
|
assert response.status_code == 200
|
|
|
|
|
data = response.json()
|
|
|
|
|
assert data["message"] == "Hello, World!"
|
|
|
|
|
assert "timestamp" in data
|
|
|
|
|
|
|
|
|
|
async def test_hello_endpoint(self):
|
|
|
|
|
"""测试 /hello/{name} 返回正确的问候语。"""
|
|
|
|
|
transport = ASGITransport(app=app)
|
|
|
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
|
|
|
response = await client.get("/hello/Python")
|
|
|
|
|
assert response.status_code == 200
|
|
|
|
|
data = response.json()
|
|
|
|
|
assert data["message"] == "Hello, Python!"
|