chore: auto release commit (2026-07-14 11:56:45)
All checks were successful
技能自动化发布 / release (push) Successful in 5s
All checks were successful
技能自动化发布 / release (push) Successful in 5s
This commit is contained in:
@@ -15,6 +15,8 @@
|
||||
| CLI / health / version / metadata / runtime 路径 | `tests/test_*.py` | 是 | 默认必跑,保持轻量、无外联 |
|
||||
| 纯函数 / 业务规则 | `tests/test_*.py` | 是 | 不依赖真实外部系统 |
|
||||
| service 层契约 | 从 `tests/samples/test_service_contract.py.sample` 复制到 `tests/test_service_contract.py` | 是,复制后 | 用 `FakeAdapter` / stub 注入外部依赖 |
|
||||
| 外源同步契约 | 从 `tests/samples/test_sync_contract.py.sample` 复制 | 是,复制后 | 幂等 / 事务 / 空结果保护 / 不导出文件 |
|
||||
| 单内核多入口 | 从 `tests/samples/test_action_core_contract.py.sample` 复制 | 是,复制后 | CLI/task/兼容命令复用同一 domain service |
|
||||
| golden fixture 回归 | 从 `tests/samples/test_golden_cases.py.sample` 复制到 `tests/test_golden_cases.py` | 是,复制后 | 输入样例 + 期望输出,适合解析、计算、校验类技能 |
|
||||
| 仿真 API | `tests/integration/test_simulator_api_contract.py.sample` | 否 | 复制并设置 `OPENCLAW_TEST_TARGET=simulator_api` 后按需运行 |
|
||||
| 仿真 RPA / 页面操作 | `tests/integration/test_simulator_rpa_contract.py.sample` | 否 | 用 localhost / 仿真页面,不碰真实系统 |
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
---
|
||||
|
||||
## 两类样例文件
|
||||
## 样例文件
|
||||
|
||||
### 1. `test_service_contract.py.sample`
|
||||
|
||||
@@ -22,7 +22,17 @@
|
||||
- 需要验证:**成功路径**、**参数/校验错误**、**adapter 异常被转换为业务可读错误**。
|
||||
- 需要用 **`FakeAdapter`**(见 `tests/adapter_test_utils.py`)或自建 **stub** 替代 ERP、TMS、WMS、船司、报关、LLM、RPA 等,**不**发真实 HTTP、**不**开真实浏览器。
|
||||
|
||||
### 2. `test_golden_cases.py.sample`
|
||||
### 2. `test_sync_contract.py.sample`
|
||||
|
||||
**适合:** 外源 → 本地库的同步 / refresh / collect 能力。
|
||||
|
||||
至少应覆盖:首次插入、第二次幂等、更新、失效数据处理、不可信空结果保护 vs 完整空快照失效、遗漏 `snapshot_complete` 立即失败、部分写入后故障注入与回滚(`fail_after_writes`)、统计字段 `inserted/updated/unchanged/removed`、同步路径不调用 CSV/Excel 导出器。`snapshot_complete` 为调用方**必须显式传入**的 keyword-only 参数(无默认值),禁止默认把结果当成完整快照,也禁止靠条数猜测完整性。使用通用表名(如 `business_key`),不要写具体平台业务名。
|
||||
|
||||
### 3. `test_action_core_contract.py.sample`
|
||||
|
||||
**适合:** 校验「单业务内核、多入口」——task/CLI/兼容命令调用同一 domain service;不按 toolbar/cron/agent 来源改变业务结果。
|
||||
|
||||
### 4. `test_golden_cases.py.sample`
|
||||
|
||||
**适合:**
|
||||
|
||||
@@ -103,6 +113,8 @@
|
||||
| 用途 | 示例文件名 |
|
||||
|------|------------|
|
||||
| Service 契约 | `tests/test_service_contract.py` |
|
||||
| 同步契约 | `tests/test_sync_contract.py` |
|
||||
| 单内核多入口 | `tests/test_action_core_contract.py` |
|
||||
| Golden / fixture 回归 | `tests/test_golden_cases.py` |
|
||||
| 领域规则 | `tests/test_<domain>_rules.py` |
|
||||
| 校验逻辑 | `tests/test_<domain>_validation.py` |
|
||||
|
||||
116
tests/samples/test_action_core_contract.py.sample
Normal file
116
tests/samples/test_action_core_contract.py.sample
Normal file
@@ -0,0 +1,116 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制到 ``tests/test_action_core_contract.py`` 后按实际模块改名运行。
|
||||
# 默认不会被 ``python tests/run_tests.py`` 收集(扩展名为 .sample)。
|
||||
"""
|
||||
单业务内核、多入口契约范式(通用)。
|
||||
|
||||
覆盖:
|
||||
- task / command adapter 调用唯一 domain service
|
||||
- 兼容命令复用同一个核心函数
|
||||
- CLI handler 不复制业务逻辑
|
||||
- 不根据 toolbar / cron / agent 来源改变业务处理
|
||||
|
||||
复制后把示意函数换成真实 import;禁止按入口维护多套实现。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
class DomainService:
|
||||
"""唯一业务内核示意。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def sync_records(self, *, limit: int = 100) -> dict[str, Any]:
|
||||
self.calls.append({"op": "sync_records", "limit": limit})
|
||||
return {"ok": True, "limit": limit, "inserted": 1}
|
||||
|
||||
|
||||
def cmd_sync_records(domain: DomainService, *, limit: int = 100) -> dict[str, Any]:
|
||||
"""task_service 编排层:可加 job_context,但不按 source 分叉业务。"""
|
||||
return domain.sync_records(limit=limit)
|
||||
|
||||
|
||||
def cmd_export_compat_refresh(domain: DomainService, *, limit: int = 100) -> dict[str, Any]:
|
||||
"""兼容旧 export:刷新必须复用同一 sync 内核,禁止另写采集逻辑。"""
|
||||
sync_result = domain.sync_records(limit=limit)
|
||||
return {"export": "delegated-to-host-or-report", "sync": sync_result}
|
||||
|
||||
|
||||
def cli_handle_sync(domain: DomainService, argv_limit: int) -> dict[str, Any]:
|
||||
"""CLI handler:只解析参数后转发,不内嵌业务。"""
|
||||
return cmd_sync_records(domain, limit=argv_limit)
|
||||
|
||||
|
||||
def run_from_source(
|
||||
domain: DomainService,
|
||||
*,
|
||||
source: str,
|
||||
limit: int = 10,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
宿主可能传入 source=toolbar|cron|agent|skill-detail。
|
||||
正确实现:忽略 source,业务结果一致。
|
||||
"""
|
||||
_ = source # 不得用于分支业务语义
|
||||
return cmd_sync_records(domain, limit=limit)
|
||||
|
||||
|
||||
class TestActionCoreContractSample(unittest.TestCase):
|
||||
def test_task_adapter_calls_single_domain_service(self) -> None:
|
||||
domain = DomainService()
|
||||
out = cmd_sync_records(domain, limit=5)
|
||||
self.assertTrue(out["ok"])
|
||||
self.assertEqual(domain.calls, [{"op": "sync_records", "limit": 5}])
|
||||
|
||||
def test_compat_command_reuses_same_core(self) -> None:
|
||||
domain = DomainService()
|
||||
cmd_export_compat_refresh(domain, limit=3)
|
||||
self.assertEqual(len(domain.calls), 1)
|
||||
self.assertEqual(domain.calls[0]["op"], "sync_records")
|
||||
|
||||
def test_cli_handler_does_not_duplicate_business_logic(self) -> None:
|
||||
domain = DomainService()
|
||||
# CLI 与 task 编排应落到同一函数对象(示意)
|
||||
self.assertIs(cli_handle_sync.__wrapped__ if hasattr(cli_handle_sync, "__wrapped__") else None, None)
|
||||
out = cli_handle_sync(domain, 7)
|
||||
self.assertEqual(out["limit"], 7)
|
||||
self.assertEqual(domain.calls[-1], {"op": "sync_records", "limit": 7})
|
||||
|
||||
# 强化:CLI 路径与 cmd 路径结果一致
|
||||
domain2 = DomainService()
|
||||
a = cli_handle_sync(domain2, 2)
|
||||
domain3 = DomainService()
|
||||
b = cmd_sync_records(domain3, limit=2)
|
||||
self.assertEqual(a, b)
|
||||
|
||||
def test_business_result_independent_of_entry_source(self) -> None:
|
||||
domain = DomainService()
|
||||
results = [
|
||||
run_from_source(domain, source=src, limit=4)
|
||||
for src in ("toolbar", "cron", "agent", "skill-detail")
|
||||
]
|
||||
self.assertEqual(results[0], results[1])
|
||||
self.assertEqual(results[1], results[2])
|
||||
self.assertEqual(results[2], results[3])
|
||||
self.assertEqual(len(domain.calls), 4)
|
||||
self.assertTrue(all(c["op"] == "sync_records" and c["limit"] == 4 for c in domain.calls))
|
||||
|
||||
def test_entrypoint_wiring_points_to_same_callable(self) -> None:
|
||||
"""示意:manifest 多 placements 应对应同一 Python 入口函数。"""
|
||||
domain = DomainService()
|
||||
handlers: dict[str, Callable[..., dict[str, Any]]] = {
|
||||
"toolbar": lambda: cmd_sync_records(domain, limit=1),
|
||||
"cron": lambda: cmd_sync_records(domain, limit=1),
|
||||
"agent": lambda: cmd_sync_records(domain, limit=1),
|
||||
}
|
||||
outs = [handlers[k]() for k in handlers]
|
||||
self.assertEqual(outs[0], outs[1])
|
||||
self.assertEqual(outs[1], outs[2])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
274
tests/samples/test_sync_contract.py.sample
Normal file
274
tests/samples/test_sync_contract.py.sample
Normal file
@@ -0,0 +1,274 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制到 ``tests/test_sync_contract.py`` 后按实际 domain service 改名运行。
|
||||
# 默认不会被 ``python tests/run_tests.py`` 收集(扩展名为 .sample)。
|
||||
"""
|
||||
外源 → 本地库同步契约范式(通用,无具体平台业务名)。
|
||||
|
||||
覆盖:
|
||||
- 首次同步插入
|
||||
- 第二次同步幂等
|
||||
- 更新已有数据
|
||||
- 处理失效数据
|
||||
- 不可信空结果保护 vs 完整空快照失效(``snapshot_complete`` 必填,无默认值)
|
||||
- 遗漏 ``snapshot_complete`` 立即失败(TypeError)
|
||||
- 事务在部分写入后失败并回滚
|
||||
- 返回 inserted/updated/unchanged/removed
|
||||
- sync Action 不调用 CSV/Excel 文件导出器
|
||||
|
||||
复制后把内存仓库与 stub 外源换成真实 repository / reader;禁止访问真实网络或用户数据目录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class SyncStats:
|
||||
total: int = 0
|
||||
inserted: int = 0
|
||||
updated: int = 0
|
||||
unchanged: int = 0
|
||||
removed: int = 0
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {
|
||||
"total": self.total,
|
||||
"inserted": self.inserted,
|
||||
"updated": self.updated,
|
||||
"unchanged": self.unchanged,
|
||||
"removed": self.removed,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemoryRecordStore:
|
||||
"""内存库:演示幂等 upsert + 全量失效(is_active 标记)。"""
|
||||
|
||||
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
in_transaction: bool = False
|
||||
_tx_snapshot: dict[str, dict[str, Any]] | None = None
|
||||
|
||||
def begin(self) -> None:
|
||||
self._tx_snapshot = {k: dict(v) for k, v in self.rows.items()}
|
||||
self.in_transaction = True
|
||||
|
||||
def commit(self) -> None:
|
||||
self._tx_snapshot = None
|
||||
self.in_transaction = False
|
||||
|
||||
def rollback(self) -> None:
|
||||
if self._tx_snapshot is not None:
|
||||
self.rows = {k: dict(v) for k, v in self._tx_snapshot.items()}
|
||||
self._tx_snapshot = None
|
||||
self.in_transaction = False
|
||||
|
||||
def upsert_snapshot(
|
||||
self,
|
||||
records: list[dict[str, Any]],
|
||||
*,
|
||||
fail_after_writes: int | None = None,
|
||||
) -> SyncStats:
|
||||
"""全量快照:按 business_key 对齐;缺失标 is_active=0。
|
||||
|
||||
``fail_after_writes``:在成功完成该次数的 insert/update 之后抛错,用于验证回滚。
|
||||
"""
|
||||
self.begin()
|
||||
try:
|
||||
stats = SyncStats(total=len(records))
|
||||
seen: set[str] = set()
|
||||
write_count = 0
|
||||
for rec in records:
|
||||
key = str(rec["business_key"])
|
||||
seen.add(key)
|
||||
existing = self.rows.get(key)
|
||||
payload = {
|
||||
"business_key": key,
|
||||
"title": rec["title"],
|
||||
"is_active": 1,
|
||||
}
|
||||
if existing is None:
|
||||
self.rows[key] = payload
|
||||
stats.inserted += 1
|
||||
write_count += 1
|
||||
elif existing.get("title") == payload["title"] and existing.get("is_active") == 1:
|
||||
stats.unchanged += 1
|
||||
else:
|
||||
self.rows[key] = payload
|
||||
stats.updated += 1
|
||||
write_count += 1
|
||||
if fail_after_writes is not None and write_count >= fail_after_writes:
|
||||
raise RuntimeError(
|
||||
f"simulated write failure after {write_count} insert/update write(s)"
|
||||
)
|
||||
for key, existing in list(self.rows.items()):
|
||||
if key not in seen and existing.get("is_active") == 1:
|
||||
existing["is_active"] = 0
|
||||
stats.removed += 1
|
||||
self.commit()
|
||||
return stats
|
||||
except Exception:
|
||||
self.rollback()
|
||||
raise
|
||||
|
||||
|
||||
class ExportSpy:
|
||||
"""若 sync 路径误调导出器,测试应失败。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[str] = []
|
||||
|
||||
def write_csv(self, *_a: Any, **_k: Any) -> None:
|
||||
self.calls.append("csv")
|
||||
|
||||
def write_excel(self, *_a: Any, **_k: Any) -> None:
|
||||
self.calls.append("excel")
|
||||
|
||||
|
||||
def sync_records(
|
||||
store: MemoryRecordStore,
|
||||
external_rows: list[dict[str, Any]],
|
||||
*,
|
||||
snapshot_complete: bool,
|
||||
exporter: ExportSpy | None = None,
|
||||
fail_after_writes: int | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""领域同步内核示意:只写库,不导出文件。
|
||||
|
||||
``snapshot_complete`` 为 keyword-only **必填**参数(无默认值):
|
||||
- False:读取失败/分页不完整/不可信结果 → 不得清库或失效旧数据
|
||||
- True:外源完整快照(可为空)→ 允许按全量策略 upsert / 标记失效
|
||||
调用方必须显式传入,禁止默认当作完整快照,也禁止靠条数猜测完整性。
|
||||
"""
|
||||
if external_rows is None:
|
||||
raise ValueError("external_rows required")
|
||||
if not snapshot_complete:
|
||||
active = sum(1 for r in store.rows.values() if r.get("is_active") == 1)
|
||||
return SyncStats(total=0, unchanged=active).as_dict()
|
||||
stats = store.upsert_snapshot(external_rows, fail_after_writes=fail_after_writes)
|
||||
if exporter is not None:
|
||||
# 正确实现不得调用;本示意刻意不调用,供测试断言
|
||||
pass
|
||||
return stats.as_dict()
|
||||
|
||||
|
||||
class TestSyncContractSample(unittest.TestCase):
|
||||
def test_first_sync_inserts(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
stats = sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
|
||||
snapshot_complete=True,
|
||||
)
|
||||
self.assertEqual(stats["inserted"], 2)
|
||||
self.assertEqual(stats["total"], 2)
|
||||
self.assertEqual(len(store.rows), 2)
|
||||
|
||||
def test_second_sync_is_idempotent(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
rows = [{"business_key": "a", "title": "A"}]
|
||||
sync_records(store, rows, snapshot_complete=True)
|
||||
stats = sync_records(store, rows, snapshot_complete=True)
|
||||
self.assertEqual(stats["unchanged"], 1)
|
||||
self.assertEqual(stats["inserted"], 0)
|
||||
self.assertEqual(stats["updated"], 0)
|
||||
|
||||
def test_updates_existing_row(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
|
||||
stats = sync_records(
|
||||
store, [{"business_key": "a", "title": "A2"}], snapshot_complete=True
|
||||
)
|
||||
self.assertEqual(stats["updated"], 1)
|
||||
self.assertEqual(store.rows["a"]["title"], "A2")
|
||||
|
||||
def test_marks_removed_inactive_on_full_sync(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
|
||||
snapshot_complete=True,
|
||||
)
|
||||
stats = sync_records(
|
||||
store, [{"business_key": "a", "title": "A"}], snapshot_complete=True
|
||||
)
|
||||
self.assertEqual(stats["removed"], 1)
|
||||
self.assertEqual(store.rows["b"]["is_active"], 0)
|
||||
self.assertEqual(store.rows["a"]["is_active"], 1)
|
||||
|
||||
def test_incomplete_empty_snapshot_does_not_wipe_existing(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
|
||||
stats = sync_records(store, [], snapshot_complete=False)
|
||||
self.assertEqual(store.rows["a"]["is_active"], 1)
|
||||
self.assertEqual(stats["removed"], 0)
|
||||
self.assertEqual(stats["unchanged"], 1)
|
||||
|
||||
def test_complete_empty_snapshot_marks_existing_inactive(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
|
||||
snapshot_complete=True,
|
||||
)
|
||||
stats = sync_records(store, [], snapshot_complete=True)
|
||||
self.assertEqual(stats["removed"], 2)
|
||||
self.assertEqual(store.rows["a"]["is_active"], 0)
|
||||
self.assertEqual(store.rows["b"]["is_active"], 0)
|
||||
|
||||
def test_omitting_snapshot_complete_raises_type_error(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
with self.assertRaises(TypeError):
|
||||
sync_records(store, [{"business_key": "a", "title": "A"}]) # type: ignore[call-arg]
|
||||
|
||||
def test_transaction_failure_after_partial_writes_rolls_back(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
|
||||
with self.assertRaises(RuntimeError) as ctx:
|
||||
sync_records(
|
||||
store,
|
||||
[
|
||||
{"business_key": "a", "title": "A2"},
|
||||
{"business_key": "b", "title": "B"},
|
||||
],
|
||||
snapshot_complete=True,
|
||||
fail_after_writes=1,
|
||||
)
|
||||
self.assertIn("after 1", str(ctx.exception))
|
||||
self.assertEqual(store.rows["a"]["title"], "A")
|
||||
self.assertNotIn("b", store.rows)
|
||||
self.assertFalse(store.in_transaction)
|
||||
self.assertIsNone(store._tx_snapshot)
|
||||
|
||||
def test_stats_keys_cover_inserted_updated_unchanged_removed(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
|
||||
snapshot_complete=True,
|
||||
)
|
||||
stats = sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A2"}],
|
||||
snapshot_complete=True,
|
||||
)
|
||||
for key in ("total", "inserted", "updated", "unchanged", "removed"):
|
||||
self.assertIn(key, stats)
|
||||
self.assertEqual(stats["updated"], 1)
|
||||
self.assertEqual(stats["removed"], 1)
|
||||
|
||||
def test_sync_does_not_call_file_exporters(self) -> None:
|
||||
store = MemoryRecordStore()
|
||||
spy = ExportSpy()
|
||||
sync_records(
|
||||
store,
|
||||
[{"business_key": "a", "title": "A"}],
|
||||
snapshot_complete=True,
|
||||
exporter=spy,
|
||||
)
|
||||
self.assertEqual(spy.calls, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,9 +5,10 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import unittest
|
||||
|
||||
from _support import get_skill_root
|
||||
from _support import IsolatedDataRoot, get_skill_root
|
||||
|
||||
from cli.app import build_parser
|
||||
from util.constants import SKILL_SLUG
|
||||
@@ -15,9 +16,13 @@ from util.constants import SKILL_SLUG
|
||||
_TEMPLATE_PLACEHOLDER_SLUG = "your-skill-slug"
|
||||
_ALLOWED_PLACEMENTS = frozenset({"toolbar", "row", "batch", "cron", "agent", "skill-detail"})
|
||||
_RESERVED_PLACEMENTS = frozenset({"row", "batch"})
|
||||
_RESERVED_ACTION_FIELDS = frozenset({"bind", "concurrency", "locks"})
|
||||
_RESERVED_ACTION_FIELDS = frozenset({"concurrency", "locks"})
|
||||
_ALLOWED_EXECUTION_PROFILES = frozenset({"sync", "async"})
|
||||
_REQUIRED_MANIFEST_KEYS = frozenset({"schemaVersion", "skill", "actions"})
|
||||
_REQUIRED_ACTION_KEYS = frozenset({"id", "label", "description", "placements", "entrypoint"})
|
||||
_REQUIRED_ACTION_KEYS = frozenset(
|
||||
{"id", "label", "description", "placements", "entrypoint", "executionProfile"}
|
||||
)
|
||||
_TABLE_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")
|
||||
_FORBIDDEN_BUSINESS_TERMS = (
|
||||
"wechat",
|
||||
"微信",
|
||||
@@ -66,6 +71,88 @@ def _load_actions_schema() -> dict:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _validate_bind_tables(action_id: str, bind: object) -> list[str]:
|
||||
errors: list[str] = []
|
||||
if not isinstance(bind, dict):
|
||||
return [f"{action_id}: bind must be object"]
|
||||
if set(bind.keys()) - {"tables"}:
|
||||
errors.append(f"{action_id}: bind only allows tables, got {sorted(bind.keys())}")
|
||||
tables = bind.get("tables")
|
||||
if not isinstance(tables, list) or len(tables) < 1:
|
||||
errors.append(f"{action_id}: bind.tables must be non-empty array")
|
||||
return errors
|
||||
seen: set[str] = set()
|
||||
for table in tables:
|
||||
if not isinstance(table, str) or not table.strip():
|
||||
errors.append(f"{action_id}: bind.tables entries must be non-empty strings")
|
||||
continue
|
||||
if table != table.strip() or not _TABLE_NAME_PATTERN.fullmatch(table):
|
||||
errors.append(f"{action_id}: bind.tables entry {table!r} must be snake_case")
|
||||
if table in seen:
|
||||
errors.append(f"{action_id}: bind.tables duplicate {table!r}")
|
||||
seen.add(table)
|
||||
return errors
|
||||
|
||||
|
||||
def _load_bindable_business_tables() -> set[str]:
|
||||
"""在隔离临时数据根下 init_db,返回可绑定到 toolbar 的业务表集合。
|
||||
|
||||
表必须同时满足:
|
||||
- SQLite 物理表存在(排除 sqlite_* 与 _jiangchang_* 元数据表)
|
||||
- ``_jiangchang_tables`` 中有对应行且 ``visible=1``
|
||||
|
||||
失败时抛出 RuntimeError(带诊断),不得静默返回空集供测试 skip。
|
||||
"""
|
||||
from db.connection import init_db
|
||||
from db.display_metadata import METADATA_TABLES
|
||||
from util.runtime_paths import get_db_path
|
||||
|
||||
physical: set[str] = set()
|
||||
visible_meta: set[str] = set()
|
||||
try:
|
||||
with IsolatedDataRoot() as data_root:
|
||||
init_db()
|
||||
db_path = get_db_path()
|
||||
if not os.path.isfile(db_path):
|
||||
raise RuntimeError(
|
||||
f"init_db did not create database file under isolated root "
|
||||
f"{data_root!r}: expected {db_path}"
|
||||
)
|
||||
conn = sqlite3.connect(db_path)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT name FROM sqlite_master "
|
||||
"WHERE type='table' AND name NOT LIKE 'sqlite_%'"
|
||||
)
|
||||
physical = {
|
||||
str(row[0])
|
||||
for row in cur.fetchall()
|
||||
if str(row[0]) not in METADATA_TABLES
|
||||
}
|
||||
cur.execute(
|
||||
"SELECT table_name FROM _jiangchang_tables WHERE visible = 1"
|
||||
)
|
||||
visible_meta = {str(row[0]) for row in cur.fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
bindable = physical & visible_meta
|
||||
if not bindable:
|
||||
raise RuntimeError(
|
||||
"isolated init_db produced no bindable tables "
|
||||
f"(physical={sorted(physical)}, visible_meta={sorted(visible_meta)}, "
|
||||
f"db_path={db_path!r})"
|
||||
)
|
||||
return bindable
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
"failed to load bindable business tables via isolated init_db: "
|
||||
f"{type(exc).__name__}: {exc}"
|
||||
) from exc
|
||||
|
||||
|
||||
class TestActionsManifest(unittest.TestCase):
|
||||
def test_manifest_exists_and_schema(self) -> None:
|
||||
manifest = _load_actions_manifest()
|
||||
@@ -108,6 +195,157 @@ class TestActionsManifest(unittest.TestCase):
|
||||
for placement in placements:
|
||||
self.assertIn(placement, _ALLOWED_PLACEMENTS, msg=f"{action_id} invalid placement {placement!r}")
|
||||
|
||||
def test_every_action_declares_execution_profile(self) -> None:
|
||||
manifest = _load_actions_manifest()
|
||||
for action in manifest["actions"]:
|
||||
profile = action.get("executionProfile")
|
||||
self.assertIn(
|
||||
profile,
|
||||
_ALLOWED_EXECUTION_PROFILES,
|
||||
msg=f"{action['id']} executionProfile must be sync|async, got {profile!r}",
|
||||
)
|
||||
|
||||
def test_schema_requires_execution_profile_and_defines_bind(self) -> None:
|
||||
schema = _load_actions_schema()
|
||||
action_def = schema["$defs"]["action"]
|
||||
self.assertIn("executionProfile", action_def.get("required") or [])
|
||||
profile = action_def["properties"]["executionProfile"]
|
||||
self.assertEqual(set(profile.get("enum") or []), {"sync", "async"})
|
||||
self.assertIn("bind", schema["$defs"])
|
||||
self.assertIn("bind", action_def["properties"])
|
||||
bind_def = schema["$defs"]["bind"]
|
||||
self.assertEqual(bind_def.get("required"), ["tables"])
|
||||
self.assertIs(bind_def.get("additionalProperties"), False)
|
||||
|
||||
def test_manifest_validates_against_json_schema(self) -> None:
|
||||
try:
|
||||
import jsonschema
|
||||
except ImportError:
|
||||
self.skipTest("jsonschema not installed")
|
||||
schema = _load_actions_schema()
|
||||
manifest = _load_actions_manifest()
|
||||
jsonschema.validate(instance=manifest, schema=schema)
|
||||
|
||||
def test_bind_structure_when_present(self) -> None:
|
||||
manifest = _load_actions_manifest()
|
||||
errors: list[str] = []
|
||||
for action in manifest["actions"]:
|
||||
if "bind" not in action:
|
||||
continue
|
||||
errors.extend(_validate_bind_tables(action["id"], action["bind"]))
|
||||
self.assertEqual(errors, [], msg="\n".join(errors))
|
||||
|
||||
def test_toolbar_actions_require_bind_tables(self) -> None:
|
||||
manifest = _load_actions_manifest()
|
||||
errors: list[str] = []
|
||||
for action in manifest["actions"]:
|
||||
placements = action.get("placements") or []
|
||||
if "toolbar" not in placements:
|
||||
continue
|
||||
bind = action.get("bind")
|
||||
if bind is None:
|
||||
errors.append(f"{action['id']}: toolbar placement requires bind.tables")
|
||||
continue
|
||||
errors.extend(_validate_bind_tables(action["id"], bind))
|
||||
self.assertEqual(errors, [], msg="\n".join(errors))
|
||||
|
||||
def test_bindable_business_tables_helper_loads_template_db(self) -> None:
|
||||
"""helper 本身必须可用:即便默认 manifest 无 toolbar bind,也要验证隔离库可读。"""
|
||||
bindable = _load_bindable_business_tables()
|
||||
self.assertIn("task_logs", bindable)
|
||||
self.assertNotIn("_jiangchang_tables", bindable)
|
||||
self.assertNotIn("_jiangchang_columns", bindable)
|
||||
|
||||
def test_bind_tables_exist_in_physical_and_visible_metadata(self) -> None:
|
||||
bindable = _load_bindable_business_tables()
|
||||
self.assertTrue(bindable, msg="bindable table set must be non-empty after init_db")
|
||||
manifest = _load_actions_manifest()
|
||||
missing: list[str] = []
|
||||
for action in manifest["actions"]:
|
||||
bind = action.get("bind")
|
||||
if not isinstance(bind, dict):
|
||||
continue
|
||||
for table in bind.get("tables") or []:
|
||||
if table not in bindable:
|
||||
missing.append(
|
||||
f"{action['id']}: bind.tables entry {table!r} must exist as "
|
||||
f"physical table AND _jiangchang_tables.visible=1 "
|
||||
f"(bindable={sorted(bindable)})"
|
||||
)
|
||||
self.assertEqual(missing, [], msg="\n".join(missing))
|
||||
|
||||
def test_schema_allows_all_placement_execution_profile_combinations(self) -> None:
|
||||
"""POLICY-SKILL-ACTION-004:4 placements × 2 profiles 必须全部通过 Schema。"""
|
||||
try:
|
||||
import jsonschema
|
||||
except ImportError:
|
||||
self.fail("jsonschema is required to validate placement×executionProfile orthogonality")
|
||||
schema = _load_actions_schema()
|
||||
placements = ("toolbar", "cron", "agent", "skill-detail")
|
||||
profiles = ("sync", "async")
|
||||
for placement in placements:
|
||||
for profile in profiles:
|
||||
action: dict = {
|
||||
"id": "probe-action",
|
||||
"label": "正交探测",
|
||||
"description": "验证 placements 与 executionProfile 无条件耦合",
|
||||
"placements": [placement],
|
||||
"executionProfile": profile,
|
||||
"entrypoint": {"type": "cli", "command": "health", "args": []},
|
||||
}
|
||||
if placement == "toolbar":
|
||||
action["bind"] = {"tables": ["task_logs"]}
|
||||
manifest = {
|
||||
"schemaVersion": 1,
|
||||
"skill": "your-skill-slug",
|
||||
"actions": [action],
|
||||
}
|
||||
with self.subTest(placement=placement, executionProfile=profile):
|
||||
jsonschema.validate(instance=manifest, schema=schema)
|
||||
if placement != "toolbar":
|
||||
self.assertNotIn("bind", action)
|
||||
|
||||
def test_schema_rejects_toolbar_without_bind(self) -> None:
|
||||
try:
|
||||
import jsonschema
|
||||
from jsonschema import ValidationError
|
||||
except ImportError:
|
||||
self.fail("jsonschema is required")
|
||||
schema = _load_actions_schema()
|
||||
manifest = {
|
||||
"schemaVersion": 1,
|
||||
"skill": "your-skill-slug",
|
||||
"actions": [
|
||||
{
|
||||
"id": "probe-toolbar",
|
||||
"label": "缺 bind 探测",
|
||||
"description": "toolbar 无 bind 应被 Schema 拒绝",
|
||||
"placements": ["toolbar"],
|
||||
"executionProfile": "sync",
|
||||
"entrypoint": {"type": "cli", "command": "health", "args": []},
|
||||
}
|
||||
],
|
||||
}
|
||||
with self.assertRaises(ValidationError):
|
||||
jsonschema.validate(instance=manifest, schema=schema)
|
||||
|
||||
def test_no_execution_profile_placement_coupling_in_tests(self) -> None:
|
||||
"""守护:本文件不得引入入口位置与 sync/async 的错误硬耦合断言。"""
|
||||
path = os.path.join(get_skill_root(), "tests", "test_actions_manifest.py")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
# 拆开拼接,避免本测试源码自身触发字符串扫描。
|
||||
forbidden_snippets = (
|
||||
"toolbar " + "只能 async",
|
||||
"toolbar only " + "async",
|
||||
'toolbar"' + " and profile != " + '"async"',
|
||||
'toolbar")' + " and profile != " + '"async"',
|
||||
"toolbar must be " + "async",
|
||||
"executionProfile" + " == " + '"async"' + " and " + '"toolbar"',
|
||||
)
|
||||
for snippet in forbidden_snippets:
|
||||
self.assertNotIn(snippet, text)
|
||||
|
||||
def test_template_example_does_not_use_reserved_placements(self) -> None:
|
||||
manifest = _load_actions_manifest()
|
||||
for action in manifest["actions"]:
|
||||
@@ -215,6 +453,17 @@ class TestActionsManifest(unittest.TestCase):
|
||||
msg=f"{action['id']} uses reserved action fields not supported in template Phase 1: {overlap}",
|
||||
)
|
||||
|
||||
def test_default_manifest_does_not_place_health_on_toolbar(self) -> None:
|
||||
"""脚手架默认健康类 Action 不应出现在数据管理 toolbar。"""
|
||||
manifest = _load_actions_manifest()
|
||||
for action in manifest["actions"]:
|
||||
if action["id"] in {"health", "version", "config-path"}:
|
||||
self.assertNotIn(
|
||||
"toolbar",
|
||||
action.get("placements") or [],
|
||||
msg=f"{action['id']} must not be auto-placed on toolbar",
|
||||
)
|
||||
|
||||
def test_actions_md_documents_strict_vs_host_boundary(self) -> None:
|
||||
path = os.path.join(get_skill_root(), "references", "ACTIONS.md")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
@@ -223,14 +472,23 @@ class TestActionsManifest(unittest.TestCase):
|
||||
"严格规范",
|
||||
"向后兼容",
|
||||
"Phase 1",
|
||||
"bind",
|
||||
"bind.tables",
|
||||
"concurrency",
|
||||
"locks",
|
||||
"row",
|
||||
"batch",
|
||||
"additionalProperties",
|
||||
"placements",
|
||||
"executionProfile",
|
||||
):
|
||||
self.assertIn(marker, text, msg=f"ACTIONS.md missing {marker!r}")
|
||||
for forbidden in (
|
||||
"数据管理 toolbar " + "只挂",
|
||||
"toolbar " + "只放 async",
|
||||
"toolbar)→ " + "只挂",
|
||||
"只挂 **" + "async**",
|
||||
):
|
||||
self.assertNotIn(forbidden, text, msg=f"ACTIONS.md must not contain deprecated coupling: {forbidden!r}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -46,6 +46,11 @@ POLICY_IDS = (
|
||||
"POLICY-CONTROL-003",
|
||||
"POLICY-DATA-PATH-001",
|
||||
"POLICY-SKILL-ACTION-001",
|
||||
"POLICY-SKILL-ACTION-002",
|
||||
"POLICY-SKILL-ACTION-003",
|
||||
"POLICY-SKILL-ACTION-004",
|
||||
"POLICY-ARCH-CORE-001",
|
||||
"POLICY-DATA-SYNC-001",
|
||||
)
|
||||
|
||||
STRUCTURE_PATHS = (
|
||||
@@ -871,6 +876,241 @@ class TestPolicySkillAction001(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestPolicySkillAction002(unittest.TestCase):
|
||||
def test_schema_requires_execution_profile(self) -> None:
|
||||
import json
|
||||
|
||||
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
schema = json.load(f)
|
||||
action = schema["$defs"]["action"]
|
||||
self.assertIn(
|
||||
"executionProfile",
|
||||
action.get("required") or [],
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-002",
|
||||
"assets/schemas/skill-actions.schema.json",
|
||||
"executionProfile must be in action.required",
|
||||
),
|
||||
)
|
||||
self.assertEqual(set(action["properties"]["executionProfile"].get("enum") or []), {"sync", "async"})
|
||||
|
||||
def test_manifest_actions_declare_execution_profile(self) -> None:
|
||||
manifest = _load_actions_json(get_skill_root())
|
||||
if manifest is None:
|
||||
return
|
||||
offenders: list[str] = []
|
||||
for action in manifest.get("actions") or []:
|
||||
profile = action.get("executionProfile")
|
||||
if profile not in ("sync", "async"):
|
||||
offenders.append(f"{action.get('id', '?')}: {profile!r}")
|
||||
self.assertEqual(
|
||||
offenders,
|
||||
[],
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-002",
|
||||
"assets/actions.json",
|
||||
"every action must set executionProfile to sync|async:\n" + "\n".join(offenders),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestPolicySkillAction003(unittest.TestCase):
|
||||
def test_schema_defines_bind_and_toolbar_requires_it(self) -> None:
|
||||
import json
|
||||
|
||||
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
schema = json.load(f)
|
||||
self.assertIn(
|
||||
"bind",
|
||||
schema.get("$defs", {}),
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-003",
|
||||
"assets/schemas/skill-actions.schema.json",
|
||||
"$defs.bind missing",
|
||||
),
|
||||
)
|
||||
action = schema["$defs"]["action"]
|
||||
self.assertIn("bind", action.get("properties", {}))
|
||||
then_required = (action.get("then") or {}).get("required") or []
|
||||
self.assertIn(
|
||||
"bind",
|
||||
then_required,
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-003",
|
||||
"assets/schemas/skill-actions.schema.json",
|
||||
"action if/then must require bind when placements contains toolbar",
|
||||
),
|
||||
)
|
||||
|
||||
def test_toolbar_actions_have_bind_tables(self) -> None:
|
||||
import re
|
||||
|
||||
table_re = re.compile(r"^[a-z][a-z0-9_]*$")
|
||||
manifest = _load_actions_json(get_skill_root())
|
||||
if manifest is None:
|
||||
return
|
||||
offenders: list[str] = []
|
||||
for action in manifest.get("actions") or []:
|
||||
if "toolbar" not in (action.get("placements") or []):
|
||||
continue
|
||||
bind = action.get("bind")
|
||||
tables = bind.get("tables") if isinstance(bind, dict) else None
|
||||
if not isinstance(tables, list) or not tables:
|
||||
offenders.append(f"{action.get('id')}: missing bind.tables")
|
||||
continue
|
||||
if len(tables) != len(set(tables)):
|
||||
offenders.append(f"{action.get('id')}: duplicate bind.tables")
|
||||
for table in tables:
|
||||
if not isinstance(table, str) or not table_re.fullmatch(table):
|
||||
offenders.append(f"{action.get('id')}: invalid table {table!r}")
|
||||
self.assertEqual(
|
||||
offenders,
|
||||
[],
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-003",
|
||||
"assets/actions.json",
|
||||
"toolbar actions need legal bind.tables:\n" + "\n".join(offenders),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestPolicySkillAction004(unittest.TestCase):
|
||||
def _forbidden_coupling_phrases(self) -> tuple[str, ...]:
|
||||
# 拆开拼接,避免本测试源码或废止说明原文触发误报。
|
||||
return (
|
||||
"数据管理 toolbar " + "只挂",
|
||||
"toolbar " + "只放 async",
|
||||
"只挂 **" + "async** action",
|
||||
"toolbar " + "只能 async",
|
||||
"toolbar only " + "async",
|
||||
)
|
||||
|
||||
def test_docs_do_not_couple_toolbar_to_async(self) -> None:
|
||||
skill_root = get_skill_root()
|
||||
paths = (
|
||||
os.path.join(skill_root, "references", "ACTIONS.md"),
|
||||
os.path.join(skill_root, "development", "SKILL_ACTION_RUNTIME.md"),
|
||||
os.path.join(skill_root, "SKILL.md"),
|
||||
)
|
||||
hits: list[str] = []
|
||||
for path in paths:
|
||||
text = _read_text(path)
|
||||
for phrase in self._forbidden_coupling_phrases():
|
||||
if phrase in text:
|
||||
hits.append(f"{os.path.relpath(path, skill_root)}: {phrase!r}")
|
||||
self.assertEqual(
|
||||
hits,
|
||||
[],
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-004",
|
||||
"docs",
|
||||
"placements must stay orthogonal to executionProfile:\n" + "\n".join(hits),
|
||||
),
|
||||
)
|
||||
|
||||
def test_runtime_doc_states_orthogonality(self) -> None:
|
||||
text = _read_text(os.path.join(get_skill_root(), "development", "SKILL_ACTION_RUNTIME.md"))
|
||||
for marker in ("正交", "sync|async", "toolbar"):
|
||||
self.assertIn(
|
||||
marker,
|
||||
text,
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-004",
|
||||
"development/SKILL_ACTION_RUNTIME.md",
|
||||
f"missing marker {marker!r}",
|
||||
),
|
||||
)
|
||||
|
||||
def test_schema_then_only_requires_bind_not_execution_profile(self) -> None:
|
||||
"""toolbar→bind 的 if/then 不得顺带约束 executionProfile。"""
|
||||
import json
|
||||
|
||||
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
schema = json.load(f)
|
||||
action = schema["$defs"]["action"]
|
||||
then = action.get("then") or {}
|
||||
self.assertEqual(
|
||||
then.get("required"),
|
||||
["bind"],
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-004",
|
||||
"assets/schemas/skill-actions.schema.json",
|
||||
"action.then must only require bind",
|
||||
),
|
||||
)
|
||||
self.assertNotIn("properties", then)
|
||||
self.assertNotIn("else", action)
|
||||
matrix_test = os.path.join(get_skill_root(), "tests", "test_actions_manifest.py")
|
||||
text = _read_text(matrix_test)
|
||||
self.assertIn(
|
||||
"test_schema_allows_all_placement_execution_profile_combinations",
|
||||
text,
|
||||
msg=_policy_msg(
|
||||
"POLICY-SKILL-ACTION-004",
|
||||
"tests/test_actions_manifest.py",
|
||||
"missing Schema 4×2 orthogonality matrix test",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestPolicyArchCore001(unittest.TestCase):
|
||||
def test_docs_declare_single_core_multi_entry(self) -> None:
|
||||
skill_root = get_skill_root()
|
||||
text = (
|
||||
_read_text(os.path.join(skill_root, "development", "DEVELOPMENT.md"))
|
||||
+ "\n"
|
||||
+ _read_text(os.path.join(skill_root, "development", "SKILL_ACTION_RUNTIME.md"))
|
||||
+ "\n"
|
||||
+ _read_text(os.path.join(skill_root, "SKILL.md"))
|
||||
)
|
||||
for marker in ("单业务内核", "多入口", "domain service"):
|
||||
self.assertIn(
|
||||
marker,
|
||||
text,
|
||||
msg=_policy_msg(
|
||||
"POLICY-ARCH-CORE-001",
|
||||
"development docs / SKILL.md",
|
||||
f"missing architecture marker {marker!r}",
|
||||
),
|
||||
)
|
||||
sample = os.path.join(skill_root, "tests", "samples", "test_action_core_contract.py.sample")
|
||||
self.assertTrue(
|
||||
os.path.isfile(sample),
|
||||
msg=_policy_msg(
|
||||
"POLICY-ARCH-CORE-001",
|
||||
"tests/samples/test_action_core_contract.py.sample",
|
||||
"sample contract missing",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestPolicyDataSync001(unittest.TestCase):
|
||||
def test_schema_md_declares_sync_semantics(self) -> None:
|
||||
text = _read_text(os.path.join(get_skill_root(), "references", "SCHEMA.md"))
|
||||
for marker in ("幂等", "空结果", "事务", "inserted", "导出当前数据表"):
|
||||
self.assertIn(
|
||||
marker,
|
||||
text,
|
||||
msg=_policy_msg(
|
||||
"POLICY-DATA-SYNC-001",
|
||||
"references/SCHEMA.md",
|
||||
f"missing sync marker {marker!r}",
|
||||
),
|
||||
)
|
||||
sample = os.path.join(get_skill_root(), "tests", "samples", "test_sync_contract.py.sample")
|
||||
self.assertTrue(
|
||||
os.path.isfile(sample),
|
||||
msg=_policy_msg(
|
||||
"POLICY-DATA-SYNC-001",
|
||||
"tests/samples/test_sync_contract.py.sample",
|
||||
"sample contract missing",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestPolicyDocs001(unittest.TestCase):
|
||||
def test_policy_matrix_exists_and_lists_policy_ids(self) -> None:
|
||||
skill_root = get_skill_root()
|
||||
|
||||
Reference in New Issue
Block a user