test_async_tasks_api.py 8.7 KB
"""异步任务 API 测试"""
import pytest
from httpx import AsyncClient


class TestAsyncTasksAPI:
    """异步任务 API 测试"""

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

    ACCOUNT_CREATE_DATA = {
        "account_name": "测试账号 task",
        "code": "ACCOUNT-TASK-001",
        "api_key": "sk-test-task-key",
        "model_name": "test-model-1",
    }

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

    TASK_CREATE_DATA = {
        "celery_task_id": "celery-task-001",
    }

    TASK_UPDATE_DATA = {
        "status": "success",
        "progress": 100,
        "result": {"output": "task completed"},
    }

    @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) -> str:
        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()["id"]

    @pytest.mark.asyncio
    async def _create_task(self, client: AsyncClient, call_record_id: str) -> dict:
        data = self.TASK_CREATE_DATA.copy()
        data["call_record_id"] = call_record_id
        resp = await client.post("/api/v1/async-tasks", json=data)
        return resp.json()

    @pytest.mark.asyncio
    async def test_create_async_task(self, client: AsyncClient):
        """测试创建异步任务记录"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)

        data = self.TASK_CREATE_DATA.copy()
        data["call_record_id"] = call_id
        resp = await client.post("/api/v1/async-tasks", json=data)
        assert resp.status_code == 201
        result = resp.json()
        assert result["celery_task_id"] == "celery-task-001"
        assert result["status"] == "processing"
        assert result["progress"] == 0
        assert result["call_record_id"] == call_id
        assert "id" in result

    @pytest.mark.asyncio
    async def test_update_async_task(self, client: AsyncClient):
        """测试更新任务状态和结果"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)
        created = await self._create_task(client, call_id)
        task_id = created["id"]

        resp = await client.put(
            f"/api/v1/async-tasks/{task_id}",
            json=self.TASK_UPDATE_DATA,
        )
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "success"
        assert result["progress"] == 100
        assert result["result"] == {"output": "task completed"}

    @pytest.mark.asyncio
    async def test_update_async_task_not_found(self, client: AsyncClient):
        """测试更新不存在的任务应返回 404"""
        resp = await client.put(
            "/api/v1/async-tasks/nonexistent-id",
            json=self.TASK_UPDATE_DATA,
        )
        assert resp.status_code == 404

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

        resp = await client.get(f"/api/v1/async-tasks/{task_id}")
        assert resp.status_code == 200
        result = resp.json()
        assert result["id"] == task_id
        assert result["celery_task_id"] == "celery-task-001"

    @pytest.mark.asyncio
    async def test_get_async_task_not_found(self, client: AsyncClient):
        """测试查询不存在的任务应返回 404"""
        resp = await client.get("/api/v1/async-tasks/nonexistent-id")
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_list_async_tasks(self, client: AsyncClient):
        """测试查询异步任务列表"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)
        await self._create_task(client, call_id)

        resp = await client.get("/api/v1/async-tasks")
        assert resp.status_code == 200
        result = resp.json()
        assert result["total"] >= 1
        assert len(result["items"]) >= 1

    @pytest.mark.asyncio
    async def test_list_async_tasks_filter_by_status(self, client: AsyncClient):
        """测试按状态筛选任务"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)
        await self._create_task(client, call_id)

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

    @pytest.mark.asyncio
    async def test_cancel_async_task(self, client: AsyncClient):
        """测试取消异步任务"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)
        created = await self._create_task(client, call_id)
        task_id = created["id"]

        resp = await client.post(f"/api/v1/async-tasks/{task_id}/cancel")
        assert resp.status_code == 200
        result = resp.json()
        assert result["status"] == "cancelled"

    @pytest.mark.asyncio
    async def test_cancel_async_task_not_found(self, client: AsyncClient):
        """测试取消不存在的任务应返回 404"""
        resp = await client.post("/api/v1/async-tasks/nonexistent-id/cancel")
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_cancel_async_task_wrong_status(self, client: AsyncClient):
        """测试取消已完成的任务应返回 409"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        call_id = await self._create_call(client, account_id, provider_id)
        created = await self._create_task(client, call_id)
        task_id = created["id"]

        # 先完成任务
        await client.put(
            f"/api/v1/async-tasks/{task_id}",
            json={"status": "success", "progress": 100},
        )

        # 再取消应返回 409
        resp = await client.post(f"/api/v1/async-tasks/{task_id}/cancel")
        assert resp.status_code == 409

    @pytest.mark.asyncio
    async def test_async_task_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):
            # 每个调用使用不同的 request_body 避免 MD5 冲突
            call_data = self.CALL_CREATE_DATA.copy()
            call_data["account_id"] = account_id
            call_data["provider_id"] = provider_id
            call_data["request_body"] = {"messages": [{"role": "user", "content": f"Hello {i}"}]}
            resp = await client.post("/api/v1/calls", json=call_data)
            call_id = resp.json()["id"]

            task_data = {"call_record_id": call_id, "celery_task_id": f"celery-task-{i}"}
            await client.post("/api/v1/async-tasks", json=task_data)

        resp = await client.get("/api/v1/async-tasks?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