test_async_task_worker.py 10.2 KB
"""F-10 异步任务处理服务测试"""
import pytest
from unittest.mock import patch, AsyncMock, MagicMock, ANY
from datetime import datetime, timedelta
from httpx import AsyncClient

from app.models.async_task import AsyncTask
from app.models.call_record import CallRecord


# Mock Celery task.delay to prevent real Redis connection
@pytest.fixture(autouse=True)
def mock_celery():
    """Mock Celery 任务提交,防止真实 Redis 连接(每个调用返回不同 ID)"""
    counter = [0]
    with patch("app.services.orchestration_service.HAS_CELERY", True), \
         patch("app.services.orchestration_service.process_async_llm_call") as mock_task:
        def delay_side_effect(**kwargs):
            counter[0] += 1
            return MagicMock(id=f"mock-celery-id-{counter[0]:06d}")
        mock_task.delay.side_effect = delay_side_effect
        yield mock_task


class TestAsyncTaskOrchestration:
    """异步任务编排测试(mock Celery)"""

    PROVIDER_DATA = {
        "provider_name": "async-test-provider",
        "display_name": "异步测试供应商",
        "adapter_type": "openai_compat",
        "supported_models": ["gpt-async"],
    }

    ACCOUNT_DATA = {
        "account_name": "异步测试账号",
        "code": "ACCOUNT-ASYNC-001",
        "api_key": "sk-async-test-key",
        "model_name": "gpt-async",
        "priority": 1,
        "status": "active",
    }

    ASYNC_REQUEST = {
        "model_name": "gpt-async",
        "biz_type": "general",
        "request_body": {"messages": [{"role": "user", "content": "Hello"}]},
    }

    @pytest.mark.asyncio
    async def _setup(self, client: AsyncClient) -> tuple:
        """创建测试数据"""
        resp = await client.post("/api/v1/providers", json=self.PROVIDER_DATA)
        provider = resp.json()
        provider_id = provider["id"]

        acct_data = self.ACCOUNT_DATA.copy()
        acct_data["provider_id"] = provider_id
        resp = await client.post("/api/v1/accounts", json=acct_data)
        account_id = resp.json()["id"]

        return provider_id, account_id

    @pytest.mark.asyncio
    async def test_async_call_submits_to_celery(self, client: AsyncClient):
        """测试异步调用正确提交到 Celery"""
        from app.services.orchestration_service import process_async_llm_call

        await self._setup(client)

        resp = await client.post("/api/v1/calls/orchestrate/async", json=self.ASYNC_REQUEST)
        assert resp.status_code == 202
        result = resp.json()
        assert result["status"] == "accepted"
        assert "task_id" in result
        # 验证 Celery delay 被调用
        process_async_llm_call.delay.assert_called_once()
        # 验证传入的是 async_task_id
        call_kwargs = process_async_llm_call.delay.call_args
        assert "async_task_id" in call_kwargs[1] or call_kwargs[0][0]

    @pytest.mark.asyncio
    async def test_async_call_creates_task_record(self, client: AsyncClient, db_session):
        """测试异步调用创建了 AsyncTask 记录"""
        await self._setup(client)

        resp = await client.post("/api/v1/calls/orchestrate/async", json=self.ASYNC_REQUEST)
        assert resp.status_code == 202
        task_id = resp.json()["task_id"]

        # 验证数据库中存在该记录
        from sqlalchemy import select
        result = await db_session.execute(
            select(AsyncTask).where(AsyncTask.id == task_id)
        )
        task = result.scalar_one_or_none()
        assert task is not None
        assert task.status in ("processing", "pending")
        assert task.celery_task_id != ""

    @pytest.mark.asyncio
    async def test_async_call_query_result(self, client: AsyncClient, db_session):
        """测试查询异步调用结果"""
        await self._setup(client)

        # 创建异步任务
        resp = await client.post("/api/v1/calls/orchestrate/async", json=self.ASYNC_REQUEST)
        assert resp.status_code == 202
        task_id = resp.json()["task_id"]

        # 查询结果
        resp = await client.get(f"/api/v1/calls/orchestrate/async", params={"task_id": task_id})
        assert resp.status_code == 200
        result = resp.json()
        assert result["task_id"] == task_id

    @pytest.mark.asyncio
    async def test_async_call_query_not_found(self, client: AsyncClient):
        """测试查询不存在的异步任务"""
        resp = await client.get("/api/v1/calls/orchestrate/async", params={"task_id": "nonexistent-id"})
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_async_call_batch_query(self, client: AsyncClient):
        """测试批量查询"""
        await self._setup(client)

        ids = []
        for i in range(2):
            data = self.ASYNC_REQUEST.copy()
            data["request_body"] = {"messages": [{"role": "user", "content": f"Batch {i}"}]}
            resp = await client.post("/api/v1/calls/orchestrate/async", json=data)
            assert resp.status_code == 202
            ids.append(resp.json()["task_id"])

        resp = await client.post(
            "/api/v1/calls/orchestrate/async/batch",
            json={"task_ids": ids},
        )
        assert resp.status_code == 200
        result = resp.json()
        assert len(result["results"]) == 2

    @pytest.mark.asyncio
    async def test_async_call_model_not_found(self, client: AsyncClient):
        """测试模型无可用账号返回 404"""
        data = self.ASYNC_REQUEST.copy()
        data["model_name"] = "nonexistent-model"
        resp = await client.post("/api/v1/calls/orchestrate/async", json=data)
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_async_call_missing_model(self, client: AsyncClient):
        """测试缺少 model_name 返回 422"""
        data = self.ASYNC_REQUEST.copy()
        del data["model_name"]
        resp = await client.post("/api/v1/calls/orchestrate/async", json=data)
        assert resp.status_code == 422


