test_call_records_api.py 8.09 KB
"""调用记录 API 测试"""
import hashlib
import json
import pytest
from httpx import AsyncClient


class TestCallRecordsAPI:
    """调用记录 API 测试"""

    PROVIDER_DATA = {
        "provider_name": "test-provider",
        "display_name": "测试供应商",
        "adapter_type": "openai_compat",
        "supported_models": ["test-model-1"],
    }

    ACCOUNT_CREATE_DATA = {
        "account_name": "测试账号 1",
        "code": "ACCOUNT-CALL-001",
        "api_key": "sk-test-api-key-12345",
        "model_name": "test-model-1",
        "temperature": 0.5,
        "max_tokens": 2048,
        "priority": 1,
    }

    CALL_CREATE_DATA = {
        "model_name": "test-model-1",
        "biz_type": "general",
        "request_body": {"messages": [{"role": "user", "content": "Hello"}]},
    }

    CALL_UPDATE_RESULT_DATA = {
        "response_body": {"choices": [{"message": {"content": "Hi there!"}}]},
        "prompt_tokens": 10,
        "completion_tokens": 5,
        "total_tokens": 15,
        "duration_ms": 1200,
        "status": "success",
    }

    @pytest.mark.asyncio
    async def _create_provider(self, client: AsyncClient) -> str:
        resp = await client.post("/api/v1/providers", json=self.PROVIDER_DATA)
        return resp.json()["id"]

    @pytest.mark.asyncio
    async def _create_account(self, client: AsyncClient, provider_id: str) -> str:
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        resp = await client.post("/api/v1/accounts", json=data)
        return resp.json()["id"]

    @pytest.mark.asyncio
    async def _create_call(self, client: AsyncClient, account_id: str, provider_id: str) -> dict:
        data = self.CALL_CREATE_DATA.copy()
        data["account_id"] = account_id
        data["provider_id"] = provider_id
        resp = await client.post("/api/v1/calls", json=data)
        return resp.json()

    @pytest.mark.asyncio
    async def test_create_call(self, client: AsyncClient):
        """测试创建调用记录"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        data = self.CALL_CREATE_DATA.copy()
        data["account_id"] = account_id
        data["provider_id"] = provider_id

        resp = await client.post("/api/v1/calls", json=data)
        assert resp.status_code == 201
        result = resp.json()
        assert result["model_name"] == "test-model-1"
        assert result["biz_type"] == "general"
        assert result["status"] == "pending"
        assert result["prompt_tokens"] == 0
        assert result["completion_tokens"] == 0
        assert "id" in result
        assert "request_md5" in result

    @pytest.mark.asyncio
    async def test_create_call_md5_dedup(self, client: AsyncClient):
        """测试 MD5 去重阻止重复提交"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        data = self.CALL_CREATE_DATA.copy()
        data["account_id"] = account_id
        data["provider_id"] = provider_id

        resp1 = await client.post("/api/v1/calls", json=data)
        assert resp1.status_code == 201

        resp2 = await client.post("/api/v1/calls", json=data)
        assert resp2.status_code == 409

    @pytest.mark.asyncio
    async def test_update_call_result(self, client: AsyncClient):
        """测试更新调用结果"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_call(client, account_id, provider_id)
        call_id = created["id"]

        resp = await client.put(
            f"/api/v1/calls/{call_id}/result",
            json=self.CALL_UPDATE_RESULT_DATA,
        )
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"
        assert result["prompt_tokens"] == 10
        assert result["completion_tokens"] == 5
        assert result["total_tokens"] == 15
        assert result["duration_ms"] == 1200

    @pytest.mark.asyncio
    async def test_update_call_result_not_found(self, client: AsyncClient):
        """测试更新不存在的调用记录应返回 404"""
        resp = await client.put(
            "/api/v1/calls/nonexistent-id/result",
            json=self.CALL_UPDATE_RESULT_DATA,
        )
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_get_call(self, client: AsyncClient):
        """测试查询调用详情"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_call(client, account_id, provider_id)
        call_id = created["id"]

        resp = await client.get(f"/api/v1/calls/{call_id}")
        assert resp.status_code == 200
        result = resp.json()
        assert result["id"] == call_id
        assert result["model_name"] == "test-model-1"

    @pytest.mark.asyncio
    async def test_get_call_not_found(self, client: AsyncClient):
        """测试查询不存在的调用记录应返回 404"""
        resp = await client.get("/api/v1/calls/nonexistent-id")
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_list_calls(self, client: AsyncClient):
        """测试查询调用记录列表"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        await self._create_call(client, account_id, provider_id)

        resp = await client.get("/api/v1/calls")
        assert resp.status_code == 200
        result = resp.json()
        assert result["total"] >= 1
        assert len(result["items"]) >= 1
        assert "account_name" in result["items"][0]
        assert result["items"][0]["account_name"] == "测试账号 1"

    @pytest.mark.asyncio
    async def test_list_calls_filter_by_model(self, client: AsyncClient):
        """测试按模型名称筛选调用记录"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        await self._create_call(client, account_id, provider_id)

        resp = await client.get("/api/v1/calls?model_name=test-model-1")
        assert resp.status_code == 200
        result = resp.json()
        for item in result["items"]:
            assert item["model_name"] == "test-model-1"

    @pytest.mark.asyncio
    async def test_list_calls_filter_by_status(self, client: AsyncClient):
        """测试按状态筛选调用记录"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        await self._create_call(client, account_id, provider_id)

        resp = await client.get("/api/v1/calls?status=pending")
        assert resp.status_code == 200
        result = resp.json()
        for item in result["items"]:
            assert item["status"] == "pending"

    @pytest.mark.asyncio
    async def test_call_pagination(self, client: AsyncClient):
        """测试调用记录分页"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)

        for i in range(3):
            data = self.CALL_CREATE_DATA.copy()
            data["account_id"] = account_id
            data["provider_id"] = provider_id
            data["request_body"] = {"messages": [{"role": "user", "content": f"Test {i}"}]}
            await client.post("/api/v1/calls", json=data)

        resp = await client.get("/api/v1/calls?page=1&page_size=2")
        assert resp.status_code == 200
        result = resp.json()
        assert result["total"] == 3
        assert len(result["items"]) == 2
        assert result["total_pages"] == 2

    @pytest.mark.asyncio
    async def test_create_call_missing_account(self, client: AsyncClient):
        """测试创建调用记录时缺少 account_id 应返回 422"""
        data = self.CALL_CREATE_DATA.copy()
        data["provider_id"] = "some-provider"
        resp = await client.post("/api/v1/calls", json=data)
        assert resp.status_code == 422