Files
writer-work-flow/apps/api/tests/test_gateway_fallback_wiring.py
Yaojia Wang 765dbdfbd4 feat: M4 文风 + M5 生成/多provider/Skill + Kimi Code 订阅接入 + 本地联调修复
M4(文风): style-auditor 双轨(提取指纹/漂移第四审)+ jobs 长任务框架(zombie reaper) + 回炉 refine + GET /style read-back。
M5(生成+扩展): worldbuilder/character-gen(入库 continuity 409 gate + partition_writes 白名单 + schema→JSONB 形变);
  网关多 provider 回退链/熔断/能力降级(Anthropic/Gemini 适配器);Skill registry + 表权限沙箱 + 规则;
  前端 角色生成器/世界观/Codex/规则页/技能库/⌘K 命令面板。
K1(Kimi Code 订阅接入): OAuth device-flow(kimi-code)+ 静态 Console key(kimi-code-key)两路径;
  coding 端点 KimiCLI 伪造头(实测 UA allow-list 门禁,缺则 403)+ JSON 模式结构化(thinking ⊥ tool_choice)。
本地联调修复: CORS 中间件;assemble 注入 premise+「写第N章」指令(修空 prompt 400);
  GET /outline·/draft read-back + 大纲/工作台/审稿页重载;写页 client/server 常量边界 + notFound 健壮化;
  字数 toLocaleString locale 水合;审稿页终稿从已存草稿 seed(修 accept 422)。
门禁: backend ruff/mypy(157)/alembic 无漂移/pytest 451 · frontend lint/tsc/vitest/build。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 10:39:58 +02:00

101 lines
3.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""T5.2/T5.4 接线:`build_gateway_for_tier` 据 DB tier_routing 装配多 provider 回退链。
不联网:只断言网关被装配了**多个适配器** + 注入了回退链解析器chain_resolver
故链长 > 1。真实回退/降级行为由 packages/llm_gateway 单测 + T5.7 E2E 覆盖。
"""
from __future__ import annotations
import os
import pytest
from fakes_projects import FakeSession
from fakes_providers import FakeCredentialStore
from ww_api.services.credentials import STUB_OWNER_ID, StoredRouting
# 真 Fernet key测试加解密凭据用仅本测试非生产密钥
_ENC_KEY = "imB6TEcV2AzlpXjR4NjTgK_9Zt-OoqaLFQc3XqBQ0CQ="
def _store_with_creds(*providers: str) -> FakeCredentialStore:
from ww_api.security.credentials import encrypt_api_key
store = FakeCredentialStore()
for p in providers:
store.creds[(STUB_OWNER_ID, p)] = encrypt_api_key("sk-test", key=_ENC_KEY)
return store
@pytest.mark.asyncio
async def test_build_gateway_wires_fallback_chain_with_multiple_adapters() -> None:
os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
from ww_config import get_settings
get_settings.cache_clear()
from ww_api.services.project_deps import build_gateway_for_tier
store = _store_with_creds("deepseek", "kimi")
store.routing["writer"] = StoredRouting(
tier="writer", provider="deepseek", model="deepseek-chat", fallback=["kimi:moonshot-v1-8k"]
)
gateway = await build_gateway_for_tier(FakeSession(), store, "writer")
# 两个 provider 的适配器都装配进网关 → 回退链可绕过首个失败者。
assert set(gateway._adapters) == {"deepseek", "kimi"} # noqa: SLF001
# chain_resolver 注入 → 链长 2去重保序
chain = gateway._resolve_chain("writer") # noqa: SLF001
assert [r.provider for r in chain] == ["deepseek", "kimi"]
@pytest.mark.asyncio
async def test_build_gateway_single_provider_still_works() -> None:
"""无 fallback 的路由行单元素链M1 行为不变,向后兼容)。"""
os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
from ww_config import get_settings
get_settings.cache_clear()
from ww_api.services.project_deps import build_gateway_for_tier
store = _store_with_creds("deepseek")
store.routing["analyst"] = StoredRouting(
tier="analyst", provider="deepseek", model="deepseek-chat", fallback=[]
)
gateway = await build_gateway_for_tier(FakeSession(), store, "analyst")
assert set(gateway._adapters) == {"deepseek"} # noqa: SLF001
chain = gateway._resolve_chain("analyst") # noqa: SLF001
assert len(chain) == 1
@pytest.mark.asyncio
async def test_build_gateway_no_routing_row_falls_back_to_global_default() -> None:
"""无 DB 路由行 → 退回全局 resolve_route单 provider"""
os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
from ww_config import get_settings
get_settings.cache_clear()
from ww_api.services.project_deps import build_gateway_for_tier
store = _store_with_creds("deepseek") # 无 routing 行
gateway = await build_gateway_for_tier(FakeSession(), store, "writer")
assert "deepseek" in gateway._adapters # noqa: SLF001
@pytest.mark.asyncio
async def test_build_gateway_no_usable_credentials_raises_503() -> None:
os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
from ww_config import get_settings
get_settings.cache_clear()
from ww_api.services.project_deps import build_gateway_for_tier
from ww_shared import AppError, ErrorCode
store = FakeCredentialStore() # 无任何凭据
store.routing["writer"] = StoredRouting(
tier="writer", provider="deepseek", model="deepseek-chat", fallback=["kimi:moonshot-v1-8k"]
)
with pytest.raises(AppError) as exc:
await build_gateway_for_tier(FakeSession(), store, "writer")
assert exc.value.code == ErrorCode.LLM_UNAVAILABLE