test_four_tuple.py
15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""四元组改造的新能力:决策表、函数试跑、画布、版本对比、问数 Agent、一句话起草、MCP 服务页、业务角色。
复用 test_platform 的夹具:SQLite 元数据库 + 假业务库 + 打桩 LLM。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).parent))
from app.core import llm # noqa: E402
from test_platform import build_basics, env, make_action # noqa: E402,F401
# =========================== 决策表 ===========================
def test_决策表单元格写法():
from app.kernel.decision import cell_expr
assert cell_expr("x", "") == "" and cell_expr("x", "-") == ""
assert cell_expr("x", "> 3") == "(x > 3)"
assert cell_expr("x", ">= 0 and < 3") == "(x >= 0) and (x < 3)"
assert cell_expr("x", "[0, 3]") == "(x >= 0 and x <= 3)"
assert cell_expr("x", "0..3") == "(x >= 0 and x <= 3)"
assert cell_expr("x", "A") == "x == 'A'"
assert cell_expr("x", "'A'") == "x == 'A'"
assert cell_expr("x", 12) == "x == 12"
assert cell_expr("x", "in ['A', 'B']") == "x in ['A', 'B']"
def test_决策表命中策略与默认值():
from app.kernel import decision
spec = decision.normalize({
"inputs": [{"name": "delta"}, {"name": "grade"}], "outputs": ["score", "tag"],
"rows": [{"when": {"delta": "> 3"}, "then": {"score": 2, "tag": "好"}},
{"when": {"delta": "> 0", "grade": "A"}, "then": {"score": "=delta * 10", "tag": "中"}},
{"when": {"delta": "> 0"}, "then": {"score": 1, "tag": "一般"}}],
"default": {"score": 0, "tag": "无"}})
assert decision.evaluate(spec, {"delta": 5, "grade": "B"})["result"] == {"score": 2, "tag": "好"}
r = decision.evaluate(spec, {"delta": 0.5, "grade": "A"})
assert r["result"] == {"score": 5.0, "tag": "中"} and r["matched"] == [2]
assert decision.evaluate(spec, {"delta": -1, "grade": "A"})["result"] == {"score": 0, "tag": "无"}
spec["hit_policy"] = "collect"
assert [x["tag"] for x in decision.evaluate(spec, {"delta": 5, "grade": "A"})["result"]] == ["好", "中", "一般"]
with pytest.raises(decision.DecisionError):
decision.normalize({"inputs": ["x"], "outputs": ["y"], "rows": [{"when": {"x": "> > 3"}}]})
with pytest.raises(decision.DecisionError):
decision.normalize({"inputs": [], "outputs": ["y"]})
def test_决策表是函数并能被调用(env):
from app.capability import registry
from app.kernel import service
service.create_concept("function", "达成分级", spec={
"category": "decision", "inputs": [{"name": "rate"}], "outputs": [{"name": "level"}],
"rows": [{"when": {"rate": ">= 1"}, "then": {"level": "A"}},
{"when": {"rate": "< 1"}, "then": {"level": "B"}}]})
service.publish("决策表")
assert registry.call_function("decision.eval", {"table": "达成分级", "inputs": {"rate": 1.2}})["result"] == {"level": "A"}
out = registry.call_function("function.eval", {"name": "达成分级", "args": {"inputs": {"rate": 0.3}}})
assert out["result"] == {"level": "B"} and out["function"]["category"] == "decision"
ov = registry.call_function("ontology.overview", {})
assert ov["concepts"]["decision"][0]["name"] == "达成分级"
# =========================== 试跑 / 画布 / 版本 ===========================
def test_试跑草稿不用发布(env):
from fastapi.testclient import TestClient
from app.main import app
b = build_basics(env["ds_id"])
c = TestClient(app)
r = c.post("/api/kernel/try", json={"kind": "function", "spec": {
"category": "rule", "expression": "max(0, ceil(t * d - o))"}, "args": {"vars": {"t": 0.15, "d": 100, "o": 12}}})
assert r.status_code == 200 and r.json()["result"] == 3
r = c.post("/api/kernel/try", json={"kind": "function", "spec": {
"category": "decision", "inputs": ["x"], "outputs": ["y"],
"rows": [{"when": {"x": "> 0"}, "then": {"y": "正"}}], "default": {"y": "非正"}},
"args": {"inputs": {"x": -2}}})
assert r.json()["result"] == {"y": "非正"}
# 聚合函数的工作副本可以直接试跑取数
r = c.post(f"/api/kernel/concepts/{b['metric']['id']}/try", json={"args": {"dimensions": ["网点"]}})
assert r.status_code == 200 and len(r.json()["rows"]) == 3
# 动作试跑只预览、不提议
a = make_action(b["ot"]["id"])
r = c.post(f"/api/kernel/concepts/{a['id']}/try", json={"args": {"reason": "x"}, "object_key": "1"})
assert r.status_code == 200 and r.json()["effects"][0]["tool"] == "object.write"
from app.capability import actions
assert actions.list_runs() == []
def test_画布数据与布局不算修改(env):
from fastapi.testclient import TestClient
from app.main import app
from app.kernel import service
b = build_basics(env["ds_id"])
a = make_action(b["ot"]["id"])
store2 = service.create_concept("object_type", "区域")
service.create_concept("link_type", "属于", spec={"from_type": b["ot"]["id"], "to_type": store2["id"]})
c = TestClient(app)
g = c.get("/api/kernel/graph").json()
kinds = {n["id"]: n["type_key"] for n in g["nodes"]}
assert kinds[b["metric"]["id"]] == "aggregate" and kinds[a["id"]] == "action"
assert any(e["kind"] == "link" and e["label"] == "属于" for e in g["edges"])
assert any(e["kind"] == "owns" and e["target"] == a["id"] for e in g["edges"])
service.publish("加关系")
assert c.put("/api/kernel/layout", json={"positions": {b["ot"]["id"]: {"x": 10, "y": 20}}}).json()["saved"] == 1
assert service.pending_diff() == {"added": [], "removed": [], "changed": []}
assert service.get_concept(b["ot"]["id"])["spec"]["ui"]["pos"] == {"x": 10.0, "y": 20.0}
# 表单保存不带 ui,也不会冲掉画布位置
service.update_concept(b["ot"]["id"], description="改")
assert service.get_concept(b["ot"]["id"])["spec"]["ui"]["pos"]["x"] == 10.0
def test_动作随本体一起发布_版本对比_回滚(env):
from app.capability import actions, defs
from app.kernel import service
b = build_basics(env["ds_id"]) # 第 1 版
a = make_action(b["ot"]["id"]) # 第 2 版:加了动作
assert defs.find("mark_follow", "action")["status"] == "published"
service.update_concept(b["metric"]["id"], description="新口径", synonyms=["销售额", "营收"])
service.publish("第三版")
cmp = service.compare_revisions(1, 3)
assert [x["name"] for x in cmp["added"]] == ["mark_follow"] and cmp["added"][0]["type_key"] == "action"
ch = next(x for x in cmp["changed"] if x["name"] == "成交金额")
fields = {c["field"]: c for c in ch["changes"]}
assert fields["description"]["after"] == "新口径" and "营收" in fields["synonyms"]["after"]
service.rollback(1) # 回到没有动作的版本
with pytest.raises(HTTPException):
actions.prepare(a["id"], {"reason": "x"}, "1")
from fastapi.testclient import TestClient
from app.main import app
r = TestClient(app).get("/api/kernel/revisions/compare?from=0&to=1")
assert r.status_code == 200 and len(r.json()["added"]) == 3
# =========================== 问数 Agent ===========================
def test_问数Agent_命中指标走确定性取数(env, monkeypatch):
from app.capability import registry
b = build_basics(env["ds_id"])
calls = []
def fake(msgs, **k):
calls.append(msgs[0]["content"])
return {"route": "metric", "metric": "成交金额", "dimensions": ["网点"]}
monkeypatch.setattr(llm, "chat_json", fake)
events = []
out = registry.call_function("data.ask", {"question": "各网点的销售额"}, emit=events.append)
assert out["route"] == "metric" and len(out["rows"]) == 3 and out["run_id"] > 0
assert "成交金额" in calls[0] and "可拆分维度:网点" in calls[0]
assert events[0]["type"] == "data_route" and events[0]["route"] == "metric"
assert out["calibre"]["name"] == "达标判定" and b["metric"]["name"] == "成交金额"
def test_问数Agent_指标失败降级到SQL并做体检(env, monkeypatch):
from app.data_agent import agent
from app.text2sql import pipeline
build_basics(env["ds_id"])
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: {"route": "metric", "metric": "成交金额",
"dimensions": ["不存在的维度"]})
seen = {}
def fake_run(ds_id, q, history=None, summarize=True):
seen["q"] = q
yield {"type": "execute", "sql": "SELECT 1", "truncated": False}
yield {"type": "rows", "columns": ["v"], "rows": [[None]]}
yield {"type": "done", "run_id": 9, "outcome": "ok"}
monkeypatch.setattr(pipeline, "run_ask", fake_run)
out = agent.ask("上个月的销售额")
assert out["route"] == "sql" and out["run_id"] == 9
assert any("改为生成 SQL" in n for n in out["notes"])
assert any("NULL" in n for n in out["notes"]) # 体检:一行全空
assert "本体提示" in seen["q"] and "解析为" in seen["q"] # 时间按本体周期解析后交给 SQL 路
def test_问数Agent_没有指标不花选路调用(env, monkeypatch):
from app.data_agent import agent
from app.text2sql import pipeline
def boom(*a, **k):
raise AssertionError("没有命中指标时不该调用选路模型")
monkeypatch.setattr(llm, "chat_json", boom)
monkeypatch.setattr(pipeline, "run_ask", lambda *a, **k: iter([
{"type": "rows", "columns": ["n"], "rows": []}, {"type": "done", "run_id": 3}]))
out = agent.ask("一共有多少条明细")
assert out["route"] == "sql" and any("没有返回任何行" in n for n in out["notes"])
def test_问数的指标来自本体(env):
from app.kernel import service
from app.text2sql import semantic
b = build_basics(env["ds_id"])
ms = semantic.list_metrics(env["ds_id"])
assert [m["name"] for m in ms] == ["成交金额"]
assert ms[0]["expression"] == "SUM(amount)" and ms[0]["base_model_id"] > 0
assert ms[0]["id"] == b["metric"]["id"] and "销售额" in ms[0]["synonyms"]
service.deprecate_concept(b["metric"]["id"])
service.publish("下线指标")
assert semantic.list_metrics(env["ds_id"]) == []
# =========================== 一句话起草 ===========================
def test_一句话起草_校验不过自动修一次(env, monkeypatch):
from app.kernel import draft, service
service.create_concept("object_type", "网点", spec={"properties": [{"name": "编号", "is_key": True}]})
replies = iter([
{"kind": "function", "category": "rule", "name": "差额", "object_type": "网点", "reason": "给定输入算一个数"},
{"name": "差额", "spec": {"expression": "import os"}}, # 第一次写坏
{"name": "差额", "description": "还差多少", "spec": {"expression": "max(0, target - actual)",
"object_type": "网点"},
"samples": [{"input": {"target": 10, "actual": 7}}]},
])
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: next(replies))
evs = list(draft.generate("算一下离目标还差多少"))
types = [e["type"] for e in evs]
assert "classify" in types and "entities" in types
vals = [e for e in evs if e["type"] == "validate"]
assert [v["ok"] for v in vals] == [False, True]
done = evs[-1]
assert done["type"] == "done" and done["ok"]
assert done["draft"]["spec"]["category"] == "rule"
assert done["draft"]["spec"]["object_type"] == service.find("网点", "object_type")["id"]
assert done["samples"][0]["input"]["target"] == 10
assert service.find("差额", "function") is None # 起草不落库
# =========================== MCP 服务页 ===========================
def test_MCP在线调用写审计_提议只进审批(env):
from fastapi.testclient import TestClient
from app.capability import actions
from app.main import app
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
c = TestClient(app)
tools = c.get("/api/cap/mcp/tools").json()
names = {t["name"] for t in tools["tools"]}
assert {"data_ask", "execute_function", "impact_analysis", "traverse_link", "execute_runcard",
"propose_action", "get_action_status"} <= names
assert not {n for n in names if "approve" in n or "reject" in n} # 目录里没有审批工具
# 老名字 function_eval 仍可调用(别名),审计记成新名字
r = c.post("/api/cap/mcp/call/function_eval", json={"args": {"name": "达标判定",
"args": {"vars": {"actual": 2, "target": 1}}}})
assert r.json()["ok"] and r.json()["result"]["result"] is True
r = c.post("/api/cap/mcp/call/nope", json={"args": {}})
assert not r.json()["ok"]
r = c.post("/api/cap/mcp/call/propose_action", json={"args": {
"action": "mark_follow", "params": {"reason": "外部 Agent 建议"}, "object_key": "1", "reason": "测"}},
headers={"X-User-Id": "operator"})
run = r.json()["result"]
assert run["status"] == "pending_approval" and run["initiator_kind"] == "ai"
st = c.post("/api/cap/mcp/call/get_action_status", json={"args": {"run_id": run["id"]}}).json()
assert st["result"]["status"] == "pending_approval"
logs = c.get("/api/cap/mcp/logs").json()
assert len(logs) == 4 and any("调用失败" in x["summary"] for x in logs)
assert actions.get(run["id"])["status"] == "pending_approval" # Agent 不能批
# =========================== 业务角色 ===========================
def test_业务角色在成员与角色里维护(env):
from fastapi.testclient import TestClient
from app.main import app
from app.sop import spec as sop_spec
c = TestClient(app)
assert c.post("/api/gov/roles", json={"name": "店长", "description": "门店负责人"},
headers={"X-User-Id": "viewer"}).status_code == 403
c.post("/api/gov/roles", json={"name": "店长", "description": "门店负责人"})
assert [r["name"] for r in c.get("/api/gov/roles").json()] == ["店长"]
assert "店长" in c.get("/api/kernel/meta").json()["roles"]
s = sop_spec.normalize({"steps": [
{"id": "a", "type": "human_task", "title": "巡店", "role": "店长", "next": "b"},
{"id": "c", "type": "human_task", "title": "复核", "role": "不存在的角色", "next": "b"},
{"id": "b", "type": "end"}]})
warns = " ".join(sop_spec.validate(s)["warnings"])
assert "不存在的角色" in warns and "「店长」" not in warns
def test_数据源提议的关系带上两端对象(env):
"""内省出来的关联基数是大写的 N:1,曾经因此校验失败、关系两端变成空的。"""
from app.kernel import propose, schema
assert schema.normalize_spec("link_type", {"cardinality": "N:1"})["cardinality"] == "n:1"
assert schema.normalize_spec("link_type", {"cardinality": "many_to_many"})["cardinality"] == "n:n"
links = [p for p in propose.datasource_proposals(env["ds_id"]) if p["kind"] == "link_type"]
for p in links:
spec = schema.normalize_spec("link_type", p["spec"])
assert spec["from_type"] and spec["to_type"]