Files
group_fqcd_jr/tests/unit/service/test_suitability_service.py
T
lzf_0626 6516ccb385 feat: 第二版——接口契约对齐 docs/05,修复静默故障与数据库基线
相对第一版 46fc976 的完整变更。组员迁移对照表见 docs/20。

一、对外契约对齐 docs/05(破坏性,共 4 处,组员需按 docs/20 调整)
1) 配置发布端点改为文档规定的复数资源名:submit→validations、
   approve→reviews(需 body decision)、activate→activations、
   rollback→rollbacks;第一版这 4 个动词式路径 docs/05 从未定义过。
2) 错误码由 8 个笼统码改为 15 个具体语义码(FORBIDDEN→AGENT_PERMISSION_DENIED、
   UNAUTHORIZED→AUTHENTICATION_REQUIRED、CONFLICT→RESOURCE_VERSION_CONFLICT、
   RESOURCE_NOT_FOUND→RUN_NOT_FOUND/SESSION_NOT_FOUND 等),
   输入类错误状态码 400→422。
3) POST /api/v1/agent-runs 与 GET /api/v1/agent-runs/{run_id} 统一为
   {data, meta} 信封(data 内字段名与语义未变)。
4) 错误响应体统一为 {error:{code,message,retryable,field_errors}, meta:{trace_id}},
   不再返回 FastAPI 默认的 {"detail": ...}。

二、数据库基线与约束
新增 39 张表的基线迁移(链根)与联合唯一键纠偏(4 张表、删 8 增 4,幂等收敛);
撤下 config_release 的双人复核 CHECK(应用层已允许自审,审核节点保留,
自审如实写入 reviewer_id);记忆 active key 生成列与唯一键;
activate 开始记录 supersedes_release_id 使版本链可追溯。
docs/00 基线未修改,未重命名或删除任何表与字段。

三、修复会静默出错或无报错的缺陷
- 跑完集成测试后平台会静默失去生效配置:清理只删自己创建的版本,却没有恢复被它
  顶成 superseded 的原生效版本,且审计一并删除因而完全无痕,表现为所有工具被拒
  但没有任何报错。已修清理逻辑并加恢复。
- Worker 单轮异常导致进程退出;记忆抽取调用方的“事务已开始”异常;
  召回缓存丢失 degraded 标记;连接时区未生效导致 created_at/updated_at 差 8 小时;
  .env 与 os.getenv 密钥来源分裂导致“没有可用的已批准模型端点”。
- 记忆信号识别漏判与跨键误命中;SSE 未带 Accept 的协商行为。

四、功能补齐
记忆链路 P1/P2/P3(抽取、受控词表、召回与缓存、生命周期级联及投影事件)、
fin_* 场内交易只读 ORM 层、agent_intent_config 状态流转并在运行期真正生效、
限流(Redis 固定窗口、故障一律放行)、游标校验、trace_id 中间件、
示例业务 Agent fund_query_demo 与一键端到端验证脚本,以及审计/指纹/迁移状态工具。

五、文档与验证
新增 docs/19(业务 Agent 接入实操)、docs/20(第一版迁移指南)与 docs/evidence 证据;
docs/01/02/06/08/09/17 同步实现现状。

验证结果:ruff 通过、mypy 103 文件无错、unit+contract 447 passed、
integration 29 passed、acceptance_check --production 7 PASS、
demo_agent_e2e 9/9 PASS(含失败关闭反证)。
2026-09-10 15:55:54 +08:00

239 lines
8.4 KiB
Python

