fntests.py 3.2 KB
"""函数的测试用例:编辑时一键全跑,发布前自动跑(没过就不让发布)。

用例 = {name, inputs, expect};expect 的键是输出里的路径(result、result.level、value、output.紧急程度……),
值是期望值。数字按 1e-6 的误差比较,其余按字符串比较("1" 和 1 算相等)。
AI 分析函数的结论不确定,不跑用例(编辑器里也不给加);聚合函数要连业务库,照常跑。
"""
from __future__ import annotations

from typing import Any

from fastapi import HTTPException

from . import service

SKIP = ("ai",)


def _get(v: Any, path: str) -> Any:
    from ..capability.actions import lookup
    return lookup(path, v if isinstance(v, dict) else {"result": v})


def _same(got: Any, want: Any) -> bool:
    try:
        if isinstance(want, bool) or isinstance(got, bool):
            return str(got).lower() in ("true", "1", "是") if str(want).lower() in ("true", "1", "是") \
                else str(got).lower() in ("false", "0", "否", "none", "")
        return abs(float(got) - float(want)) < 1e-6
    except (TypeError, ValueError):
        return str(got if got is not None else "") == str(want if want is not None else "")


def run(fn: dict, tests: list[dict] | None = None) -> list[dict]:
    """跑一个函数的用例(默认用它自己 spec 里的),返回每条的结果。"""
    from ..capability import builtins
    cat = (fn.get("spec") or {}).get("category")
    out = []
    for t in (tests if tests is not None else (fn.get("spec") or {}).get("tests")) or []:
        item = {"name": t.get("name") or "", "ok": False, "got": {}, "error": ""}
        if cat in SKIP:
            item.update(ok=True, error="AI 分析的结论不固定,不跑用例")
            out.append(item)
            continue
        try:
            with service.draft_runtime():
                res = builtins.eval_function(fn, t.get("inputs") or {}, draft=True)
            bad = []
            for path, want in (t.get("expect") or {}).items():
                got = _get(res, path)
                item["got"][path] = got
                if not _same(got, want):
                    bad.append(f"{path} 期望 {want!r},实际 {got!r}")
            item["ok"] = not bad
            item["error"] = ";".join(bad)
        except HTTPException as e:
            item["error"] = str(e.detail)
        except Exception as e:  # noqa: BLE001
            item["error"] = str(e)[:300]
        out.append(item)
    return out


def _gate(diff: dict, concept_ids: list[str] | None = None) -> tuple[bool, str]:
    """发布闸门:这次要发布的函数里,有用例没过的就拦下。"""
    ids = {x["id"] for k in ("added", "changed") for x in diff.get(k) or [] if x.get("kind") == "function"}
    failed = []
    for cid in ids:
        try:
            fn = service.get_concept(cid)
        except HTTPException:
            continue
        for r in run(fn):
            if not r["ok"]:
                failed.append(f"「{fn['name']}」的{r['name']}:{r['error'][:80]}")
    if failed:
        return False, "函数的测试用例没过 —— " + ";".join(failed[:4]) + ("……" if len(failed) > 4 else "")
    return True, ""


service.register_publish_gate(_gate)