import logging import random import httpx import pytest # 使用 pytest 来运行异步测试 from app.main import app # 替换为你的 FastAPI 应用实例 @pytest.mark.asyncio # 指定测试是异步的 async def test_list_chapter_relations(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/relations/") assert response.status_code == 200 assert isinstance(response.json(), list) # 检查返回的数据类型 @pytest.mark.asyncio async def test_search_chapters_valid(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/search_chapters?q=1") assert response.status_code == 200 assert isinstance(response.json(), list) assert len(response.json()) > 0 # 假设数据库中有相关数据 @pytest.mark.asyncio async def test_search_chapters_invalid(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/search_chapters?q=") # 空查询 assert response.status_code == 400 assert response.json() == {"detail": "搜索关键字不能为空"} @pytest.mark.asyncio async def test_get_relations_by_level_valid(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/relations/level/3") print(response.json()) assert response.status_code == 200 assert isinstance(response.json(), list) assert len(response.json()) > 0 @pytest.mark.asyncio async def test_get_relations_by_level_invalid(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/relations/level/6") assert response.status_code == 400 assert response.json() == {"detail": "层级参数必须在 0 到 5 之间"} @pytest.mark.asyncio async def test_get_relations_by_chapter_valid(): chapter_id = random.choice(["1", "3", "6", "8", "15"]) async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get(f"/chapters/{chapter_id}/relations") print(response.json()) assert response.status_code == 200 assert isinstance(response.json(), list) @pytest.mark.asyncio async def test_get_relations_by_chapter_not_found(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/chapters/10/relations") print(response.json()) assert response.status_code == 404 assert response.json() == {"detail": "No relations found for chapter 10"}