test_accounts_api.py 9.31 KB
"""账号 API 测试"""
import pytest
from httpx import AsyncClient


class TestAccountAPI:
    """模型账号配置 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-TEST-001",
        "api_key": "sk-test-api-key-12345",
        "model_name": "test-model-1",
        "temperature": 0.5,
        "max_tokens": 2048,
        "priority": 1,
    }

    ACCOUNT_UPDATE_DATA = {
        "account_name": "更新后的账号",
        "temperature": 0.3,
    }

    @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 test_create_account(self, client: AsyncClient):
        """测试创建账号"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id

        resp = await client.post("/api/v1/accounts", json=data)
        assert resp.status_code == 201
        result = resp.json()
        assert result["account_name"] == self.ACCOUNT_CREATE_DATA["account_name"]
        assert result["model_name"] == self.ACCOUNT_CREATE_DATA["model_name"]
        # API Key 应脱敏
        assert "****" in result["api_key"]
        assert self.ACCOUNT_CREATE_DATA["api_key"] not in result["api_key"]
        assert "id" in result

    @pytest.mark.asyncio
    async def test_list_accounts(self, client: AsyncClient):
        """测试查询账号列表"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        await client.post("/api/v1/accounts", json=data)

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

    @pytest.mark.asyncio
    async def test_list_accounts_filter_by_provider(self, client: AsyncClient):
        """测试按供应商筛选账号"""
        provider_id = await self._create_provider(client)

        # 创建第二个供应商
        p2_data = self.PROVIDER_DATA.copy()
        p2_data["provider_name"] = "test-provider-2"
        p2_resp = await client.post("/api/v1/providers", json=p2_data)
        provider_id_2 = p2_resp.json()["id"]

        # 创建两个账号,分属不同供应商
        d1 = self.ACCOUNT_CREATE_DATA.copy()
        d1["provider_id"] = provider_id
        d1["code"] = "ACCOUNT-TEST-FILTER-1"
        await client.post("/api/v1/accounts", json=d1)

        d2 = self.ACCOUNT_CREATE_DATA.copy()
        d2["provider_id"] = provider_id_2
        d2["account_name"] = "测试账号 2"
        d2["code"] = "ACCOUNT-TEST-FILTER-2"
        await client.post("/api/v1/accounts", json=d2)

        # 筛选
        resp = await client.get(f"/api/v1/accounts?provider_id={provider_id}")
        assert resp.status_code == 200
        result = resp.json()
        # 应该只返回一个账号
        for item in result["items"]:
            assert item["provider_id"] == provider_id

    @pytest.mark.asyncio
    async def test_get_account(self, client: AsyncClient):
        """测试查询账号详情(API Key 脱敏返回)"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

        resp = await client.get(f"/api/v1/accounts/{account_id}")
        assert resp.status_code == 200
        result = resp.json()
        assert result["id"] == account_id
        assert result["api_key"] == ""

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

    @pytest.mark.asyncio
    async def test_update_account(self, client: AsyncClient):
        """测试更新账号"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

        resp = await client.put(
            f"/api/v1/accounts/{account_id}",
            json=self.ACCOUNT_UPDATE_DATA,
        )
        assert resp.status_code == 200
        result = resp.json()
        assert result["account_name"] == self.ACCOUNT_UPDATE_DATA["account_name"]

    @pytest.mark.asyncio
    async def test_update_account_status(self, client: AsyncClient):
        """测试启用/停用账号"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

        # 停用
        resp = await client.patch(
            f"/api/v1/accounts/{account_id}/status",
            json={"status": "disabled"},
        )
        assert resp.status_code == 200
        assert resp.json()["status"] == "disabled"

        # 启用
        resp = await client.patch(
            f"/api/v1/accounts/{account_id}/status",
            json={"status": "active"},
        )
        assert resp.status_code == 200
        assert resp.json()["status"] == "active"

    @pytest.mark.asyncio
    async def test_update_account_status_invalid(self, client: AsyncClient):
        """测试使用无效状态值应返回 400"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

        resp = await client.patch(
            f"/api/v1/accounts/{account_id}/status",
            json={"status": "invalid_status"},
        )
        assert resp.status_code == 400

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

    @pytest.mark.asyncio
    async def test_account_pagination(self, client: AsyncClient):
        """测试账号列表分页"""
        provider_id = await self._create_provider(client)

        # 创建 3 个账号
        for i in range(3):
            d = self.ACCOUNT_CREATE_DATA.copy()
            d["provider_id"] = provider_id
            d["account_name"] = f"测试账号 {i}"
            d["code"] = f"ACCOUNT-TEST-{i:03d}"
            await client.post("/api/v1/accounts", json=d)

        resp = await client.get("/api/v1/accounts?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_delete_account(self, client: AsyncClient):
        """测试删除账号"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

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

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

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

    @pytest.mark.asyncio
    async def test_delete_account_cascade_strategies(self, client: AsyncClient):
        """测试删除账号时级联删除关联的调用策略"""
        provider_id = await self._create_provider(client)
        data = self.ACCOUNT_CREATE_DATA.copy()
        data["provider_id"] = provider_id
        create_resp = await client.post("/api/v1/accounts", json=data)
        account_id = create_resp.json()["id"]

        # 创建关联策略
        strategy_data = {
            "account_id": account_id,
            "strategy_name": "级联删除测试策略",
            "retry_enabled": True,
            "retry_max_attempts": 3,
        }
        await client.post("/api/v1/strategies", json=strategy_data)

        # 删除账号
        resp = await client.delete(f"/api/v1/accounts/{account_id}")
        assert resp.status_code == 200

        # 验证策略也被删除
        resp = await client.get(f"/api/v1/strategies?account_id={account_id}")
        assert resp.status_code == 200
        assert resp.json()["total"] == 0