"""
基线测试：KPI创建接口缺少必填元数据字段时返回 HTTP 422。

场景：POST /api/cma/kpis 请求体不传 formula 字段（数据治理规则2: 元数据必填），
期望返回 HTTP 422，且 errors 中包含 formula 相关提示。
"""
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session

from tests.conftest import create_test_user, get_token_for_user, auth_header


class TestKpi422Baseline:
    """KPI创建缺少必填元数据字段 → 422 基线测试"""

    def test_create_kpi_missing_formula_returns_422(self, client: TestClient, db: Session):
        """不传 formula 字段时，创建KPI返回 422"""
        create_test_user(db)
        token = get_token_for_user(client)

        # 构造请求体：其余必填字段齐全，唯独不传 formula
        payload = {
            "kpi_code": "F_BASELINE_001",
            "kpi_name": "基线测试收入指标",
            "dimension": "finance",
            "target_value": 1000000,
            "unit": "元",
            # 注意：故意不传 formula（必填元数据字段）
            "data_source": "测试系统",
            "data_owner": "测试管理员",
        }
        resp = client.post("/api/cma/kpis", headers=auth_header(token), json=payload)
        assert resp.status_code == 422, f"期望422，实际 {resp.status_code}: {resp.text}"

        # 校验错误信息中包含 formula 字段
        # 注意：FastAPI HTTPException(detail=dict) 时响应体为 {"detail": {...}}
        body = resp.json()
        detail = body.get("detail", {})
        errors = detail.get("errors", []) if isinstance(detail, dict) else []
        assert any("formula" in e for e in errors), f"errors 应提及 formula: {body}"