"""适当性校验(B2)单元测试:权威风险等级、测评有效期、专业投资者规则、越权与审计。"""
from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
from pydantic import ValidationError
from app.core.contracts import RequestContext
from app.core.errors import ForbiddenAgentError
from app.service.suitability_service import (
SuitabilityService,
SuitabilityToolInput,
suitability_tool_handler,
)
NOW = datetime(2026, 9, 9, 10, 0, tzinfo=UTC)
VALID_UNTIL = NOW + timedelta(days=30)
class FakeResult:
def __init__(self, row: dict[str, Any] | None) -> None:
self._row = row
def mappings(self) -> "FakeResult":
return self
def first(self) -> dict[str, Any] | None:
return self._row
class FakeSession:
"""同时支持只读查询与审计写入的最小替身。"""
def __init__(self, row: dict[str, Any] | None, added: list[Any]) -> None:
self._row = row
self.added = added
async def __aenter__(self) -> "FakeSession":
return self
async def __aexit__(self, *args: object) -> None:
return None
def begin(self) -> "FakeSession":
return self
async def execute(self, *args: object, **kwargs: object) -> FakeResult:
return FakeResult(self._row)
def add(self, item: Any) -> None:
self.added.append(item)
def authority_row(**overrides: Any) -> dict[str, Any]:
row: dict[str, Any] = {
"is_professional_investor": 0,
"professional_investor_status": "未申请",
"investor_type": "C3",
"assessed_at": NOW - timedelta(days=5),
"valid_until": VALID_UNTIL,
}
row.update(overrides)
return row
def query(**overrides: Any) -> SuitabilityToolInput:
values: dict[str, Any] = {"customer_id": "7", "product_risk_level": 3}
values.update(overrides)
return SuitabilityToolInput.model_validate(values)
def context(**overrides: Any) -> RequestContext:
values: dict[str, Any] = {"user_id": "7", "trace_id": "trace-suitability"}
values.update(overrides)
return RequestContext(**values)
def service_with_row(
row: dict[str, Any] | None, added: list[Any] | None = None
) -> SuitabilityService:
sink = added if added is not None else []
return SuitabilityService(session_factory=lambda: FakeSession(row, sink))
async def test_authority_risk_level_replaces_caller_supplied_level() -> None:
decision = await service_with_row(authority_row(investor_type="C5")).evaluate(
query(product_risk_level=5), context(), now=NOW
)
assert decision.allowed is True
assert decision.reason_code == "SUITABLE"
assert decision.customer_risk_level == 5
assert decision.risk_level_source == "fin_risk_assessment"
@pytest.mark.parametrize("forged", [{"customer_risk_level": 5}, {"professional_investor": True},
{"assessment_expires_at": "2099-01-01T00:00:00Z"}])
def test_caller_cannot_declare_risk_facts(forged: dict[str, Any]) -> None:
with pytest.raises(ValidationError):
query(**forged)
async def test_insufficient_authority_level_is_denied() -> None:
decision = await service_with_row(authority_row(investor_type="C1")).evaluate(
query(product_risk_level=2), context(), now=NOW
)
assert decision.allowed is False
assert decision.reason_code == "RISK_LEVEL_MISMATCH"
assert decision.requires_recording is True
async def test_expired_assessment_is_denied_even_for_eligible_level() -> None:
row = authority_row(investor_type="C5", valid_until=NOW - timedelta(seconds=1))
decision = await service_with_row(row).evaluate(query(product_risk_level=1), context(), now=NOW)
assert decision.allowed is False
assert decision.reason_code == "ASSESSMENT_EXPIRED"
assert decision.customer_risk_level == 5
async def test_missing_valid_until_is_treated_as_unusable() -> None:
decision = await service_with_row(authority_row(valid_until=None)).evaluate(
query(), context(), now=NOW
)
assert decision.allowed is False
assert decision.reason_code == "ASSESSMENT_EXPIRED"
async def test_no_assessment_is_denied() -> None:
decision = await service_with_row(authority_row(investor_type=None)).evaluate(
query(), context(), now=NOW
)
assert decision.allowed is False
assert decision.reason_code == "ASSESSMENT_MISSING"
assert decision.customer_risk_level is None
async def test_unknown_customer_is_denied() -> None:
decision = await service_with_row(None).evaluate(query(), context(), now=NOW)
assert decision.allowed is False
assert decision.reason_code == "CUSTOMER_NOT_FOUND"
@pytest.mark.parametrize("investor_type", ["X9", "C6", "C0", ""])
async def test_invalid_investor_type_fails_closed(investor_type: str) -> None:
decision = await service_with_row(authority_row(investor_type=investor_type)).evaluate(
query(), context(), now=NOW
)
assert decision.allowed is False
assert decision.reason_code == "RISK_LEVEL_INVALID"
async def test_certified_professional_investor_gets_level_exemption_with_disclosure() -> None:
row = authority_row(
investor_type="C1",
is_professional_investor=1,
professional_investor_status="已认定",
)
decision = await service_with_row(row).evaluate(
query(product_risk_level=5, product_requires_disclosure=True),
context(),
now=NOW,
)
assert decision.allowed is True
assert decision.reason_code == "SUITABLE_PROFESSIONAL_INVESTOR"
assert decision.professional_investor is True
assert decision.required_disclosure is True
assert decision.requires_confirmation is True
assert decision.requires_recording is True
@pytest.mark.parametrize("status", ["未申请", "审核中", "已拒绝"])
async def test_uncertified_professional_status_does_not_exempt_level(status: str) -> None:
row = authority_row(
investor_type="C1", is_professional_investor=1, professional_investor_status=status
)
decision = await service_with_row(row).evaluate(
query(product_risk_level=5), context(), now=NOW
)
assert decision.allowed is False
assert decision.reason_code == "RISK_LEVEL_MISMATCH"
async def test_professional_investor_cannot_bypass_expired_assessment() -> None:
row = authority_row(
investor_type="C5",
is_professional_investor=1,
professional_investor_status="已认定",
valid_until=NOW - timedelta(days=1),
)
decision = await service_with_row(row).evaluate(query(product_risk_level=1), context(), now=NOW)
assert decision.allowed is False
assert decision.reason_code == "ASSESSMENT_EXPIRED"
async def test_assessment_of_other_customer_is_forbidden() -> None:
service = service_with_row(authority_row())
with pytest.raises(ForbiddenAgentError):
await service.evaluate(query(customer_id="9"), context(customer_ids=("8",)), now=NOW)
async def test_assigned_customer_is_allowed_and_admin_is_exempt() -> None:
service = service_with_row(authority_row())
assigned = await service.evaluate(query(customer_id="9"), context(customer_ids=("9",)), now=NOW)
assert assigned.customer_risk_level == 3
admin = await service.evaluate(
query(customer_id="9"), context(roles=("admin",), permissions=()), now=NOW
)
assert admin.customer_risk_level == 3
async def test_decision_is_audited_with_authority_source() -> None:
added: list[Any] = []
service = service_with_row(authority_row(investor_type="C2"), added)
decision = await service.evaluate_and_audit(query(product_risk_level=4), context(), now=NOW)
assert decision.allowed is False
assert len(added) == 1
detail = added[0].detail
assert detail["reason_code"] == "RISK_LEVEL_MISMATCH"
assert detail["customer_risk_level"] == 2
assert detail["risk_level_source"] == "fin_risk_assessment"
assert detail["professional_investor"] is False
assert "answers" not in detail
async def test_tool_handler_uses_same_service(
monkeypatch: pytest.MonkeyPatch,
) -> None:
added: list[Any] = []
sink = added
monkeypatch.setattr(
"app.service.suitability_service.SessionFactory",
lambda: FakeSession(authority_row(investor_type="C1"), sink),
)
result = await suitability_tool_handler(query(product_risk_level=5), context())
assert result["allowed"] is False
assert result["reason_code"] == "RISK_LEVEL_MISMATCH"
assert result["customer_risk_level"] == 1
assert len(added) == 1