Files
KiloStar/tests/unit/test_api_agent_template.py
T
zhaoxi 9b73ae4db4 fix: 修复 5 项确定 bug + Provider UX 重做 + 文档统一
Bug fixes:
- fix(dao): AsyncSession.delete 补齐漏掉的 await(provider/user/individual 共 4 处)
- fix(worker): result.data.output → result.output.output(pydantic-ai 1.x API 适配)
- fix(api): 删除 create_worker_from_template 死端点(ORM 字段不匹配必崩)
- fix(api): /provider/test 按 provider_type 分支适配 Anthropic/Gemini/OpenAI 三种协议
- fix(chat): SSE 流式聊天在 distributed 模式 fallback 到非流式,避免 asyncio.Queue 序列化崩溃

Features (previously unstaged):
- feat(provider): Provider 管理页重做(品牌图标、5 种类型、Test Connection、编辑模式)
- feat(provider): 新增 Gemini provider_type 支持
- feat(workflow): Finalize 节点输出 blackboard 摘要 + 失败原因;步骤完成/失败实时推送 SSE
- feat(i18n): regulatory_node 提示词从路由模式改为直接对话模式(中英双语)
- feat(consciousness): dynamic_prompt 支持 locale 国际化
- feat(logs): SystemLogsView 自动刷新 + 暂停按钮

Docs:
- docs: README/README-EN 统一为"开源通用多 Agent 协作平台"口径
- docs: ROADMAP 按 v0.1.x / v0.2.x / v0.3.x 重组
- docs: project.md 重写为结构化项目介绍

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-14 08:49:38 +00:00

130 lines
4.7 KiB
Python

"""``api/agent.py`` persona template 路由:CRUD 鉴权与 node_affinity 校验。"""
from __future__ import annotations
import types
from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI
from httpx import AsyncClient, ASGITransport
from kilostar.api.agent import agent_router, _VALID_AFFINITIES
from kilostar.utils.access import Accessor, TokenData
from kilostar.core.postgres_database.model import UserAuthority
def _fake_user(user_id: str = "alice"):
return TokenData(user_id=user_id, username=user_id)
def _tpl(owner: str = "alice", is_builtin: bool = False):
return types.SimpleNamespace(
template_id="tpl1", name="MyBot", agent_type="ordinary",
description="d", system_prompt="s", provider_title="openai",
model_id="gpt-4", tools=[], tags=[], is_builtin=is_builtin, owner_id=owner,
)
@pytest.fixture
def app(monkeypatch):
import kilostar.utils.check_user.role_check as rc
monkeypatch.setattr(rc, "get_authority", AsyncMock(return_value=UserAuthority.USER))
_app = FastAPI()
_app.include_router(agent_router)
_app.dependency_overrides[Accessor.get_current_user] = lambda: _fake_user()
return _app
def _register_pg(fake_actors, **kwargs):
pg = types.SimpleNamespace(**kwargs)
fake_actors.register("postgres_database", pg)
return pg
# ── node_affinity 校验(纯 pydantic) ─────────────────────────────────────
def test_valid_affinities_accepted():
from kilostar.api.agent import WorkerIndividualCreate
for aff in _VALID_AFFINITIES:
m = WorkerIndividualCreate(
agent_name="x", agent_type="ordinary", description="d",
provider_title="p", model_id="m", persona_id="pid",
output_template={}, bound_skill={}, workspace=[], node_affinity=aff,
)
assert m.node_affinity == aff
def test_invalid_affinity_raises():
from pydantic import ValidationError
from kilostar.api.agent import WorkerIndividualCreate
with pytest.raises(ValidationError):
WorkerIndividualCreate(
agent_name="x", agent_type="ordinary", description="d",
provider_title="p", model_id="m", persona_id="pid",
output_template={}, bound_skill={}, workspace=[], node_affinity="bad",
)
def test_update_invalid_affinity_raises():
from pydantic import ValidationError
from kilostar.api.agent import WorkerIndividualUpdate
with pytest.raises(ValidationError):
WorkerIndividualUpdate(node_affinity="bad")
def test_update_none_affinity_ok():
from kilostar.api.agent import WorkerIndividualUpdate
assert WorkerIndividualUpdate(node_affinity=None).node_affinity is None
# ── template API 路由 ──────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_list_templates(app, fake_actors):
pg = types.SimpleNamespace(
list_templates=types.SimpleNamespace(remote=AsyncMock(return_value=[]))
)
fake_actors.register("postgres_database", pg)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:
r = await c.get("/api/v1/agent/template")
assert r.status_code == 200
assert r.json()["templates"] == []
@pytest.mark.asyncio
async def test_create_template(app, fake_actors):
tpl = _tpl()
pg = types.SimpleNamespace(
add_template=types.SimpleNamespace(remote=AsyncMock(return_value=tpl))
)
fake_actors.register("postgres_database", pg)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:
r = await c.post("/api/v1/agent/template", json={"name": "test"})
assert r.status_code == 200
assert r.json()["template_id"] == "tpl1"
@pytest.mark.asyncio
async def test_delete_template_not_found(app, fake_actors):
pg = types.SimpleNamespace(
get_template=types.SimpleNamespace(remote=AsyncMock(return_value=None))
)
fake_actors.register("postgres_database", pg)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:
r = await c.delete("/api/v1/agent/template/missing")
assert r.status_code == 404
@pytest.mark.asyncio
async def test_delete_other_users_template_forbidden(app, fake_actors):
pg = types.SimpleNamespace(
get_template=types.SimpleNamespace(remote=AsyncMock(return_value=_tpl(owner="bob")))
)
fake_actors.register("postgres_database", pg)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:
r = await c.delete("/api/v1/agent/template/tpl1")
assert r.status_code == 403