test_platform.py
25.7 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""本体平台端到端测试:内核(四元组元素/发布/回滚/版本对比/链接/取数/对象/决策表/试跑/一句话起草)、
能力(动作审批/四眼/撤销/任务)、问数 Agent、SOP(校验/试运行/发布审核/正式运行挂起与恢复)、
统一提问、MCP、评测、通用性检查、接口权限。
元数据库与业务库都用 SQLite,LLM 全部打桩,不依赖外部服务。
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
import pytest
from fastapi import HTTPException
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
from app.core import db as core_db, identity, llm # noqa: E402
from app.core.config import DEFAULT_RUNTIME # noqa: E402
from app.text2sql import introspect, semantic # noqa: E402
from test_sql_pipeline import FakeConnector # noqa: E402
ROOT = Path(__file__).parent.parent
@pytest.fixture()
def env(tmp_path, monkeypatch):
from app import bootstrap
from app.capability import models as _m1 # noqa: F401
from app.evals import models as _m2 # noqa: F401
from app.governance import models as _m3 # noqa: F401
from app.kernel import models as _m4 # noqa: F401
from app.agents import models as _m5 # noqa: F401
from app.sop import models as _m6 # noqa: F401
from app.text2sql import models as _m7 # noqa: F401
from app.memory import models as _m8 # noqa: F401
from app.watch import models as _m9 # noqa: F401
meta = create_engine(f"sqlite:///{tmp_path / 'meta.db'}", future=True)
core_db.Base.metadata.create_all(meta)
with Session(meta) as s:
for k, v in DEFAULT_RUNTIME.items():
# 发布后自动同步走后台线程,测试里关掉,需要时显式调用 pipeline
s.add(core_db.Config(cfg_key=k, cfg_value="0" if k == "PIPELINE_AUTO_SYNC" else v))
s.commit()
monkeypatch.setattr(core_db, "engine", meta)
conn = FakeConnector(tmp_path / "biz.db")
monkeypatch.setattr(semantic, "connector_for", lambda ds_id, fresh=False: conn)
monkeypatch.setattr(semantic.crypto, "encrypt", lambda p: f"enc:{p}")
monkeypatch.setattr(semantic.crypto, "decrypt", lambda t: t[4:] if t.startswith("enc:") else "")
bootstrap.setup()
from app.governance import users
from app.kernel import linker, service
from app.sop import engine
users.seed()
users.invalidate()
service.invalidate_runtime()
linker.invalidate()
# SOP 推进改成同步,测试里好断言
monkeypatch.setattr(engine, "_submit", lambda rid: engine._safe_advance(rid))
ds_id = semantic.create_datasource(name="测试库", ds_type="mysql", host="h", port=3306,
db_name="biz", username="ro", password="pw")
events = list(introspect.run_introspection(ds_id))
assert events[-1]["stage"] == "done"
semantic.set_models_enabled(ds_id, [m["id"] for m in semantic.list_models(ds_id)], True)
tok = identity.set_current(identity.Actor())
yield {"ds_id": ds_id, "conn": conn}
identity.reset(tok)
def as_user(uid: str):
from app.governance import users
users.invalidate()
return identity.set_current(users.load_actor(uid))
def build_basics(ds_id: int) -> dict:
"""建一套最小本体:对象 + 聚合函数(统计周期口径是业务月)+ 规则函数,并发布。"""
from app.kernel import service
ot = service.create_concept("object_type", "网点", synonyms=["店"], spec={
"properties": [{"name": "编号", "data_type": "string", "is_key": True},
{"name": "名称"}, {"name": "品牌"},
{"name": "等级", "data_type": "enum", "enum_values": ["A", "B", "S"],
"is_writable": True},
{"name": "跟进状态", "data_type": "enum",
"enum_values": ["正常", "重点跟进"], "is_writable": True}],
"label_property": "名称"})
service.set_binding(ot["id"], ds_id, "table", {
"table": "store", "key_column": "id", "label_column": "store_name",
"columns": {"编号": "id", "名称": "store_name", "品牌": "brand_name", "等级": "level"}})
rule = service.create_concept("function", "达标判定", spec={
"category": "rule", "expression": "actual >= target"})
m = service.create_concept("function", "成交金额", synonyms=["销售额"], spec={
"category": "aggregate", "object_type": ot["id"], "unit": "元", "calibre_rule": rule["id"],
"period": {"start_day": 26, "start_month_offset": -1, "end_day": 25, "end_month_offset": 0, "label": "业务月"}})
service.set_binding(m["id"], ds_id, "metric_expr", {
"base_table": "order_item", "expression": "SUM(amount)",
"object_key_column": "store_id", "time_column": "created_at",
"dimensions": {"网点": "store_id"}})
service.publish("初始化")
return {"ot": ot, "metric": m, "rule": rule}
# =========================== 规则 / 周期 ===========================
def test_规则表达式安全求值():
from app.kernel import rules
assert rules.evaluate("actual >= target", {"actual": "0.31", "target": 0.3}) is True
assert rules.evaluate("max(0, ceil(t * d - o))", {"t": 0.15, "d": 100, "o": 12}) == 3
assert rules.evaluate("obj.等级 == 'A'", {"obj": {"等级": "A"}}) is True
assert rules.evaluate("x ≥ 1 && y", {"x": 2, "y": True}) is True
for bad in ("__import__('os')", "a.__class__", "[x for x in y]", "open('f')", "lambda: 1"):
with pytest.raises(rules.RuleError):
rules.evaluate(bad, {"a": 1, "y": []})
assert rules.free_names("rate >= target and max(a, 1) > 0") == ["rate", "target", "a"]
def test_自定义周期解析():
import datetime as dt
from app.kernel import calendar as cal
spec = {"start_day": 26, "start_month_offset": -1, "end_day": 25, "end_month_offset": 0}
r = cal.resolve(spec, "2026-08")
assert (r["start"], r["end"]) == ("2026-07-26", "2026-08-25")
# 9 月 27 日落在「10 月期」
assert cal.resolve(spec, "current", today=dt.date(2026, 9, 27))["period"] == "2026-10"
assert cal.resolve(spec, "last", today=dt.date(2026, 9, 27))["period"] == "2026-09"
assert cal.resolve(None, "2026-02")["end"] == "2026-02-28"
assert cal.parse_time_phrase("上个月的销售额")["ref"] == "last"
assert cal.parse_time_phrase("2026年3月各网点")["ref"] == "2026-03"
# =========================== 内核 ===========================
def test_发布前改动不影响运行时_发布后生效_可回滚(env):
from app.kernel import service
b = build_basics(env["ds_id"])
assert service.rt_fn("销售额", "aggregate")["id"] == b["metric"]["id"]
assert service.rt_fn("销售额", "rule") is None
service.update_concept(b["metric"]["id"], description="改了口径")
assert service.rt_get(b["metric"]["id"])["description"] == "" # 运行时仍是旧版
diff = service.pending_diff()
assert diff["changed"][0]["name"] == "成交金额"
out = service.publish("第二版")
assert out["revision"] == 2
assert service.rt_get(b["metric"]["id"])["description"] == "改了口径"
service.rollback(1)
assert service.rt_get(b["metric"]["id"])["description"] == ""
assert service.list_revisions()[0]["note"] == "回滚到第 1 版"
with pytest.raises(HTTPException) as e:
service.delete_concept(b["metric"]["id"])
assert e.value.status_code == 409
def test_同名冲突与spec校验(env):
from app.kernel import service
service.create_concept("object_type", "审核单")
with pytest.raises(HTTPException):
service.create_concept("object_type", "审核单")
with pytest.raises(HTTPException):
service.create_concept("function", "坏规则", spec={"category": "rule", "expression": "import os"})
with pytest.raises(HTTPException) as e: # 角色、流程、术语不再是元素
service.create_concept("role", "审核员")
assert "成员与角色" in e.value.detail
legacy = service.create_concept("rule", "旧写法规则", spec={"expression": "a > 1"})
assert legacy["kind"] == "function" and legacy["spec"]["category"] == "rule"
with pytest.raises(HTTPException):
service.create_concept("object_type", "两个主键", spec={"properties": [
{"name": "a", "is_key": True}, {"name": "b", "is_key": True}]})
def test_链接_最长匹配_实例_时间(env):
from app.kernel import linker, objects
b = build_basics(env["ds_id"])
from app.kernel import pipeline
assert pipeline.sync_type(b["ot"]["id"])["rows"] == 3
linker.invalidate()
r = linker.link("上个月杭州体验中心的销售额是多少")
assert [c["name"] for c in r["concepts"]] == ["成交金额"]
assert r["instances"][0]["label"] == "杭州体验中心"
assert r["time"]["ref"] == "last"
def test_指标确定性取数与对象读写回(env):
from app.kernel import metrics, objects
b = build_basics(env["ds_id"])
r = metrics.query("成交金额", dimensions=["网点"])
assert r["columns"] == ["网点", "网点名称", "value"] and len(r["rows"]) == 3
assert r["run_id"] > 0 and r["calibre"]["name"] == "达标判定"
one = metrics.query("销售额", object_key="1")
assert one["value"] == 300.0 + 600.0 # store_id=1 的两单:i=3、i=6
c = metrics.compile_sql(metrics.metric("成交金额"), time="2026-08") # 指标自己的周期口径:业务月
assert "2026-07-26" in c["sql"] and "2026-08-26" in c["sql"] # 含 25 日:截止日的第二天之前
with pytest.raises(HTTPException):
metrics.compile_sql(metrics.metric("成交金额"), dimensions=["不存在的维度"])
o = objects.get("网点", "1")
assert o["label"] == "杭州体验中心" and o["properties"]["等级"] == "A"
with pytest.raises(HTTPException): # 不可写属性
objects.apply_ops([{"op": "update", "object_type": b["ot"]["id"], "key": "1", "values": {"名称": "x"}}])
e = objects.apply_ops([{"op": "update", "object_type": b["ot"]["id"], "key": "1", "values": {"等级": "S"}}])
assert objects.get("网点", "1")["properties"]["等级"] == "S"
objects.revert_edits(e["edit_ids"])
assert objects.get("网点", "1")["properties"]["等级"] == "A"
# =========================== 动作 + 审批 ===========================
def make_action(ot_id: str):
"""动作也是本体元素:建成草稿,随本体一起发布。"""
from app.kernel import service
a = service.create_concept("action", "mark_follow", display_name="标记重点跟进", spec={
"target_type": ot_id,
"params": [{"name": "reason", "label": "原因", "type": "text", "required": True}],
"criteria": [{"expression": "obj.跟进状态 != '重点跟进'", "message": "已在跟进中"}],
"effects": [
{"tool": "object.write", "args": {"object_type": ot_id, "key": "$obj_key",
"property": "跟进状态", "value": "重点跟进"}},
{"tool": "task.create", "args": {"title": "整改:$obj.label", "description": "$reason",
"role": "operator",
"form": [{"name": "measures", "label": "措施",
"required": True}]}}],
"approval": {"mode": "manual", "approver_roles": []}})
service.publish("发布动作")
return a
def test_动作必须审批_四眼原则_执行_撤销(env):
from app.capability import actions, tasks
from app.kernel import objects
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
tok = as_user("operator")
run = actions.propose("mark_follow", {"reason": "连续偏低"}, object_key="1")
assert run["status"] == "pending_approval"
assert "跟进状态" in run["preview"]["summary"]
# 提议人不能自己批
with pytest.raises(HTTPException) as e:
actions.decide(run["id"], True)
assert e.value.status_code == 403
identity.reset(tok)
# 幂等:同一提议不重复建
tok = as_user("operator")
assert actions.propose("mark_follow", {"reason": "连续偏低"}, object_key="1")["id"] == run["id"]
identity.reset(tok)
# 没有审批权限的人不能批
tok = as_user("viewer")
with pytest.raises(HTTPException):
actions.decide(run["id"], True)
identity.reset(tok)
# 审批人批准 → 执行
tok = as_user("approver")
done = actions.decide(run["id"], True, "同意")
identity.reset(tok)
assert done["status"] == "done", done["error"]
assert objects.get("网点", "1")["properties"]["跟进状态"] == "重点跟进"
open_tasks = tasks.list_tasks(scope="all")
assert open_tasks and open_tasks[0]["title"] == "整改:杭州体验中心"
# 前置条件:已经在跟进中就不能再提
with pytest.raises(HTTPException):
actions.prepare("mark_follow", {"reason": "x"}, "1")
# 撤销也要审批
tok = as_user("operator")
rv = actions.propose_revert(run["id"], "误操作")
identity.reset(tok)
tok = as_user("approver")
actions.decide(rv["id"], True, "同意撤销")
identity.reset(tok)
assert objects.get("网点", "1")["properties"].get("跟进状态") is None
assert actions.get(run["id"])["status"] == "reverted"
assert tasks.get(open_tasks[0]["id"])["status"] == "cancelled"
# 全链路审计
from app.governance import audit
events = {i["event"] for i in audit.query(limit=500)["items"]}
assert {"action.propose", "action.approve", "action.effect", "action.done",
"action.revert_propose", "action.reverted", "object.write", "task.create"} <= events
def test_AI提议的动作提交人也不能自己批(env):
from app.capability import actions
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
tok = as_user("approver")
ai = identity.set_current(identity.as_ai(identity.current()))
run = actions.propose("mark_follow", {"reason": "AI 建议"}, object_key="2", initiator_kind="ai")
identity.reset(ai)
assert run["initiator_kind"] == "ai" and run["submitted_by"] == "approver"
with pytest.raises(HTTPException):
actions.decide(run["id"], True)
identity.reset(tok)
def test_动作定义只能调用已注册工具(env):
from app.capability import defs
from app.kernel import service
with pytest.raises(HTTPException):
service.create_concept("action", "bad", spec={"effects": [{"tool": "os.system", "args": {}}]})
with pytest.raises(HTTPException):
service.create_concept("action", "bad2", spec={"effects": [
{"tool": "notify.send", "args": {"recipient": "$nobody", "title": "x"}}]})
with pytest.raises(HTTPException):
service.create_concept("function", "bad3", spec={
"category": "ai", "instructions": "x", "functions": ["object.write"]})
with pytest.raises(HTTPException): # 能力表只剩外部端点
defs.upsert("action", "bad4", spec={})
# =========================== SOP ===========================
def sop_spec(ot_id: str) -> dict:
return {
"params": [{"name": "store", "label": "网点", "type": "object", "object_type": ot_id}],
"roles": ["operator"],
"steps": [
{"id": "q", "type": "function", "title": "取成交金额", "function": "metric.query",
"args": {"metric": "成交金额", "object_key": "$store.key"}, "output": "amt", "next": "d"},
{"id": "d", "type": "decision", "title": "是否偏低",
"branches": [{"when": "amt.value < 1000", "next": "fix", "label": "偏低"}],
"default": "ok"},
{"id": "fix", "type": "human_task", "title": "制定整改措施", "role": "operator",
"form": [{"name": "plan", "label": "措施", "required": True}], "output": "plan",
"next": "act"},
{"id": "act", "type": "action", "title": "标记跟进", "action": "mark_follow",
"params": {"reason": "$plan.plan"}, "object_key": "$store.key",
"on_reject": "ok", "next": "end"},
{"id": "ok", "type": "end", "title": "无需处理", "outcome": "正常"},
{"id": "end", "type": "end", "title": "已处理", "outcome": "已整改"}]}
def test_SOP校验(env):
from app.sop import spec
bad = spec.normalize({"steps": [
{"id": "a", "type": "function", "function": "metric.query", "args": {"metric": "$nope"},
"next": "b"},
{"id": "b", "type": "decision", "branches": [{"when": "x >", "next": "c"}]},
{"id": "c", "type": "end"},
]})
errs = " ".join(spec.validate(bad)["errors"])
assert "变量「nope」" in errs and "「否则」" in errs and "有误" in errs
cyc = spec.normalize({"steps": [
{"id": "a", "type": "function", "function": "ontology.overview", "next": "b"},
{"id": "b", "type": "function", "function": "ontology.overview", "next": "a"}]})
assert any("环" in e for e in spec.validate(cyc)["errors"])
tool = spec.normalize({"steps": [
{"id": "a", "type": "function", "function": "object.write", "next": "z"},
{"id": "z", "type": "end"}]})
assert any("只读函数" in e for e in spec.validate(tool)["errors"])
def test_SOP试运行_审核发布_正式运行挂起与恢复(env):
from app.capability import actions, tasks
from app.governance import review
from app.kernel import objects
from app.sop import engine, service
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
d = service.create("低成交整改", spec=sop_spec(b["ot"]["id"]))
assert d["validation"]["errors"] == []
assert any("还没有试运行" in w for w in d["validation"]["warnings"]) # 没试运行只是提醒,不拦发布
dry = engine.start(d["id"], {"store": "1"}, mode="dry_run", wait=True)
assert dry["status"] == "done", dry["error"]
assert [s["step_id"] for s in dry["steps"]] == ["q", "d", "fix", "act", "end"]
item = service.submit_publish(d["id"], "首版")
review.decide(item["id"], True)
assert service.get(d["id"])["current_version"] == 1
# 正式运行:走到人工任务停下
tok = as_user("operator")
run = engine.start(d["id"], {"store": "1"}, wait=True)
identity.reset(tok)
assert run["status"] == "waiting"
task = next(t for t in tasks.list_tasks(scope="all") if t["source_type"] == "sop")
with pytest.raises(HTTPException): # 表单必填
tasks.complete(task["id"], {})
tok = as_user("operator")
tasks.complete(task["id"], {"plan": "加强培训"})
identity.reset(tok)
run = engine.get_run(run["id"])
assert run["status"] == "waiting"
st = next(s for s in run["steps"] if s["step_id"] == "act")
assert st["status"] == "waiting_approval"
ar = actions.get(st["action_run_id"])
assert ar["initiator_kind"] == "sop" and ar["params"]["reason"] == "加强培训"
tok = as_user("approver")
actions.decide(ar["id"], True, "同意")
identity.reset(tok)
run = engine.get_run(run["id"])
assert run["status"] == "done" and run["outcome"] == "已整改"
assert objects.get("网点", "1")["properties"]["跟进状态"] == "重点跟进"
# 驳回分支
tok = as_user("operator")
run2 = engine.start(d["id"], {"store": "2"}, wait=True)
t2 = next(t for t in tasks.list_tasks(scope="all", status="open") if t["source_type"] == "sop")
tasks.complete(t2["id"], {"plan": "x"})
identity.reset(tok)
st2 = next(s for s in engine.get_run(run2["id"])["steps"] if s["step_id"] == "act")
tok = as_user("approver")
actions.decide(st2["action_run_id"], False, "不必")
identity.reset(tok)
assert engine.get_run(run2["id"])["outcome"] == "正常"
def test_SOP只读剧本模式停在人工步骤(env):
from app.sop import engine, service
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
d = service.create("剧本", spec=sop_spec(b["ot"]["id"]))
engine.start(d["id"], {"store": "1"}, mode="dry_run", wait=True)
from app.governance import review
review.decide(service.submit_publish(d["id"])["id"], True)
run = engine.start(d["id"], {"store": "1"}, mode="ai_readonly", wait=True)
assert run["status"] == "paused"
assert run["steps"][-1]["status"] == "suggested"
# =========================== 评测 / 模板 ===========================
def test_评测打分与本体召回(env):
from app.evals import service as evals
case = {"kind": "mixed", "question": "q", "expected": "", "must_include": ["赔付", "差额"],
"expected_calls": ["metric.query"], "expected_action": ""}
g = evals.grade(case, {"answer": "按差额赔付", "plan": {"steps": [{"call": "metric.query"}]},
"data_refs": [{"run_id": 1}]}, judge=False)
assert g["passed"] and g["score"] == 1.0
def test_行业模板可导入_导出往返(env):
from app.capability import defs
from app.kernel import service, templates
from app.governance import roles
out = templates.apply_template("store_ops")
assert not out["errors"], out["errors"]
m = service.find("安心包渗透率", "function")
assert m["spec"]["category"] == "aggregate"
assert m["spec"]["period"]["start_day"] == 26 and m["spec"]["period"]["label"] == "生态月" # 周期是指标自己的口径
assert defs.find("mark_follow_up", "action")["spec"]["target_type"] == service.find("门店", "object_type")["id"]
assert defs.find("指标归因分析", "skill")["status"] == "draft"
assert "区域运营" in roles.names()
y = templates.export_yaml()
assert "生态月" in y and "mark_follow_up" in y and "区域运营" in y
# 旧格式(kind: metric / role / capabilities)也能导入
old = templates.import_yaml("""
concepts:
- {kind: metric, name: 旧指标, spec: {unit: 元}}
- {kind: role, name: 旧角色, spec: {responsibilities: 审批}}
- {kind: term, name: 旧术语}
capabilities:
- {kind: skill, name: 旧技能, spec: {instructions: 分析, functions: [concept.lookup]}}
""")
assert set(old["created"]) == {"旧指标", "旧技能"} and "旧角色" in roles.names()
assert old["notes"] and service.find("旧技能", "function")["spec"]["category"] == "ai"
# =========================== 通用性 / 接口 ===========================
BUSINESS_WORDS = ("问界", "鸿蒙", "门店", "生态月", "渗透率", "盯防", "安心包", "生态系数", "主机厂", "智界")
def test_代码里没有行业词():
hits = []
for p in (ROOT / "app").rglob("*.py"):
text = p.read_text(encoding="utf-8")
for w in BUSINESS_WORDS:
if w in text:
hits.append(f"{p.relative_to(ROOT)}: {w}")
assert not hits, "app/ 必须与行业无关,行业内容放 templates/:\n" + "\n".join(hits)
def test_接口权限(env):
from fastapi.testclient import TestClient
from app.main import app
c = TestClient(app)
me = c.get("/api/gov/me", headers={"X-User-Id": "approver"}).json()
assert "approve" in me["permissions"] and "build" not in me["permissions"]
r = c.post("/api/kernel/concepts", json={"kind": "object_type", "name": "x"},
headers={"X-User-Id": "viewer"})
assert r.status_code == 403
r = c.post("/api/kernel/concepts", json={"kind": "object_type", "name": "x"},
headers={"X-User-Id": "builder"})
assert r.status_code == 200
r = c.post("/api/kernel/concepts", json={"kind": "role", "name": "y"},
headers={"X-User-Id": "builder"})
assert r.status_code == 422
assert c.get("/api/cap/catalog").json()["functions"]
assert c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}).status_code == 404
def test_采纳提议时名字已被别名占用则合并(env):
from app.governance import review
from app.kernel import propose, service
propose.submit_proposals([
{"kind": "object_type", "name": "二级品牌", "synonyms": ["品牌"], "spec": {}},
{"kind": "object_type", "name": "品牌", "synonyms": ["品牌名"], "spec": {},
"evidence": [{"chunk_id": "d1:c1", "doc_id": 1, "heading": "h", "snippet": "s"}]},
], "extract")
items = review.list_items(kind="concept_create")["items"]
for it in sorted(items, key=lambda x: x["title"] != "对象类型「二级品牌」"):
out = review.decide(it["id"], True)
assert out["result"].get("merged") is True
c = service.get_concept(service.find("二级品牌")["id"])
assert "品牌名" in c["synonyms"] and c["evidence"]
def test_金标问题集重复导入不产生重复用例(env):
from app.evals import service as evals
text = (ROOT / "eval" / "store_ops" / "questions.yaml").read_text(encoding="utf-8")
evals.import_cases_yaml(text, "s")
evals.import_cases_yaml(text, "s")
qs = [c["question"] for c in evals.list_cases("s")]
assert len(qs) == len(set(qs)) == 30
def test_答案角标纠正():
from app.agents.lead import normalize_cites
steps = [{"id": "s1"}, {"id": "s2"}]
results = {"s1": {"run_id": 7}, "s2": {"evidence": [{"chunk_id": "d7:c6"}]}}
chunks = {"d7:c6": {"id": "d7:c6"}}
data = {7: {}}
out = normalize_cites("甲[^run:s1]乙[^run:d7:c6]丙[^run:s2]丁[^run:99]戊[^s1]己[^d7:c6]庚[^x:y]",
steps, results, chunks, data)
assert out == "甲[^run:7]乙[^d7:c6]丙[^d7:c6]丁戊[^run:7]己[^d7:c6]庚"
def test_可选参数给错时丢弃而不是失败():
from app.capability import registry
schema = {"properties": {"q": {"type": "string"}, "ds_id": {"type": "integer"}}, "required": ["q"]}
assert registry.validate_args(schema, {"q": "x", "ds_id": "门店库"}, "f") == {"q": "x"}