class TestAsyncTaskWorker:
    """Celery 工作器核心逻辑测试"""

    @pytest.mark.asyncio
    async def test_celery_app_created(self):
        """测试 Celery 应用创建成功"""
        from app.celery_app import celery_app
        assert celery_app.main == "llm_call_platform"
        assert "app.tasks.llm_tasks.process_async_llm_call" in [
            t.name for t in celery_app.tasks.values() if hasattr(t, 'name')
        ]

    def test_task_module_importable(self):
        """测试任务模块可导入"""
        from app.tasks import llm_tasks
        assert hasattr(llm_tasks, "process_async_llm_call")
        assert hasattr(llm_tasks, "rescan_stuck_tasks")

    @pytest.mark.asyncio
    async def test_rescan_stuck_with_mock_db(self):
        """测试扫描卡住任务逻辑(mock DB)"""
        from app.tasks.llm_tasks import _rescan_stuck

        # Mock async_session_factory
        with patch("app.tasks.llm_tasks.async_session_factory") as mock_factory:
            mock_session = MagicMock()
            # 模拟没有卡住任务:db.execute() 是 async,需要返回可 await 对象
            mock_execute_result = MagicMock()
            mock_execute_result.scalars.return_value.all.return_value = []
            mock_execute = AsyncMock(return_value=mock_execute_result)
            mock_session.__aenter__.return_value.execute = mock_execute
            mock_factory.return_value = mock_session

            result = await _rescan_stuck()
            assert result == []

    @pytest.mark.asyncio
    async def test_process_call_with_mock_db(self):
        """测试处理异步任务的核心逻辑"""
        from app.tasks.llm_tasks import _process_call

        # Mock 完整的 DB 和 adapter 调用
        with patch("app.tasks.llm_tasks.async_session_factory") as mock_factory, \
             patch("app.tasks.llm_tasks.adapter_invoke") as mock_adapter:

            # Mock adapter 返回成功
            mock_response = MagicMock()
            mock_response.success = True
            mock_response.content = "测试回复"
            mock_response.prompt_tokens = 50
            mock_response.completion_tokens = 20
            mock_response.total_tokens = 70
            mock_response.raw_response = {"choices": [{"message": {"content": "测试回复"}}]}
            mock_adapter.return_value = mock_response

            # Mock session and query chain
            mock_session = MagicMock()

            # Mock for async_task query
            mock_task = MagicMock(spec=AsyncTask)
            mock_task.id = "test-task-id"
            mock_task.call_record_id = "test-call-id"
            mock_task.status = "pending"
            mock_task.celery_task_id = ""
            mock_task.progress = 0

            # Mock for call_record query
            mock_call = MagicMock(spec=CallRecord)
            mock_call.id = "test-call-id"
            mock_call.account_id = "test-account-id"
            mock_call.model_name = "gpt-test"
            mock_call.request_body = {"messages": [{"role": "user", "content": "Hi"}]}
            mock_call.status = "pending"

            # Mock for account query
            mock_account = MagicMock()
            mock_account.id = "test-account-id"
            mock_account.provider_id = "test-provider-id"
            mock_account.model_name = "gpt-test"

            # Mock for provider query
            mock_provider = MagicMock()
            mock_provider.id = "test-provider-id"
            mock_provider.adapter_type = "openai_compat"

            # Setup execute chain: first call returns task, second returns call_record, etc.
            mock_execute = AsyncMock()
            results = [
                MagicMock(scalar_one_or_none=lambda: mock_task),
                MagicMock(scalar_one_or_none=lambda: mock_call),
                MagicMock(scalar_one_or_none=lambda: mock_account),
                MagicMock(scalar_one_or_none=lambda: mock_provider),
            ]
            mock_execute.side_effect = results

            mock_session.__aenter__.return_value.execute = mock_execute
            mock_session.__aenter__.return_value.flush = AsyncMock()
            mock_factory.return_value = mock_session

            result = await _process_call("test-task-id")
            assert result["status"] == "success"
            assert result["task_id"] == "test-task-id"