test_strategies_api.py 9.05 KB
"""调用策略 API 测试"""
import pytest
from httpx import AsyncClient


class TestStrategyAPI:
    """调用策略配置 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-STRAT-001",
        "api_key": "sk-test-api-key-12345",
        "model_name": "test-model-1",
        "temperature": 0.5,
        "max_tokens": 2048,
        "priority": 1,
    }

    STRATEGY_CREATE_DATA = {
        "strategy_name": "默认策略",
        "retry_enabled": True,
        "retry_max_attempts": 3,
        "retry_interval_ms": 1000,
        "degrade_enabled": True,
        "timeout_enabled": True,
        "timeout_connect_ms": 5000,
        "timeout_read_ms": 30000,
    }

    STRATEGY_UPDATE_DATA = {
        "strategy_name": "更新后的策略",
        "retry_enabled": False,
    }

    @pytest.mark.asyncio
    async def _create_provider(self, client: AsyncClient) -> str:
        """辅助方法:创建一个供应商并返回 ID"""
        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:
        """辅助方法:创建一个账号并返回 ID"""
        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_strategy(self, client: AsyncClient, account_id: str) -> dict:
        """辅助方法:创建一个策略并返回完整响应"""
        data = self.STRATEGY_CREATE_DATA.copy()
        data["account_id"] = account_id
        resp = await client.post("/api/v1/strategies", json=data)
        return resp.json()

    @pytest.mark.asyncio
    async def test_create_strategy(self, client: AsyncClient):
        """测试创建策略"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        data = self.STRATEGY_CREATE_DATA.copy()
        data["account_id"] = account_id

        resp = await client.post("/api/v1/strategies", json=data)
        assert resp.status_code == 201
        result = resp.json()
        assert result["strategy_name"] == self.STRATEGY_CREATE_DATA["strategy_name"]
        assert result["retry_enabled"] is True
        assert result["retry_max_attempts"] == 3
        assert result["timeout_connect_ms"] == 5000
        assert result["enabled"] is True
        assert "id" in result

    @pytest.mark.asyncio
    async def test_list_strategies(self, client: AsyncClient):
        """测试查询策略列表"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        await self._create_strategy(client, account_id)

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

    @pytest.mark.asyncio
    async def test_list_strategies_filter_by_account(self, client: AsyncClient):
        """测试按账号筛选策略"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        await self._create_strategy(client, account_id)

        resp = await client.get(f"/api/v1/strategies?account_id={account_id}")
        assert resp.status_code == 200
        result = resp.json()
        for item in result["items"]:
            assert item["account_id"] == account_id

    @pytest.mark.asyncio
    async def test_get_strategy(self, client: AsyncClient):
        """测试查询策略详情"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_strategy(client, account_id)
        strategy_id = created["id"]

        resp = await client.get(f"/api/v1/strategies/{strategy_id}")
        assert resp.status_code == 200
        result = resp.json()
        assert result["id"] == strategy_id
        assert result["strategy_name"] == self.STRATEGY_CREATE_DATA["strategy_name"]

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

    @pytest.mark.asyncio
    async def test_update_strategy(self, client: AsyncClient):
        """测试更新策略"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_strategy(client, account_id)
        strategy_id = created["id"]

        resp = await client.put(
            f"/api/v1/strategies/{strategy_id}",
            json=self.STRATEGY_UPDATE_DATA,
        )
        assert resp.status_code == 200
        result = resp.json()
        assert result["strategy_name"] == self.STRATEGY_UPDATE_DATA["strategy_name"]
        assert result["retry_enabled"] is False

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

    @pytest.mark.asyncio
    async def test_toggle_strategy_enable(self, client: AsyncClient):
        """测试启用/停用策略链"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_strategy(client, account_id)
        strategy_id = created["id"]

        # 停用
        resp = await client.patch(
            f"/api/v1/strategies/{strategy_id}/enable",
            json={"enabled": False},
        )
        assert resp.status_code == 200
        assert resp.json()["enabled"] is False

        # 启用
        resp = await client.patch(
            f"/api/v1/strategies/{strategy_id}/enable",
            json={"enabled": True},
        )
        assert resp.status_code == 200
        assert resp.json()["enabled"] is True

    @pytest.mark.asyncio
    async def test_toggle_strategy_not_found(self, client: AsyncClient):
        """测试启用/停用不存在的策略应返回 404"""
        resp = await client.patch(
            "/api/v1/strategies/nonexistent-id/enable",
            json={"enabled": True},
        )
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_strategy_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.STRATEGY_CREATE_DATA.copy()
            data["account_id"] = account_id
            data["strategy_name"] = f"策略 {i}"
            await client.post("/api/v1/strategies", json=data)

        resp = await client.get("/api/v1/strategies?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_strategy_no_account_id(self, client: AsyncClient):
        """测试创建策略时缺少 account_id 应返回 422"""
        data = self.STRATEGY_CREATE_DATA.copy()
        resp = await client.post("/api/v1/strategies", json=data)
        assert resp.status_code == 422

    @pytest.mark.asyncio
    async def test_create_strategy_account_not_found(self, client: AsyncClient):
        """测试创建策略时关联账号不存在应返回 400"""
        data = self.STRATEGY_CREATE_DATA.copy()
        data["account_id"] = "nonexistent-account-id"
        resp = await client.post("/api/v1/strategies", json=data)
        assert resp.status_code == 400

    @pytest.mark.asyncio
    async def test_delete_strategy(self, client: AsyncClient):
        """测试删除策略"""
        provider_id = await self._create_provider(client)
        account_id = await self._create_account(client, provider_id)
        created = await self._create_strategy(client, account_id)
        strategy_id = created["id"]

        resp = await client.delete(f"/api/v1/strategies/{strategy_id}")
        assert resp.status_code == 200

        # 验证已删除
        resp = await client.get(f"/api/v1/strategies/{strategy_id}")
        assert resp.status_code == 404

    @pytest.mark.asyncio
    async def test_delete_strategy_not_found(self, client: AsyncClient):
        """测试删除不存在的策略应返回 404"""
        resp = await client.delete("/api/v1/strategies/nonexistent-id")
        assert resp.status_code == 404