"""API 集成测试。""" from collections.abc import AsyncGenerator import pytest from httpx import ASGITransport, AsyncClient from app.api.v1.deps import require_admin from app.main import app @pytest.fixture async def client( monkeypatch: pytest.MonkeyPatch, auth_headers: dict[str, str] ) -> AsyncGenerator[AsyncClient, None]: transport = ASGITransport(app=app) async with AsyncClient( transport=transport, base_url="http://test", headers=auth_headers, ) as http_client: yield http_client @pytest.mark.asyncio async def test_health_and_defaults(client: AsyncClient) -> None: health = await client.get("/api/v1/health") assert health.status_code == 200 character = await client.get("/api/v1/characters/active") assert character.status_code == 200 assert character.json()["id"].startswith("character_") @pytest.mark.asyncio async def test_mcp_server_crud(client: AsyncClient) -> None: """MCP 服务器注册 CRUD——覆盖 services/mcp 路径。""" created = await client.post( "/api/v1/tools/mcp-servers", json={ "name": "测试 MCP", "transport": "stdio", "command": "echo", "args_json": '["hello"]', }, ) assert created.status_code == 201 mcp_id = created.json()["id"] listed = await client.get("/api/v1/tools/mcp-servers") assert listed.status_code == 200 assert any(item["id"] == mcp_id for item in listed.json()) # MCP 服务器没有 GET single 端点,跳过 # PATCH: UpdateMcpServerRequest 不含 name 字段,改 command 验证路径可通 updated = await client.patch( f"/api/v1/tools/mcp-servers/{mcp_id}", json={"command": "cat", "args_json": '["-n"]'}, ) assert updated.status_code == 200 assert updated.json()["command"] == "cat" deleted = await client.delete(f"/api/v1/tools/mcp-servers/{mcp_id}") assert deleted.status_code == 204 @pytest.mark.asyncio async def test_preferences_flow(client: AsyncClient) -> None: """偏好设置读写——覆盖 services/preferences 路径。""" fetched = await client.get("/api/v1/settings/preferences") assert fetched.status_code == 200 assert "temperature" in fetched.json() updated = await client.patch( "/api/v1/settings/preferences", json={"temperature": 0.7, "max_output_tokens": 4096}, ) assert updated.status_code == 200 assert updated.json()["temperature"] == 0.7 assert updated.json()["max_output_tokens"] == 4096