Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c18d308bb | |||
| f0032b2201 | |||
| f3f59278b4 | |||
| 4730cd527d | |||
| dd6236866e | |||
| 07fa0b0038 | |||
| b1e93a323f | |||
| f214598470 | |||
| 5abe67f340 | |||
| 599d7cff48 | |||
| f1060f2a26 | |||
| 864c1a5e2b | |||
| 3e3d8c79ad | |||
| ba3d86553f | |||
| a5b56c09f5 | |||
| daadf8e25c |
21
README.md
21
README.md
@@ -1,4 +1,4 @@
|
||||
# OpenClaw 技能开发模板
|
||||
# 匠厂 技能开发模板(通用业务)
|
||||
|
||||
这是一个**规范化的新技能模板仓库**,用于复制出新的 skill 项目;它本身**不是业务 skill**。
|
||||
|
||||
@@ -6,20 +6,25 @@
|
||||
|
||||
- 对齐当前规范 skill 的目录结构:`assets/`、`references/`、`scripts/`、`tests/`、`evals/`
|
||||
- 对齐当前规范脚手架分层:`scripts/cli`、`scripts/db`、`scripts/service`、`scripts/util`、`scripts/jiangchang_skill_core`
|
||||
- 提供最小可运行入口:`python scripts/main.py health` / `version`
|
||||
- 提供最小可运行入口:`python scripts/main.py health` / `version`,以及通用任务命令骨架 `run` / `logs` / `log-get`
|
||||
- 内置 **隔离测试体系**:`IsolatedDataRoot`、双键环境、`OPENCLAW_TEST_TARGET` 档位与 adapter profile 策略(详见 [`references/TESTING.md`](references/TESTING.md))
|
||||
- 让新技能从一开始就按规范落地,不再沿用旧模板的 `docs/`、`optional/`、`skill_main.py` 结构
|
||||
|
||||
## 新技能使用步骤
|
||||
|
||||
1. 复制本目录为新的 skill 仓库。
|
||||
2. 全局替换 `your-skill-slug`、`your-platform-key`、`您的技能显示名称`、`你的平台名` 等占位内容。
|
||||
2. 全局替换 `your-skill-slug`、`your-platform-key`、`您的技能显示名称` 等占位内容。
|
||||
3. 修改 `SKILL.md`、`references/` 和 `scripts/util/constants.py`。
|
||||
4. 在 `scripts/service/` 中补业务 service 与真正的发布/执行逻辑。
|
||||
5. 用 `python scripts/main.py health` 和 `python scripts/main.py version` 做最小验证。
|
||||
4. 在 `scripts/service/task_service.py` 中实现真实业务编排与外部系统对接。
|
||||
5. 运行 `python tests/run_tests.py -v`,再执行 `python scripts/main.py health`、`version` 做最小验证。
|
||||
|
||||
如果你的技能在平台里默认是非公开的(`access_scope = 0`),建议在 `SKILL.md` 的 `metadata.openclaw.developer_ids` 中填写开发者用户 ID 列表。这样在正式发布后,平台会为这些开发者补可见权限,避免「技能已上架但开发者自己在市场中看不到」。
|
||||
|
||||
开发教程入口:
|
||||
|
||||
- `references/DEVELOPMENT.md`:给技术人员的完整开发步骤说明
|
||||
- <a href="references/REQUIREMENTS.md" target="_blank" rel="noopener noreferrer">需求文档模板</a>:给技术人员编写和查看研发需求的标准模板
|
||||
- <a href="references/DEVELOPMENT.md" target="_blank" rel="noopener noreferrer">开发教程</a>:给技术人员的完整开发步骤说明
|
||||
- <a href="references/TESTING.md" target="_blank" rel="noopener noreferrer">测试开发指南</a>:默认套件、隔离数据根、档位开关与 FakeAdapter 怎么用
|
||||
|
||||
## 目录说明
|
||||
|
||||
@@ -29,7 +34,7 @@
|
||||
| `assets/` | 示例输出与轻量 schema |
|
||||
| `references/` | 面向用户与编排的文档模板 |
|
||||
| `scripts/` | 规范分层后的代码骨架 |
|
||||
| `tests/` | 单元测试或最小回归测试 |
|
||||
| `tests/` | 单元测试与分层测试范式(默认根目录 unittest) |
|
||||
| `evals/` | 人工/半自动评估材料 |
|
||||
| `.github/workflows/release_skill.yaml` | 标准发布工作流 |
|
||||
| `release.ps1` | 对齐现有 skill 的发布脚本入口 |
|
||||
@@ -45,3 +50,5 @@ python scripts/main.py version
|
||||
|
||||
- 不要再往模板里引入旧式 `docs/` 或 `optional/` 目录。
|
||||
- 新技能若不需要某些目录,也建议先保留结构,再按实际业务填充内容。
|
||||
- `metadata.openclaw.developer_ids` 是发布元数据,不是用户展示文案;用于非公开技能的开发者默认可见授权。
|
||||
- **发起 `release.ps1` 之前**,务必确认 `python tests/run_tests.py -v` 已全部通过。
|
||||
|
||||
14
SKILL.md
14
SKILL.md
@@ -1,13 +1,16 @@
|
||||
---
|
||||
name: 技能开发模板(复制后请修改)
|
||||
description: "这是 OpenClaw 技能开发模板仓库,不直接作为业务技能发布。复制为新技能仓库后,按本模板替换 slug、名称、说明、CLI 子命令与 service 实现。"
|
||||
version: 1.0.0
|
||||
name: 技能开发模板(通用业务版)
|
||||
description: "OpenClaw 通用业务技能开发模板,覆盖任务执行、日志记录、外部系统对接、隔离测试等典型能力。复制后请按 references/DEVELOPMENT.md 完成定制。"
|
||||
version: 1.0.14
|
||||
author: 深圳匠厂科技有限公司
|
||||
metadata:
|
||||
openclaw:
|
||||
slug: your-skill-slug
|
||||
emoji: "📦"
|
||||
category: "通用"
|
||||
developer_ids:
|
||||
- 10032
|
||||
- 12428
|
||||
allowed-tools:
|
||||
- bash
|
||||
---
|
||||
@@ -19,7 +22,7 @@ allowed-tools:
|
||||
## 模板使用方式
|
||||
|
||||
1. 复制目录为你的新 skill 仓库。
|
||||
2. 全局替换 `your-skill-slug`、`技能开发模板(复制后请修改)` 等占位词。
|
||||
2. 全局替换 `your-skill-slug`、`技能开发模板(通用业务版)` 等占位词。
|
||||
3. 按 `references/CLI.md`、`scripts/` 分层与 `README.md` 的说明补业务逻辑。
|
||||
|
||||
## 目录约定
|
||||
@@ -39,4 +42,7 @@ python {baseDir}/scripts/main.py version
|
||||
|
||||
- 复制后请同步修改 `scripts/util/constants.py` 中的 `SKILL_SLUG` / `SKILL_VERSION`。
|
||||
- 如技能无需持久化,可保留 `db/` 目录但不主动调用。
|
||||
- `metadata.openclaw.developer_ids` 用于声明技能发布后的默认开发者可见用户 ID 列表。
|
||||
- 当技能在平台中 `access_scope = 0`(不公开)时,任务执行流程会把 `developer_ids` 中的用户自动补写到 `skill_user_access`,使这些开发者仍可在技能市场中查看该技能。
|
||||
- `developer_ids` 建议写为正整数数组;第一个 ID 会作为主开发者同步到 `skills.developer_id`。
|
||||
- 面向用户与编排的文档写在 `references/`,不要再新增旧式 `docs/` / `optional/` 结构。
|
||||
|
||||
@@ -3,5 +3,4 @@
|
||||
- `examples/`:CLI 成功输出形状示例(虚构路径与数据)。
|
||||
- `schemas/`:轻量 JSON Schema 示例(`additionalProperties: true` 允许扩展字段)。
|
||||
|
||||
- 面向用户的介绍见 `references/README.md`。
|
||||
- 面向编排/CLI 的细节见 `references/CLI.md`、`RUNTIME.md`、`SCHEMA.md`。
|
||||
面向编排与用户文档见 `references/README.md`、`references/CLI.md`、`RUNTIME.md`、`SCHEMA.md`。
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"id": 1,
|
||||
"account_id": "demo_account_1",
|
||||
"article_id": 12,
|
||||
"article_title": "示例标题",
|
||||
"status": "published",
|
||||
"task_type": "demo_task",
|
||||
"target_id": "demo_target_1",
|
||||
"input_id": "demo_input_42",
|
||||
"input_title": "示例任务输入标题",
|
||||
"status": "success",
|
||||
"error_msg": null,
|
||||
"result_summary": "{\"processed\": 10, \"skipped\": 0}",
|
||||
"created_at": "2026-04-01T10:00:00",
|
||||
"updated_at": "2026-04-01T10:00:00"
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://openclaw.local/skill-template/publish-log-record.schema.json",
|
||||
"title": "PublishLogRecord",
|
||||
"description": "发布型技能 log-get 返回的单条日志对象模板",
|
||||
"type": "object",
|
||||
"required": ["id", "account_id", "article_id", "article_title", "status", "created_at", "updated_at"],
|
||||
"properties": {
|
||||
"id": { "type": "integer" },
|
||||
"account_id": { "type": ["string", "integer"] },
|
||||
"article_id": { "type": "integer" },
|
||||
"article_title": { "type": "string" },
|
||||
"status": { "type": "string" },
|
||||
"error_msg": { "type": ["string", "null"] },
|
||||
"created_at": { "type": ["string", "null"] },
|
||||
"updated_at": { "type": ["string", "null"] }
|
||||
},
|
||||
"additionalProperties": true
|
||||
}
|
||||
21
assets/schemas/task-log-record.schema.json
Normal file
21
assets/schemas/task-log-record.schema.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://openclaw.local/skill-template/task-log-record.schema.json",
|
||||
"title": "TaskLogRecord",
|
||||
"description": "通用业务技能 log-get 返回的单条任务日志对象模板",
|
||||
"type": "object",
|
||||
"required": ["id", "task_type", "status", "created_at", "updated_at"],
|
||||
"properties": {
|
||||
"id": { "type": "integer" },
|
||||
"task_type": { "type": "string" },
|
||||
"target_id": { "type": ["string", "null"] },
|
||||
"input_id": { "type": ["string", "null"] },
|
||||
"input_title": { "type": ["string", "null"] },
|
||||
"status": { "type": "string" },
|
||||
"error_msg": { "type": ["string", "null"] },
|
||||
"result_summary": { "type": ["string", "null"] },
|
||||
"created_at": { "type": ["string", "null"] },
|
||||
"updated_at": { "type": ["string", "null"] }
|
||||
},
|
||||
"additionalProperties": true
|
||||
}
|
||||
BIN
assets/screenshots/gitea-workflow-success.png
Normal file
BIN
assets/screenshots/gitea-workflow-success.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 32 KiB |
BIN
assets/screenshots/gitea-workflow-tab.png
Normal file
BIN
assets/screenshots/gitea-workflow-tab.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
BIN
assets/screenshots/jc2009-download-page.png
Normal file
BIN
assets/screenshots/jc2009-download-page.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
BIN
assets/screenshots/market-installed-skill.png
Normal file
BIN
assets/screenshots/market-installed-skill.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
BIN
assets/screenshots/new-task-usage.png
Normal file
BIN
assets/screenshots/new-task-usage.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
@@ -1,4 +1,4 @@
|
||||
# skill-template CLI 模板
|
||||
# 通用业务技能模板 CLI 模板
|
||||
|
||||
将 `{baseDir}` 替换为技能根目录(含 `SKILL.md`、`scripts/` 的目录)。所有命令通过 `python {baseDir}/scripts/main.py` 调用。
|
||||
|
||||
@@ -9,28 +9,38 @@ python {baseDir}/scripts/main.py health
|
||||
python {baseDir}/scripts/main.py version
|
||||
```
|
||||
|
||||
## 若你的技能是发布型
|
||||
## 通用业务命令骨架
|
||||
|
||||
建议继续扩展这些子命令:
|
||||
模板默认提供以下命令(复制后按需保留或扩展):
|
||||
|
||||
```bash
|
||||
python {baseDir}/scripts/main.py publish
|
||||
python {baseDir}/scripts/main.py publish -a <账号id> -i <文章id>
|
||||
python {baseDir}/scripts/main.py run
|
||||
python {baseDir}/scripts/main.py run -t <target> -i <input_id>
|
||||
python {baseDir}/scripts/main.py logs
|
||||
python {baseDir}/scripts/main.py logs --task-type disburse --status failed
|
||||
python {baseDir}/scripts/main.py log-get <log_id>
|
||||
```
|
||||
|
||||
含义:
|
||||
- `run`:执行一次任务(具体语义由你的 skill 决定)
|
||||
- `logs`:列出最近 N 条任务日志,可按 task_type / status / target 过滤
|
||||
- `log-get`:按 log_id 查看单条任务日志(JSON)
|
||||
|
||||
## 若你的技能是发布类
|
||||
|
||||
可以把 `run` 命令对外别名为 `publish`,参数 `--target` 别名为 `--account-id`,参数 `--input-id` 保持不变。
|
||||
|
||||
## 若你的技能依赖兄弟技能
|
||||
|
||||
并列技能与 `{baseDir}` 同级时,兄弟技能路径写为:
|
||||
使用 `service.sibling_bridge.call_sibling_json(skill_slug, args)`,不要硬编码兄弟技能名到 sibling_bridge.py 自身。
|
||||
|
||||
```bash
|
||||
python {baseDir}/../content-manager/scripts/main.py ...
|
||||
python {baseDir}/../account-manager/scripts/main.py ...
|
||||
# 假设 base 与兄弟技能同级
|
||||
python {baseDir}/../<sibling-skill-slug>/scripts/main.py ...
|
||||
```
|
||||
|
||||
## 模板约定
|
||||
|
||||
- 最小模板至少保留 `health` / `version`
|
||||
- 发布型技能建议使用 `publish` / `logs` / `log-get`
|
||||
- 不要再用旧模板的 `scripts/skill_main.py`
|
||||
- 通用业务技能建议使用 `run` / `logs` / `log-get`
|
||||
- 不要再用旧模板的 `publish` / `--account-id` / `--article-id` 命名
|
||||
|
||||
@@ -2,14 +2,76 @@
|
||||
|
||||
这份文档是给**技术人员**看的,目标不是解释概念,而是让你拿到 `skill-template` 后,可以**一步一步开发出一个新的 skill**。
|
||||
|
||||
本文默认你开发的是当前最常见的一类技能:
|
||||
本文默认你开发的是当前最常见的一类业务 skill:
|
||||
|
||||
- 有明确的 `scripts/main.py` CLI 入口
|
||||
- 可能需要读写本地 SQLite
|
||||
- 可能需要调用兄弟技能
|
||||
- 可能需要读写本地 SQLite(例如任务日志 `task_logs`)
|
||||
- 可能需要调用兄弟技能或外部 HTTP / RPA
|
||||
- 业务逻辑主要放在 `scripts/service/`
|
||||
|
||||
如果你开发的是发布型 skill,这个模板就是直接可用的起点。
|
||||
发布、对账、代发、报表分析等场景都只是业务特例;模板提供通用骨架,复制后按领域补齐实现即可。
|
||||
|
||||
## 推荐 AI 开发工具
|
||||
|
||||
当前 skill 开发建议尽量配合 AI 编程工具使用。这样做不是为了替代技术人员,而是为了提升以下环节的效率:
|
||||
|
||||
- 搭建标准目录结构
|
||||
- 生成样板代码
|
||||
- 理解旧项目代码
|
||||
- 批量补文档、注释和测试
|
||||
- 辅助排查报错与重构代码
|
||||
|
||||
建议团队统一选择 1 到 2 个主力工具长期使用,避免每个人工具链差异太大,导致协作方式不一致。
|
||||
|
||||
下面先列国外主流工具,再列国内主流工具。链接优先使用官方站点、官方文档或官方安装入口。
|
||||
|
||||
### 国外主流工具
|
||||
|
||||
| 工具 | 类型 | 适合场景 | 官方入口 |
|
||||
|------|------|----------|----------|
|
||||
| Cursor | 独立 AI IDE | 代码编辑、Agent 开发、整仓理解 | <a href="https://www.cursor.com/" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://www.cursor.com/downloads" target="_blank" rel="noopener noreferrer">下载</a> |
|
||||
| Windsurf | 独立 AI IDE | Agent 编程、项目生成、连续开发流 | <a href="https://docs.codeium.com/windsurf" target="_blank" rel="noopener noreferrer">文档</a> / <a href="https://windsurf.com/download" target="_blank" rel="noopener noreferrer">下载</a> |
|
||||
| GitHub Copilot | IDE 插件 / 编程助手 | 日常补全、解释代码、生成函数、配合 VS Code 或 JetBrains 使用 | <a href="https://github.com/copilot" target="_blank" rel="noopener noreferrer">官网</a> |
|
||||
| Claude Code | 终端 / IDE 编程代理 | 命令行开发、代码库分析、自动改代码、运行命令 | <a href="https://www.anthropic.com/claude-code" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://docs.anthropic.com/en/docs/claude-code/" target="_blank" rel="noopener noreferrer">文档</a> |
|
||||
| Codex | 终端 / IDE / Web 编程代理 | OpenAI 官方编码代理,适合代码生成、理解、调试、评审 | <a href="https://developers.openai.com/codex/" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://developers.openai.com/codex/quickstart" target="_blank" rel="noopener noreferrer">快速开始</a> |
|
||||
| Aider | 终端 AI 编程工具 | 已有代码仓库的增量开发、终端协作、快速提交 | <a href="https://www.aider.chat/" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://aider.chat/docs/" target="_blank" rel="noopener noreferrer">文档</a> |
|
||||
| Cline | VS Code / JetBrains 插件 | 编辑器内 Agent 开发、命令执行、浏览器联动调试 | <a href="https://cline.bot/" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://docs.cline.bot/introduction/welcome" target="_blank" rel="noopener noreferrer">文档</a> / <a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank" rel="noopener noreferrer">VS Code 插件</a> |
|
||||
|
||||
### 国内主流工具
|
||||
|
||||
| 工具 | 类型 | 适合场景 | 官方入口 |
|
||||
|------|------|----------|----------|
|
||||
| Trae | 独立 AI IDE | AI 辅助写代码、项目搭建、对话式开发 | <a href="https://www.trae.ai/home" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://www.trae.ai/download" target="_blank" rel="noopener noreferrer">下载</a> |
|
||||
| 通义灵码 | 独立 IDE / IDE 插件 | 国内团队日常编码、问答、补全、代码生成 | <a href="https://tongyi.aliyun.com/lingma/?channel=yy_AiBot" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://tongyi.aliyun.com/lingma/download" target="_blank" rel="noopener noreferrer">下载</a> |
|
||||
| CodeGeeX | IDE 插件 / 开源助手 | 代码补全、生成、注释、跨语言辅助 | <a href="https://github.com/zai-org/CodeGeeX" target="_blank" rel="noopener noreferrer">GitHub</a> / <a href="https://marketplace.visualstudio.com/items?itemName=aminer.codegeex" target="_blank" rel="noopener noreferrer">VS Code 插件</a> |
|
||||
| 腾讯 CodeBuddy | IDE 插件 | 代码补全、测试生成、智能问答、腾讯云开发体系协作 | <a href="https://www.codebuddy.ai/" target="_blank" rel="noopener noreferrer">官网</a> / <a href="https://www.tencentcloud.com/document/product/1256" target="_blank" rel="noopener noreferrer">文档</a> / <a href="https://marketplace.visualstudio.com/items?itemName=Tencent-Cloud.coding-copilot" target="_blank" rel="noopener noreferrer">VS Code 插件</a> |
|
||||
| 百度文心快码(Baidu Comate) | IDE 插件 | 国内研发团队辅助编码、解释、测试、优化 | <a href="https://comate.baidu.com/zh" target="_blank" rel="noopener noreferrer">官网</a> |
|
||||
|
||||
### 选型建议
|
||||
|
||||
如果你们团队主要做这类 Python skill 开发,我建议这样选:
|
||||
|
||||
- 想要一体化最强体验:优先试 `Cursor` 或 `Windsurf`
|
||||
- 想要命令行深度协作:优先试 `Claude Code` 或 `Aider`
|
||||
- 想继续基于 VS Code 插件体系:优先试 `GitHub Copilot`、`Cline`、`通义灵码`、`CodeBuddy`
|
||||
- 想优先使用国内生态与中文支持:优先试 `Trae`、`通义灵码`、`CodeGeeX`、`CodeBuddy`、`文心快码`
|
||||
|
||||
### 团队落地建议
|
||||
|
||||
为了减少培训成本,建议内部至少统一一套主工具方案:
|
||||
|
||||
- 国外方案:`Cursor` + `Claude Code`
|
||||
- 国内方案:`Trae` + `通义灵码`
|
||||
- VS Code 插件方案:`GitHub Copilot` + `Cline`
|
||||
|
||||
不建议每位技术人员完全自由发挥,否则后续在:
|
||||
|
||||
- 提示词写法
|
||||
- 代码修改习惯
|
||||
- 调试方式
|
||||
- 提交节奏
|
||||
|
||||
这些方面会越来越不统一。
|
||||
|
||||
## 1. 先理解模板的定位
|
||||
|
||||
@@ -83,7 +145,7 @@ scripts/
|
||||
|
||||
- `service/`
|
||||
作用:核心业务逻辑
|
||||
比如发布流程、调用兄弟技能、浏览器自动化
|
||||
比如任务编排、调用兄弟技能、外部 API、可选浏览器自动化
|
||||
|
||||
- `util/`
|
||||
作用:常量、日志、路径、时间工具、通用帮助函数
|
||||
@@ -98,10 +160,10 @@ scripts/
|
||||
|
||||
### 第一步:复制模板并改目录名
|
||||
|
||||
例如你要开发 `weibo-publisher`:
|
||||
例如你要开发 `your-skill-slug`(或 `disburse-payroll-icbc` 一类领域 skill):
|
||||
|
||||
1. 复制 `skill-template`
|
||||
2. 新目录改成 `weibo-publisher`
|
||||
2. 新目录改成与 `slug` 一致的名称(如 `your-skill-slug`)
|
||||
3. 初始化为独立 git 仓库
|
||||
4. 关联它自己的远端仓库
|
||||
|
||||
@@ -114,7 +176,7 @@ scripts/
|
||||
1. `SKILL.md`
|
||||
2. `scripts/util/constants.py`
|
||||
3. `references/` 下的文案
|
||||
4. `scripts/service/` 下的平台占位文件名
|
||||
4. `scripts/service/` 下的业务占位实现(优先改 `task_service.py`)
|
||||
|
||||
最先要统一的是:
|
||||
|
||||
@@ -124,23 +186,26 @@ scripts/
|
||||
- 平台内部键
|
||||
- 日志 logger 名
|
||||
|
||||
此外,如果该技能发布后默认不公开(`access_scope = 0`),建议一开始就把 `SKILL.md` 中的 `metadata.openclaw.developer_ids` 配好。这样后续发布到平台时,开发者本人仍能在技能市场中看到并验证该技能。
|
||||
|
||||
## 5. 哪些占位内容必须替换
|
||||
|
||||
复制后,至少要全局检查并替换下面这些内容:
|
||||
|
||||
- `your-skill-slug`
|
||||
- `your-platform-key`
|
||||
- `技能开发模板(复制后请修改)`
|
||||
- `your-platform-key`(若 skill 涉及外部平台对接,可能会用到这类占位)
|
||||
- `技能开发模板(通用业务版)`
|
||||
- `你的平台名`
|
||||
- `platform_playwright.py`
|
||||
- `openclaw.skill.your_skill_slug`
|
||||
|
||||
如果你是做发布型 skill,通常还要替换:
|
||||
如果你的 skill 对外 CLI 需要自定义文案或别名(例如发布类对外仍叫 `publish`),通常还要替换:
|
||||
|
||||
- `publish` 命令中的中文提示
|
||||
- `run` 命令中的中文提示与别名策略(见 `references/CLI.md`)
|
||||
- `references/CLI.md` 的命令示例
|
||||
- `references/README.md` 的用户话术
|
||||
- `references/SCHEMA.md` 的数据库文件名
|
||||
- `references/SCHEMA.md` 的字段映射补充说明
|
||||
|
||||
如需浏览器自动化,不要在模板里保留空的 `platform_playwright.py`;请按业务新建 `xxx_playwright.py`(命名自定),并在 `task_service.py` 中按需引用。
|
||||
|
||||
## 6. `SKILL.md` 应该怎么写
|
||||
|
||||
@@ -150,9 +215,22 @@ scripts/
|
||||
|
||||
- 技能名称
|
||||
- 技能描述
|
||||
- slug
|
||||
- category
|
||||
- dependencies
|
||||
- `slug`
|
||||
作用:技能的唯一英文标识,通常用于仓库名、发布包名、运行时目录名、平台主键匹配等
|
||||
示例:`your-skill-slug`、`disburse-payroll-icbc`、`tax-invoice-verify`
|
||||
- `category`
|
||||
作用:技能在平台中的分类,用于市场展示与归类,不是代码内部键
|
||||
示例:`通用`、`内容`、`办公协作`、`物流`、`抖音`、`小红书`
|
||||
- `developer_ids`(如需给非公开技能自动补开发者可见权限)
|
||||
作用:声明发布后默认拥有可见权限的开发者用户 ID 列表
|
||||
- `dependencies`
|
||||
作用:声明该技能依赖的兄弟技能或运行前置能力,便于平台或编排层识别依赖关系
|
||||
示例(按业务填写;发布类可能会依赖账号 / 内容技能,其它领域可能完全不同):
|
||||
```yaml
|
||||
dependencies:
|
||||
required:
|
||||
- some-sibling-skill
|
||||
```
|
||||
- 何时使用本技能
|
||||
- 对用户的引导话术
|
||||
- CLI 使用原则
|
||||
@@ -164,6 +242,33 @@ scripts/
|
||||
- 代码注释
|
||||
- `service/` 实现里
|
||||
|
||||
### 关于 `metadata.openclaw.developer_ids`
|
||||
|
||||
这是一个平台发布元数据字段,用于解决下面这个问题:
|
||||
|
||||
- 技能发布后若平台记录中的 `access_scope = 0`,技能默认不公开
|
||||
- 如果不额外授权,连开发者自己也可能在技能市场里看不到这个技能
|
||||
|
||||
因此可以在 `SKILL.md` 中声明:
|
||||
|
||||
```yaml
|
||||
metadata:
|
||||
openclaw:
|
||||
slug: your-skill-slug
|
||||
category: 通用
|
||||
developer_ids:
|
||||
- 1032
|
||||
- 12428
|
||||
```
|
||||
|
||||
约定如下:
|
||||
|
||||
- 只允许填写正整数用户 ID
|
||||
- 推荐使用数组,即使当前只有 1 个开发者
|
||||
- 发布时平台会把这些用户自动补写到 `skill_user_access`
|
||||
- 第一个 ID 会同步到 `skills.developer_id`
|
||||
- 一期只做“补授权”,不会因为你 later 修改数组而自动撤销旧授权
|
||||
|
||||
## 7. `references/` 应该放什么
|
||||
|
||||
`references/` 是当前规范 skill 的文档中心,建议至少有这些:
|
||||
@@ -183,6 +288,9 @@ scripts/
|
||||
- `DEVELOPMENT.md`
|
||||
写给技术人员的开发教程,也就是本文档
|
||||
|
||||
- `TESTING.md`
|
||||
写给技术人员的测试分层、隔离数据根与档位开关指南(详见 [`references/TESTING.md`](TESTING.md))
|
||||
|
||||
如果后面某个 skill 需要更细的说明,可以再加:
|
||||
|
||||
- `ERRORS.md`
|
||||
@@ -214,8 +322,8 @@ scripts/
|
||||
也就是说,`cli/app.py` 的职责是:
|
||||
|
||||
1. 打印帮助
|
||||
2. 定义 `publish / logs / log-get / health / version`
|
||||
3. 把参数转交给 `service.publish_service`
|
||||
2. 定义 `run / logs / log-get / health / version`
|
||||
3. 把参数转交给 `service.task_service`
|
||||
|
||||
不要在 `cli/app.py` 里直接写:
|
||||
|
||||
@@ -229,14 +337,14 @@ scripts/
|
||||
|
||||
通常可以这样拆:
|
||||
|
||||
- `publish_service.py`
|
||||
放命令编排、参数兜底、结果分流
|
||||
- `task_service.py`
|
||||
放命令编排、参数兜底、结果分流(例如 `cmd_run`)
|
||||
|
||||
- `sibling_bridge.py`
|
||||
放兄弟技能调用,例如调 `account-manager`、`content-manager`
|
||||
放通用兄弟技能子进程工具(`call_sibling_json`);**具体调用哪个 slug 由业务在 `task_service.py` 决定**,不要在本文件硬编码发布类专用 helper
|
||||
|
||||
- `*_playwright.py`
|
||||
放浏览器后台自动化
|
||||
- `xxx_playwright.py`(按需新建)
|
||||
浏览器后台自动化 **不在模板默认结构中**;若确有需要,按命名约定自建模块并在 `task_service.py` 引用
|
||||
|
||||
- `entitlement_service.py`
|
||||
放鉴权逻辑
|
||||
@@ -247,7 +355,7 @@ scripts/
|
||||
|
||||
推荐流向是:
|
||||
|
||||
`cli.app` -> `service.publish_service` -> `service.sibling_bridge` / `service.xxx_playwright` -> `db`
|
||||
`cli.app` -> `service.task_service` -> `service.sibling_bridge` / (可选)`service.xxx_playwright` -> `db`
|
||||
|
||||
## 11. `db` 层怎么写
|
||||
|
||||
@@ -256,8 +364,8 @@ scripts/
|
||||
- `db/connection.py`
|
||||
只做连接和建表
|
||||
|
||||
- `db/publish_logs_repository.py`
|
||||
只做增删查改
|
||||
- `db/task_logs_repository.py`
|
||||
只做增删查改(模板默认表:`task_logs`)
|
||||
|
||||
不要在 `db` 层里:
|
||||
|
||||
@@ -276,10 +384,7 @@ scripts/
|
||||
|
||||
来做调用。
|
||||
|
||||
常见调用对象是:
|
||||
|
||||
- `account-manager`
|
||||
- `content-manager`
|
||||
调用哪些兄弟技能由具体业务决定;请在 `task_service.py` 中使用 `service.sibling_bridge.call_sibling_json(skill_slug, args)` 或 `get_sibling_main_path(skill_slug)`,不要在本模板仓库的 `sibling_bridge.py` 中堆积特定技能函数。
|
||||
|
||||
调用原则:
|
||||
|
||||
@@ -288,27 +393,27 @@ scripts/
|
||||
3. 用子进程调用
|
||||
4. 机器可读输出优先 JSON
|
||||
|
||||
## 13. 如何开发发布型 skill
|
||||
## 13. 如何开发一个新 skill
|
||||
|
||||
如果你开发的是 publisher 类 skill,建议按这个顺序做:
|
||||
不管你开发的是发布类、采集类、分析类还是知识库类 skill,建议都先按下面这个顺序推进:
|
||||
|
||||
1. 先把目录结构搭完整
|
||||
2. 先让 `health` / `version` 跑通
|
||||
3. 再让 `publish_service.py` 的骨架跑通
|
||||
4. 再接 `sibling_bridge.py`
|
||||
5. 最后再写 `*_playwright.py`
|
||||
3. 再把核心 `service` 骨架跑通
|
||||
4. 再接兄弟技能桥接、数据库或外部系统
|
||||
5. 最后再补浏览器自动化、复杂流程编排或高风险集成
|
||||
|
||||
不要一开始就直接写页面选择器。
|
||||
不要一开始就直接写页面选择器、复杂接口编排或深层业务逻辑。
|
||||
|
||||
推荐先确保这些基础能力正常:
|
||||
|
||||
- 能取到账号
|
||||
- 能取到文章
|
||||
- 能写日志
|
||||
- CLI 子命令通了
|
||||
- CLI 入口能跑通
|
||||
- 基础命令输出稳定
|
||||
- 关键依赖能取到
|
||||
- 日志或本地状态能落下来
|
||||
- 错误返回值格式定好了
|
||||
|
||||
然后再进浏览器自动化。
|
||||
如果你的 skill 属于外联型 / RPA 型,可以把上面的“核心 `service`”具体落成 `task_service.py`,再按需接 `sibling_bridge.py`、(可选)`*_playwright.py`。这只是示例路径组合,不代表模板绑定某一业务领域。
|
||||
|
||||
## 14. 本地开发的最小验证顺序
|
||||
|
||||
@@ -325,12 +430,19 @@ python scripts/main.py version
|
||||
|
||||
```bash
|
||||
python scripts/main.py -h
|
||||
python scripts/main.py publish -h
|
||||
python scripts/main.py <your-command> -h
|
||||
```
|
||||
|
||||
### 3. 验证本地日志与数据库
|
||||
|
||||
如果是发布型 skill,再继续:
|
||||
如果你的 skill 需要本地日志或数据库,再继续:
|
||||
|
||||
```bash
|
||||
python scripts/main.py <your-log-command>
|
||||
python scripts/main.py <your-detail-command> <id>
|
||||
```
|
||||
|
||||
如果你沿用了模板中的通用任务日志骨架,那么这里可以具体对应成:
|
||||
|
||||
```bash
|
||||
python scripts/main.py logs
|
||||
@@ -342,10 +454,133 @@ python scripts/main.py log-get 1
|
||||
比如:
|
||||
|
||||
```bash
|
||||
python scripts/main.py publish
|
||||
python scripts/main.py <your-command>
|
||||
```
|
||||
|
||||
## 15. 发布前检查清单
|
||||
## 14.5 测试驱动的开发顺序
|
||||
|
||||
新 skill 不应该等所有业务做完才补测试。建议在每个开发阶段都先把对应测试跑一遍:
|
||||
|
||||
1. **目录搭建后**:跑 `python tests/run_tests.py -v`,确认 6 个默认测试套件全部通过。
|
||||
- 此时 `test_skill_metadata.py` 会校验 `SKILL.md` slug 与 `constants.SKILL_SLUG` 一致;如果你只改了一边,会立刻发现。
|
||||
2. **改完 constants 后**:再跑一次必跑套件,确认未引入回归。
|
||||
3. **写完 service 业务后**:从 `tests/samples/test_service_contract.py.sample` 复制一份做契约测试。
|
||||
4. **接外部系统时**:写在 `tests/integration/`,并配合 `OPENCLAW_TEST_TARGET` 显式开启。
|
||||
|
||||
详见 `references/TESTING.md`。
|
||||
|
||||
## 15. 发布到正式环境验证
|
||||
|
||||
在执行 `release.ps1` 之前,必须先在本地确认 `python tests/run_tests.py -v` 通过。测试不通过不得发起正式发布。
|
||||
|
||||
当本地开发、自测和联调完成后,还需要把 skill 发布到正式环境做一次完整验证。建议技术人员严格按下面顺序执行,不要跳步。
|
||||
|
||||
### 第一步:在 skill 根目录执行 `release.ps1`
|
||||
|
||||
在当前 skill 仓库根目录执行:
|
||||
|
||||
```powershell
|
||||
.\release.ps1
|
||||
```
|
||||
|
||||
如果你的技能使用了 `metadata.openclaw.developer_ids`,那么这一步触发的发布工作流除了同步 `skills` / `skill_versions` 外,还会在平台侧自动补开发者可见权限。测试非公开技能时,建议重点验证这部分是否生效。
|
||||
|
||||
这一步会自动完成标准发布动作,包括:
|
||||
|
||||
1. 检查当前仓库状态
|
||||
2. 自动提交尚未提交的改动
|
||||
3. 推送最新代码到远程仓库
|
||||
4. 自动创建新的语义化版本 tag
|
||||
5. 推送 tag,触发后续 CI 流程
|
||||
|
||||
如果你只是想先预览发布动作,可以先执行:
|
||||
|
||||
```powershell
|
||||
.\release.ps1 -DryRun
|
||||
```
|
||||
|
||||
### 第二步:到 Gitea 仓库查看工作流
|
||||
|
||||
发布命令执行完成后,远程仓库会自动触发 Gitea 工作流。此时应立即进入对应 skill 的仓库页面,切换到“工作流”页签查看执行状态。
|
||||
|
||||
重点确认:
|
||||
|
||||
- 是否已经出现最新一次发布记录
|
||||
- 是否由最新提交触发
|
||||
- 是否成功执行完 `release_skill.yaml`
|
||||
|
||||
下面这张图演示了在仓库页进入“工作流”的位置:
|
||||
|
||||

|
||||
|
||||
下面这张图演示了工作流成功后的状态页面:
|
||||
|
||||

|
||||
|
||||
### 第三步:确认工作流执行成功
|
||||
|
||||
只有当工作流状态为成功,才说明正式发布产物已经正确构建完成。
|
||||
|
||||
如果工作流失败,不要继续做平台验证,而应该先回到代码仓库排查,例如:
|
||||
|
||||
- 发布脚本是否正常推送
|
||||
- `SKILL.md`、`scripts/`、`references/` 是否齐全
|
||||
- 工作流文件是否存在
|
||||
- 发布包结构是否符合模板规范
|
||||
|
||||
### 第四步:进入匠厂平台下载安装包
|
||||
|
||||
当工作流成功后,就可以进入匠厂平台验证最终安装效果。
|
||||
|
||||
匠厂产品下载地址:
|
||||
|
||||
- [https://jc2009.com/product.html](https://jc2009.com/product.html)
|
||||
|
||||
打开页面后,下载并安装匠厂客户端。下面这张图演示了下载入口位置:
|
||||
|
||||

|
||||
|
||||
匠厂产品页可从这里进入:[产品下载 - 匠厂](https://jc2009.com/product.html)
|
||||
|
||||
### 第五步:安装匠厂后,在技能市场检查最新 skill
|
||||
|
||||
安装并启动匠厂后,进入左侧“技能市场”,搜索或查找刚刚发布的 skill,确认以下内容:
|
||||
|
||||
- 技能可以被正常检索到
|
||||
- 技能名称、说明、版本信息正确
|
||||
- 最新版本已经同步出来
|
||||
- 可以正常安装或更新
|
||||
|
||||
下面这张图演示了在技能市场中查看已发布 skill 的位置:
|
||||
|
||||

|
||||
|
||||
### 第六步:安装并实际启用该 skill
|
||||
|
||||
在技能市场中找到目标 skill 后,执行安装或更新操作,确保客户端本地已经拿到最新版本。
|
||||
|
||||
这一步建议至少确认:
|
||||
|
||||
- 安装按钮可以正常执行
|
||||
- 安装后状态正常
|
||||
- 不会出现缺文件、缺入口或安装失败的问题
|
||||
|
||||
### 第七步:在“新建任务”中实际使用该 skill
|
||||
|
||||
安装完成后,不要只停留在“已安装”状态,还需要进入“新建任务”页面,真正调用一次该 skill,完成最终验证。
|
||||
|
||||
建议至少验证:
|
||||
|
||||
- 新任务中可以正常选择或触发该 skill
|
||||
- skill 能被正确唤起
|
||||
- 主要命令或主流程可以运行
|
||||
- 返回结果、日志和行为符合预期
|
||||
|
||||
下面这张图演示了安装后在任务界面中实际使用 skill 的场景:
|
||||
|
||||

|
||||
|
||||
## 16. 发布前检查清单
|
||||
|
||||
每个新 skill 发布前,建议技术人员逐条确认:
|
||||
|
||||
@@ -353,14 +588,17 @@ python scripts/main.py publish
|
||||
- [ ] `SKILL.md` 中 slug、名称、描述都已替换
|
||||
- [ ] `scripts/util/constants.py` 已修改
|
||||
- [ ] `references/CLI.md` 示例命令已改成真实命令
|
||||
- [ ] `service` 下的平台文件名已改对
|
||||
- [ ] `service` 下的核心业务文件(如 `task_service.py`)已按领域改名并实现
|
||||
- [ ] 没有残留旧平台名
|
||||
- [ ] `health` / `version` 可运行
|
||||
- [ ] `.gitignore` 生效,没有把 `__pycache__` 提交进去
|
||||
- [ ] `release.ps1` 存在
|
||||
- [ ] `.github/workflows/release_skill.yaml` 存在
|
||||
- [ ] `python tests/run_tests.py -v` 全部通过
|
||||
- [ ] 没有新增默认必跑测试访问真实网络或浏览器
|
||||
- [ ] 如有 integration 测试需求,已写在 `tests/integration/` 下并保持 `.sample` 后缀
|
||||
|
||||
## 16. 常见错误
|
||||
## 17. 常见错误
|
||||
|
||||
### 错误 1:只改了目录名,没改 slug
|
||||
|
||||
@@ -380,11 +618,11 @@ python scripts/main.py publish
|
||||
表现:
|
||||
|
||||
- 兄弟技能筛选账号失败
|
||||
- 发布命令走错平台
|
||||
- `run` 命令走错平台或 task_type
|
||||
|
||||
要检查:
|
||||
|
||||
- `publish_service.py`
|
||||
- `task_service.py`
|
||||
- `sibling_bridge.py`
|
||||
- `references/CLI.md`
|
||||
|
||||
@@ -413,7 +651,7 @@ python scripts/main.py publish
|
||||
- 不做旧结构兼容
|
||||
- 统一走 `references/` + `scripts/main.py`
|
||||
|
||||
## 17. 推荐开发顺序总结
|
||||
## 18. 推荐开发顺序总结
|
||||
|
||||
如果让一个新人照着做,我建议他按这个顺序:
|
||||
|
||||
@@ -423,11 +661,12 @@ python scripts/main.py publish
|
||||
4. 改 `references/`
|
||||
5. 改 `scripts/cli/app.py`
|
||||
6. 改 `scripts/service/`
|
||||
7. 跑 `health` / `version`
|
||||
8. 再做业务联调
|
||||
9. 最后 release
|
||||
7. 跑 `python tests/run_tests.py -v`
|
||||
8. 跑 `health` / `version`
|
||||
9. 再做业务联调
|
||||
10. 最后 release
|
||||
|
||||
## 18. 这份模板的底线要求
|
||||
## 19. 这份模板的底线要求
|
||||
|
||||
以后新建 skill,至少要满足这几点:
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: "这是规范化的新技能模板说明,不直接作为业务技能使用。复制后请替换技能名、平台名、CLI 示例与 service 实现。"
|
||||
description: "规范化的新技能模板说明;复制后替换名称、CLI 示例与 task_service 等业务实现。"
|
||||
---
|
||||
|
||||
# 技能模板说明
|
||||
@@ -9,17 +9,35 @@ description: "这是规范化的新技能模板说明,不直接作为业务技
|
||||
## 它提供什么
|
||||
|
||||
- 标准目录结构
|
||||
- 最小 CLI 入口
|
||||
- 发布型技能常见的日志表骨架
|
||||
- `service` 层占位模块
|
||||
- 最小 CLI 入口(`run` / `logs` / `log-get` / `health` / `version`)
|
||||
- 通用任务日志表骨架(`task_logs`)
|
||||
- `service` 层占位模块(`task_service.py`、通用 `sibling_bridge.py`)
|
||||
- 成熟的隔离测试体系(IsolatedDataRoot、FakeAdapter、6 档测试 target、profile 策略)
|
||||
- 与现有规范 skill 一致的发布脚本与 GitHub workflow
|
||||
|
||||
## 复制后你需要改什么
|
||||
|
||||
- `SKILL.md` 中的名称、描述、slug、触发说明
|
||||
- `SKILL.md` 中 `metadata.openclaw.developer_ids`(如需让非公开技能默认授权给开发者查看)
|
||||
- `references/CLI.md` 里的命令示例
|
||||
- `scripts/util/constants.py` 中的 slug / 版本 / logger 名
|
||||
- `scripts/service/` 下的真实业务实现
|
||||
- `scripts/service/task_service.py` 中的 `cmd_run` 真实业务逻辑
|
||||
- 如有特定 task_type,在 `references/SCHEMA.md` 中补充字段映射说明
|
||||
|
||||
## `developer_ids` 是做什么的
|
||||
|
||||
`metadata.openclaw.developer_ids` 是平台发布元数据,不是终端用户文案。
|
||||
|
||||
它用于声明:当技能发布后,如果平台侧将该技能设置为 `access_scope = 0`(不公开),哪些开发者用户仍应自动获得可见权限。
|
||||
|
||||
约定如下:
|
||||
|
||||
- 字段位置:`SKILL.md` -> `metadata.openclaw.developer_ids`
|
||||
- 推荐格式:正整数数组,例如 `[1032, 12428]`
|
||||
- 发布效果:发布接口会把这些用户补写到 `skill_user_access`
|
||||
- 第一个 ID 会作为主开发者同步到 `skills.developer_id`
|
||||
|
||||
如果你的技能本来就是公开技能,或暂时不需要开发者专属可见性,这个字段可以留空数组。
|
||||
|
||||
## 不建议再保留的旧结构
|
||||
|
||||
|
||||
340
references/REQUIREMENTS.md
Normal file
340
references/REQUIREMENTS.md
Normal file
@@ -0,0 +1,340 @@
|
||||
# 技能需求文档模板
|
||||
|
||||
这份文档用于给技术人员、产品人员和实施人员统一描述某个 skill 的研发需求。
|
||||
|
||||
建议原则:
|
||||
|
||||
- 一个 skill 对应一份主需求文档
|
||||
- 需求先写清楚,再进入开发
|
||||
- 文档描述“要做什么”和“做到什么程度”,不要在这里堆实现细节
|
||||
- 实现方式、代码结构、发布流程,分别放到 `DEVELOPMENT.md`、`CLI.md`、`SCHEMA.md`、`RUNTIME.md`
|
||||
|
||||
如果你是从 `skill-template` 复制新技能,请复制本文件后,把下面所有占位内容替换成你的真实项目内容。
|
||||
|
||||
---
|
||||
|
||||
# REQUIREMENTS
|
||||
|
||||
## 1. 文档目标
|
||||
|
||||
说明这份需求文档的作用,以及它解决什么问题。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 本文档用于明确 `【技能名称】` 的研发范围、交付标准、依赖关系和验收要求。
|
||||
- 技术人员应以本文件作为开发范围依据,以避免实现偏差、范围蔓延或理解不一致。
|
||||
|
||||
示例:
|
||||
|
||||
- 本文档用于明确 `your-skill-slug`(示例:`disburse-payroll-icbc`)的研发范围、交付标准、依赖关系和验收要求。
|
||||
|
||||
## 2. 业务背景
|
||||
|
||||
说明为什么要做这个 skill,它服务什么业务场景,解决什么实际问题。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 当前业务场景中,用户需要在 `【目标平台】` 完成 `【业务动作】`。
|
||||
- 现有流程主要依赖人工处理,存在 `【效率低 / 容易出错 / 不可批量 / 不可追踪】` 等问题。
|
||||
- 因此需要开发 `【技能名称】`,将该流程标准化、自动化,并接入匠厂技能体系中。
|
||||
|
||||
示例:
|
||||
|
||||
- 当前财务团队需要将工资代发批次与银行接口对账,人工导出表格、核对差异耗时且易错。
|
||||
- 因此需要开发 `disburse-payroll-icbc`,用于自动拉取代发结果、写入任务日志 `task_logs` 并输出对账摘要,支持审计追踪。
|
||||
|
||||
## 3. 开发目标
|
||||
|
||||
说明本次开发希望最终交付什么结果。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 完成 `【技能名称】` 的标准目录结构搭建
|
||||
- 完成 CLI 入口与基础命令
|
||||
- 完成核心业务流程
|
||||
- 完成与兄弟技能或外部系统的必要集成
|
||||
- 完成正式环境发布验证
|
||||
|
||||
示例:
|
||||
|
||||
- 完成 `your-skill-slug` 的标准 skill 结构建设
|
||||
- 提供 `health`、`version`、`run`、`logs`、`log-get` 等命令
|
||||
- 支持对接银行 / 薪酬系统 API(示例),并记录任务执行结果
|
||||
- 支持写入任务日志 `task_logs`,并可在正式环境中安装验证
|
||||
|
||||
## 4. 功能范围
|
||||
|
||||
说明这次开发明确要实现哪些功能。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 支持 `【命令1】`
|
||||
- 支持 `【命令2】`
|
||||
- 支持读取 `【数据来源】`
|
||||
- 支持执行 `【核心业务动作】`
|
||||
- 支持记录 `【日志 / 状态 / 结果】`
|
||||
|
||||
建议将功能拆成“必须实现”和“可后续扩展”。
|
||||
|
||||
示例:
|
||||
|
||||
### 必须实现
|
||||
|
||||
- 支持 `python scripts/main.py health`
|
||||
- 支持 `python scripts/main.py version`
|
||||
- 支持 `python scripts/main.py run`
|
||||
- 支持从 `some-sibling-skill` 读取批次元数据(如需要)
|
||||
- 支持执行核心业务编排(HTTP / 批处理 / 可选 RPA)
|
||||
- 支持写入任务日志(`task_logs`)
|
||||
|
||||
### 可后续扩展
|
||||
|
||||
- 支持定时批跑
|
||||
- 支持失败自动重试
|
||||
- 支持多目标轮询
|
||||
|
||||
## 5. 非功能要求
|
||||
|
||||
说明除功能外,对稳定性、可维护性、目录规范、日志、编码等方面的要求。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 目录结构必须符合当前 skill 模板规范
|
||||
- 入口必须统一为 `scripts/main.py`
|
||||
- 输出格式应尽量机读友好
|
||||
- 错误前缀统一为 `ERROR:`
|
||||
- Windows 环境下需保证 UTF-8 输出兼容
|
||||
- 必须具备基本日志能力
|
||||
|
||||
示例:
|
||||
|
||||
- 项目结构必须对齐 `skill-template`
|
||||
- CLI 入口统一使用 `scripts/main.py`
|
||||
- 关键执行结果应可通过 JSON 或固定文本结构返回
|
||||
- 任务日志必须可追踪(`task_logs`)
|
||||
- 不允许重新引入旧模板中的 `docs/`、`optional/` 或 `scripts/skill_main.py`
|
||||
|
||||
## 6. 输入输出要求
|
||||
|
||||
说明这个 skill 接收什么输入,产出什么输出。
|
||||
|
||||
模板写法:
|
||||
|
||||
### 输入
|
||||
|
||||
- `【输入参数1】`
|
||||
- `【输入参数2】`
|
||||
- `【依赖系统返回的数据】`
|
||||
|
||||
### 输出
|
||||
|
||||
- `【标准输出】`
|
||||
- `【错误输出】`
|
||||
- `【数据库记录】`
|
||||
- `【日志文件】`
|
||||
|
||||
示例:
|
||||
|
||||
### 输入
|
||||
|
||||
- `target_id`:可选,指定任务目标(账号 / 客户 / 平台)
|
||||
- `input_id`:可选,指定输入批次或记录
|
||||
- 兄弟技能返回的结构化数据(如有)
|
||||
|
||||
### 输出
|
||||
|
||||
- 成功结果(stdout / JSON)
|
||||
- 错误输出(`ERROR:` / `FAIL:`)
|
||||
- 在本地数据库写入 `task_logs`
|
||||
- 在日志目录中写入执行日志
|
||||
|
||||
## 7. 依赖的兄弟技能或外部系统
|
||||
|
||||
说明开发该 skill 时依赖哪些内部技能或外部平台。
|
||||
|
||||
模板写法:
|
||||
|
||||
### 兄弟技能依赖
|
||||
|
||||
- `【skill-a】`:作用是 `【用途】`
|
||||
- `【skill-b】`:作用是 `【用途】`
|
||||
|
||||
### 外部系统依赖
|
||||
|
||||
- `【平台名】`:作用是 `【用途】`
|
||||
- `【浏览器 / API / 第三方服务】`:作用是 `【用途】`
|
||||
|
||||
示例:
|
||||
|
||||
### 兄弟技能依赖
|
||||
|
||||
- `some-sibling-skill`:提供主数据或凭证索引(按业务填写)
|
||||
|
||||
### 外部系统依赖
|
||||
|
||||
- 银行 / 政务 HTTP API(示例):核心外部接口
|
||||
- Chromium / Chrome / Edge(可选):用于浏览器自动化
|
||||
- Gitea:用于代码托管和发布工作流
|
||||
- 匠厂客户端:用于正式环境安装与验证
|
||||
|
||||
## 8. 不在本次范围内的内容
|
||||
|
||||
这一节非常重要,用来明确本次“不做什么”,避免研发越做越散。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 本次不实现 `【功能A】`
|
||||
- 本次不处理 `【平台B】`
|
||||
- 本次不做 `【高级能力】`
|
||||
- 本次不兼容 `【旧结构 / 旧逻辑】`
|
||||
|
||||
示例:
|
||||
|
||||
- 本次不实现多租户隔离之外的附加报表
|
||||
- 本次不实现实时流式处理
|
||||
- 本次不实现自动重试机制
|
||||
- 本次不兼容旧模板中的历史目录结构
|
||||
|
||||
## 9. 验收标准
|
||||
|
||||
说明什么情况下才算真正开发完成。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 代码结构符合模板规范
|
||||
- 最小命令可运行
|
||||
- 核心命令可运行
|
||||
- 正式环境可安装
|
||||
- 匠厂中可看到最新版本
|
||||
- 可以在新建任务中实际使用
|
||||
|
||||
示例:
|
||||
|
||||
- `health`、`version` 命令执行正常
|
||||
- `run` 主流程可运行
|
||||
- 发布后 Gitea 工作流成功
|
||||
- 匠厂技能市场能看到最新版本
|
||||
- skill 可以正常安装
|
||||
- 安装后可在“新建任务”中调用
|
||||
|
||||
- `python tests/run_tests.py -v` 必跑测试全部通过
|
||||
- 任务日志(task_logs)写入和查询符合预期
|
||||
- 真实联调(如有)已在 tests/integration/ 中验证,且默认套件不包含真实外联
|
||||
|
||||
## 10. 开发注意事项
|
||||
|
||||
说明研发过程中必须特别注意的事项。
|
||||
|
||||
模板写法:
|
||||
|
||||
- 不要修改无关 skill
|
||||
- 不要破坏现有模板规范
|
||||
- 优先遵守目录和分层约定
|
||||
- 不要在 CLI 层堆业务逻辑
|
||||
- 发布前必须先做本地最小验证
|
||||
|
||||
示例:
|
||||
|
||||
- 只允许修改当前 skill 仓库,不要改动其他兄弟项目
|
||||
- 如使用浏览器自动化,优先复用已验证过的定位器和流程
|
||||
- `cli` 只做参数解析,核心逻辑统一放到 `service`
|
||||
- 发布前必须完成本地验证、工作流验证和正式环境安装验证
|
||||
|
||||
## 11. 变更记录
|
||||
|
||||
这一节用于记录需求文档本身的变化,不是 git 提交记录的替代,而是给技术人员看“需求范围怎么变了”。
|
||||
|
||||
模板写法:
|
||||
|
||||
| 日期 | 版本 | 变更人 | 变更内容 |
|
||||
|------|------|--------|----------|
|
||||
| 2026-04-13 | v1.0 | 张三 | 初版需求文档 |
|
||||
| 2026-04-14 | v1.1 | 李四 | 增加正式环境验收要求 |
|
||||
|
||||
---
|
||||
|
||||
## 建议使用方式
|
||||
|
||||
建议每个新 skill 开发时,按下面顺序使用文档:
|
||||
|
||||
1. 先写 `references/REQUIREMENTS.md`
|
||||
2. 再按 `references/DEVELOPMENT.md` 进入开发
|
||||
3. 开发过程中补充 `CLI.md`、`SCHEMA.md`、`RUNTIME.md`、`TESTING.md`
|
||||
4. 发布前回到 `REQUIREMENTS.md` 对照验收标准逐项检查
|
||||
|
||||
## 最小模板示例
|
||||
|
||||
下面给出一个可直接参考的简化版示例:
|
||||
|
||||
```md
|
||||
# REQUIREMENTS
|
||||
|
||||
## 1. 文档目标
|
||||
|
||||
本文档用于明确 `your-skill-slug` 的研发需求、范围和验收标准,作为开发与测试的统一依据。
|
||||
|
||||
## 2. 业务背景
|
||||
|
||||
采购审计需要将政府采购公告结构化归档;人工复制粘贴效率低,需要可追溯的任务日志。
|
||||
|
||||
## 3. 开发目标
|
||||
|
||||
- 完成 `your-skill-slug` 的标准 skill 结构
|
||||
- 支持核心业务批处理 / HTTP 对接主流程
|
||||
- 支持任务日志记录(task_logs)
|
||||
|
||||
## 4. 功能范围
|
||||
|
||||
- 支持 `health`
|
||||
- 支持 `version`
|
||||
- 支持 `run`
|
||||
- 支持查询任务日志(logs / log-get)
|
||||
|
||||
## 5. 非功能要求
|
||||
|
||||
- 入口统一为 `scripts/main.py`
|
||||
- 保持 UTF-8 输出
|
||||
- 结构符合 skill 模板规范
|
||||
|
||||
## 6. 输入输出要求
|
||||
|
||||
### 输入
|
||||
|
||||
- `target_id`
|
||||
- `input_id`
|
||||
|
||||
### 输出
|
||||
|
||||
- 成功结果
|
||||
- 错误信息
|
||||
- task_logs 记录
|
||||
|
||||
## 7. 依赖的兄弟技能或外部系统
|
||||
|
||||
- (按需填写兄弟 skill)
|
||||
- 政务公告站点 HTTP API(示例)
|
||||
|
||||
## 8. 不在本次范围内的内容
|
||||
|
||||
- 不实现浏览器可视化回放(如需另行立项)
|
||||
- 不实现自动重试
|
||||
|
||||
## 9. 验收标准
|
||||
|
||||
- 命令可运行
|
||||
- `python tests/run_tests.py -v` 全部通过
|
||||
- task_logs 写入符合 SCHEMA 约定
|
||||
- 能完成正式环境安装验证
|
||||
- 能在新建任务中使用
|
||||
|
||||
## 10. 开发注意事项
|
||||
|
||||
- 不修改无关项目
|
||||
- 不引入旧模板结构
|
||||
|
||||
## 11. 变更记录
|
||||
|
||||
| 日期 | 版本 | 变更人 | 变更内容 |
|
||||
|------|------|--------|----------|
|
||||
| 2026-04-13 | v1.0 | 张三 | 初版 |
|
||||
```
|
||||
@@ -33,6 +33,17 @@
|
||||
{...}/{skill_slug}.db
|
||||
```
|
||||
|
||||
## 测试时的运行时隔离
|
||||
|
||||
本模板的 `tests/_support.IsolatedDataRoot` 会在测试期间同时设置:
|
||||
|
||||
- `CLAW_DATA_ROOT` / `JIANGCHANG_DATA_ROOT` → 临时 tempfile 目录
|
||||
- `CLAW_USER_ID` / `JIANGCHANG_USER_ID` → `_test`
|
||||
|
||||
退出时四个变量恢复,临时目录删除。所有 DB / 文件写入都被限制在临时目录内,不污染本机。
|
||||
|
||||
详见 `references/TESTING.md` 第 3 节。
|
||||
|
||||
## 编码与输出
|
||||
|
||||
- Windows 终端建议在 `scripts/main.py` 里做 UTF-8 stdout/stderr 包装
|
||||
|
||||
@@ -4,20 +4,35 @@
|
||||
|
||||
`{DATA_ROOT}/{USER_ID}/your-skill-slug/your-skill-slug.db`
|
||||
|
||||
## 发布型技能推荐日志表
|
||||
## 通用任务日志表(task_logs)
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `id` | 自增主键 |
|
||||
| `account_id` | 账号 id |
|
||||
| `article_id` | 文章 id |
|
||||
| `article_title` | 标题快照 |
|
||||
| `status` | `published` / `failed` / `require_login` |
|
||||
| `error_msg` | 错误说明 |
|
||||
| `created_at` | Unix 时间戳 |
|
||||
| `updated_at` | Unix 时间戳 |
|
||||
模板默认建表:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | INTEGER PK | 自增主键 |
|
||||
| `task_type` | TEXT NOT NULL | 任务类型(disburse / reconcile / verify ...) |
|
||||
| `target_id` | TEXT | 任务目标(账号、平台、客户等的 ID) |
|
||||
| `input_id` | TEXT | 输入对象 ID |
|
||||
| `input_title` | TEXT | 输入对象标题快照 |
|
||||
| `status` | TEXT NOT NULL | success / failed / partial / require_login 等 |
|
||||
| `error_msg` | TEXT | 错误说明 |
|
||||
| `result_summary` | TEXT | 结果摘要(建议存 JSON 字符串) |
|
||||
| `created_at` | INTEGER | Unix 时间戳 |
|
||||
| `updated_at` | INTEGER | Unix 时间戳 |
|
||||
|
||||
## 不同业务的字段映射建议
|
||||
|
||||
| 业务场景 | task_type | target_id 含义 | input_id 含义 |
|
||||
|---|---|---|---|
|
||||
| 发布类 | publish | 账号 ID | 文章 ID |
|
||||
| 工资代发 | disburse | 付款账户 | 工资表批次 ID |
|
||||
| 对账 | reconcile | 银行 / 平台 | 对账批次 ID |
|
||||
| 发票验真 | verify | 税务地区 | 发票批次 ID |
|
||||
| 报关 | declare | 港口 / 海关 | 报关批次 ID |
|
||||
|
||||
## 模板原则
|
||||
|
||||
- 模板不做历史迁移兼容设计
|
||||
- 新 skill 直接从当前 schema 起步
|
||||
- 业务有特殊字段时,建议放 `result_summary`(JSON 字符串),不要乱加列
|
||||
|
||||
185
references/TESTING.md
Normal file
185
references/TESTING.md
Normal file
@@ -0,0 +1,185 @@
|
||||
# 测试开发指南
|
||||
|
||||
面向复制 `skill-template` 后的新业务 skill:**如何把自动化测试当作一等公民**,而不是等业务写完再补文档级别的空话。本文串起模板自带的 unittest 入口、`tests/` 目录分层与安全档位约定;**更细的开关取值、表格字段与环境变量组合仍以 [`tests/README.md`](../tests/README.md) 为权威来源**。建议你随手开一个编辑器分页:`references/TESTING.md`(本篇)、[`references/DEVELOPMENT.md`](DEVELOPMENT.md)(整体节奏)、[`tests/README.md`](../tests/README.md)(落地细则)。
|
||||
|
||||
默认心智模型可以用一句话概括:**根目录 `test_*.py` = CI / 本地每次提交都应能通过的无外联套件**;`*integration*`、`*.sample`、`desktop/` = 只在人被明确要求时才启用的高风险或重量级路径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 测试体系总览
|
||||
|
||||
本模板把测试分成四层漏斗:**默认必跑(unittest + `run_tests.py`)**、从 `tests/samples/` **按需复制的 service / golden**、放在 `tests/integration/` **默认不落盘的仿真或真实联调范式(多数仍是 `.sample`)**、以及 **desktop E2E(pytest + 宿主 SDK)**。
|
||||
|
||||
[`tests/run_tests.py`](../tests/run_tests.py) 只做三件事:把 `scripts/` 与 `tests/` 放进 `sys.path`、做 Windows UTF-8 包装、收集 **`tests/` 根目录**下的 `test_*.py`。它不递归子目录——这正是刻意的安全边界:**不想让 AI 或拷贝粘贴 accidentally 把 integration 拉进默认套件**。
|
||||
|
||||
当你在设计一个新 skill 的测试策略时,请先问自己:**这段代码在没有外部凭证与浏览器的前提下是否有意义?** 若有,留在默认套件;若无,放进 integration / `.sample`,并要求明确的 `OPENCLAW_TEST_TARGET` 组合开关。
|
||||
|
||||
更深表格化的目录映射、`FakeAdapter` 与 profile 的耦合细节见 [`tests/README.md`](../tests/README.md) 开头章节『我该把测试写在哪里』。
|
||||
|
||||
---
|
||||
|
||||
## 2. 默认必跑测试要做什么
|
||||
|
||||
必跑套件要像一个紧张的守门员:**快、确定、离线**。典型覆盖:
|
||||
|
||||
- CLI:导入 [`cli.app`](../scripts/cli/app.py) 走解析链路、`health` / `version` / `logs` / `log-get` 冒烟;
|
||||
- **真实 subprocess**:[`tests/test_entrypoint_subprocess.py`](../tests/test_entrypoint_subprocess.py) 再调用一遍 `python scripts/main.py`,防路径漂移;
|
||||
- 运行时:`runtime_paths` 与 **`CLAW_*` / `JIANGCHANG_*` 并发兜底;
|
||||
- `SKILL.md` YAML slug vs [`constants.SKILL_SLUG`](../scripts/util/constants.py);
|
||||
- SQLite 骨架:`task_logs` 创建幂等与仓储读写;
|
||||
- **adapter profile**:[`tests/test_adapter_profile_policy.py`](../tests/test_adapter_profile_policy.py) + [`adapter_test_utils`](../tests/adapter_test_utils.py) ——验证在未授权情况下绝不误判开启真实网络/RPA。
|
||||
|
||||
**原则:`tests/test_*.py` 不允许隐形访问外网、不允许拉起真实浏览器、不允许读写开发者机器的真实数据根**。如果需要仿真服务器,也应仅在 integration(并由档位变量放行)。
|
||||
|
||||
套件能力与表格参见 [`tests/README.md`](../tests/README.md) 「1.2 默认套件覆盖」。
|
||||
|
||||
---
|
||||
|
||||
## 3. 数据隔离:IsolatedDataRoot
|
||||
|
||||
[`tests/_support.py`](../tests/_support.py) 提供的上下文管理器 `IsolatedDataRoot()`:进入一个专用临时目录,**镜像写入四套变量**:`CLAW_DATA_ROOT`、`JIANGCHANG_DATA_ROOT`(同一 tempfile)、以及用户镜像 ID:`CLAW_USER_ID`、`JIANGCHANG_USER_ID` → `_test`。
|
||||
|
||||
结束时:**恢复原 environ**,删除目录。
|
||||
|
||||
这样可以断言:**SQLite DB / spill files / caches** 都在 sandbox;不会在开发者桌面遗留 `{REAL_ROOT}`。
|
||||
|
||||
示例:
|
||||
|
||||
```python
|
||||
from _support import IsolatedDataRoot
|
||||
|
||||
def test_whatever():
|
||||
with IsolatedDataRoot():
|
||||
from db.connection import init_db
|
||||
init_db()
|
||||
# …断言读写均在隔离路径…
|
||||
```
|
||||
|
||||
**不要把真实凭证路径硬编码进默认测试**:隔离不等于你有权触碰真实目录。
|
||||
|
||||
---
|
||||
|
||||
## 4. 测试目标档位(OPENCLAW_TEST_TARGET)
|
||||
|
||||
模板采用统一闸门:**你想跑到哪一层外部世界,就用变量明说**。合法档位(非法值会让 helper 抛错)如下——**直接摘录自 [`tests/README.md`](../tests/README.md) §5.1**:
|
||||
|
||||
| 取值 | 含义 |
|
||||
|------|------|
|
||||
| `unit` | **默认**:单元 / 内存 / mock,不跑仿真与真实外联 |
|
||||
| `mock` | 与 `unit` 类似的安全档位(显式语义) |
|
||||
| `simulator_api` | 仅允许 **仿真 HTTP** 类集成(如 localhost) |
|
||||
| `simulator_rpa` | 仅允许 **仿真页面 / 录播 RPA** |
|
||||
| `real_api` | 真实 API(另需 `ALLOW_REAL_API=1`) |
|
||||
| `real_rpa` | 真实 RPA(另需 `ALLOW_REAL_RPA=1`) |
|
||||
|
||||
未设置环境变量 ⇒ 等价 `unit`。
|
||||
|
||||
授权开关(显式 `1`)语义 **`ALLOW_REAL_API` / `ALLOW_REAL_RPA` / `ALLOW_WRITE_ACTIONS`**——摘录 [`tests/README.md`](../tests/README.md) §5.2:
|
||||
|
||||
| 变量 | 作用 |
|
||||
|------|------|
|
||||
| `ALLOW_REAL_API=1` | 允许 `real_api` profile 访问真实 HTTP 通道 |
|
||||
| `ALLOW_REAL_RPA=1` | 允许 `real_rpa` profile 驱动真实浏览器/RPA |
|
||||
| `ALLOW_WRITE_ACTIONS=1` | 在 `real_*` 下允许**写**操作(提交表单、下单等) |
|
||||
|
||||
默认策略摘要见 §5.3:**不要在 unittest 必跑路径误把闸门打开**。
|
||||
|
||||
兼容别名:`OPENCLOW_TEST_TARGET`(历史拼写)。
|
||||
|
||||
---
|
||||
|
||||
## 5. FakeAdapter:怎么模拟外部系统
|
||||
|
||||
[`tests/adapter_test_utils.py`](../tests/adapter_test_utils.py) 暴露 `FakeAdapter`,典型四种 **mode**:
|
||||
|
||||
| mode | 用途 |
|
||||
|------|------|
|
||||
| `success` | 构造干净的成功响应路径 |
|
||||
| `timeout` | 模拟悬挂 / 慢链路 |
|
||||
| `invalid_response` | 畸形负载 / schema drift |
|
||||
| `unauthorized` | token / license / cookie 失效语义 |
|
||||
|
||||
**何时用它**:service 层出现『调用第三方 HTTP / RPA stub』但又不能把真实系统纳入 CI。**契约测试**(复制 [`tests/samples/test_service_contract.py.sample`](../tests/samples/test_service_contract.py.sample))应优先组合 FakeAdapter,而不是直接把 CLI when-json 断言堆上天。
|
||||
|
||||
把它看成:**你把不确定性折叠进可控表格**,而不是在生产日志里才第一次看到错位字段。
|
||||
|
||||
---
|
||||
|
||||
## 6. 怎么从 .sample 启用一个测试
|
||||
|
||||
步骤模板:
|
||||
|
||||
1. 找到范式文件(例如 [`tests/samples/test_service_contract.py.sample`](../tests/samples/test_service_contract.py.sample))。
|
||||
2. **复制**到 `tests/` 根:`tests/test_service_contract.py`(去掉 `.sample`)。
|
||||
3. 打开副本:**替换占位函数名 /技能特有枚举 / adapter profile**,删掉与本技能无关的示例断言。
|
||||
4. 本地执行:`python tests/run_tests.py -v [可选筛选关键词]`。
|
||||
5. **不要把 integration `.sample` 批量改名混进根目录**——除非你已经读过 [`tests/integration/README.md`](../tests/integration/README.md) 的风险清单。
|
||||
|
||||
Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../tests/samples/test_golden_cases.py.sample))。
|
||||
|
||||
---
|
||||
|
||||
## 7. 真实联调测试的安全约束
|
||||
|
||||
任何 touching **真实租户数据** 的路径:
|
||||
|
||||
1. **禁止**硬编码 token / cookie / 内部域名落入仓库;
|
||||
2. **禁止**默认套件 silent import integration;
|
||||
3. **真实 RPA** 只能标记为手动触发(双人复核 / 本地 `.env` 不入库)。
|
||||
|
||||
范式阅读 [`tests/integration/README.md`](../tests/integration/README.md):那里有针对凭证来源、目录 artifact 忽略策略的补充。
|
||||
|
||||
记住:**测试代码也是一种部署面**,别把 staging 凭证烘焙进来。
|
||||
|
||||
---
|
||||
|
||||
## 8. 新 skill 的最小测试清单
|
||||
|
||||
以下清单 **原文摘自 [`tests/README.md`](../tests/README.md) 「新技能最小测试清单」**(复制新仓库后逐项勾选):
|
||||
|
||||
- [ ] `python tests/run_tests.py -v` 能通过。
|
||||
- [ ] `python scripts/main.py health` 能通过。
|
||||
- [ ] `python scripts/main.py version` 输出 JSON,且 `skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。
|
||||
- [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。
|
||||
- [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API,不打开真实 RPA。
|
||||
- [ ] 至少有 1 个成功路径测试。
|
||||
- [ ] 至少有 1 个缺必填字段 / 非法输入测试。
|
||||
- [ ] 如果有 adapter,至少覆盖 timeout / unauthorized / invalid response(可用 fake 模拟)。
|
||||
- [ ] 如果有解析 / 计算 / 校验类业务,至少保留 1 组 golden fixture(脱敏)。
|
||||
- [ ] 真实 API / 真实 RPA 测试只放 `tests/integration/`,并且默认 `.sample`,不默认运行。
|
||||
|
||||
---
|
||||
|
||||
## 9. AI 编程工具使用测试时的红线
|
||||
|
||||
改编自 [`tests/README.md`](../tests/README.md) 「AI 编程工具注意事项」,压缩成 skill 开发者视角:
|
||||
|
||||
| 红线 | 解释 |
|
||||
|------|------|
|
||||
| 不改业务凑测试 | 除非需求变更已确认,否则别让 CI 绿通过阉割业务分支达成 |
|
||||
| **默认套件零外联** | 不把真实 HTTP / 浏览器写进 `tests/test_*.py` |
|
||||
| `.sample` 尊重 | 集成范式改名前先读完 README;别让 `.sample` silent 变成根测试 |
|
||||
| **零硬编码凭证** | token / cookie / 生产 URL → 用虚构域名或 vault ref |
|
||||
| mock 优先 | 逻辑应在 service + FakeAdapter,而不是巨胖 CLI 断言 |
|
||||
| 结构化错误 | 断言错误码字段,而不是 substring of stderr 漂移集合 |
|
||||
| **integration = 显式开关** | `OPENCLAW_TEST_TARGET` + `ALLOW_REAL_*` / `ALLOW_WRITE_ACTIONS` |
|
||||
|
||||
---
|
||||
|
||||
## 10. 测试和发布的关系
|
||||
|
||||
**在运行 [`release.ps1`](../release.ps1) 之前,`python tests/run_tests.py -v` 必须绿色**。失败的默认套件意味着:
|
||||
|
||||
- 打包路径可能根本不可运行;
|
||||
- CI 加密前的静态假设可能在宿主崩溃;
|
||||
- metadata slug 漂移将被市场拒绝。
|
||||
|
||||
把『本地 unittest 绿』视作 tag 的前置条件,而不是『有空再跑』。发布流水线成功后仍要做安装验证——那是另一个维度;**测试是第一个维度**。
|
||||
|
||||
---
|
||||
|
||||
## 延伸阅读
|
||||
|
||||
- [`tests/README.md`](../tests/README.md) — 表格、变量与目录细则
|
||||
- [`references/DEVELOPMENT.md`](DEVELOPMENT.md) §14.5 — 测试驱动的开发顺序
|
||||
- [`tests/integration/README.md`](../tests/integration/README.md) — 高风险用法
|
||||
@@ -6,11 +6,11 @@ import argparse
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
from service.publish_service import (
|
||||
from service.task_service import (
|
||||
cmd_health,
|
||||
cmd_log_get,
|
||||
cmd_logs,
|
||||
cmd_publish,
|
||||
cmd_run,
|
||||
cmd_version,
|
||||
)
|
||||
from util.argparse_zh import ZhArgumentParser
|
||||
@@ -25,34 +25,34 @@ def _cli_str_or_none(raw: Optional[str]) -> Optional[str]:
|
||||
return v or None
|
||||
|
||||
|
||||
def _handle_publish(args: argparse.Namespace) -> int:
|
||||
tail = [str(x).strip() for x in (args.publish_tail or []) if str(x).strip()]
|
||||
def _handle_run(args: argparse.Namespace) -> int:
|
||||
tail = [str(x).strip() for x in (args.run_tail or []) if str(x).strip()]
|
||||
if len(tail) > 2:
|
||||
print("❌ 参数过多。")
|
||||
print("用法:python main.py publish [账号id [文章id]] | publish [-a 账号id] [-i 文章id]")
|
||||
print("用法:python main.py run [target [input_id]] | run [-t target] [-i input_id]")
|
||||
return 1
|
||||
|
||||
t_acc: Optional[str] = None
|
||||
t_art: Optional[str] = None
|
||||
t_target: Optional[str] = None
|
||||
t_input: Optional[str] = None
|
||||
if len(tail) == 2:
|
||||
t_acc, t_art = tail[0], tail[1]
|
||||
t_target, t_input = tail[0], tail[1]
|
||||
elif len(tail) == 1:
|
||||
if tail[0].isdigit():
|
||||
t_art = tail[0]
|
||||
t_input = tail[0]
|
||||
else:
|
||||
t_acc = tail[0]
|
||||
t_target = tail[0]
|
||||
|
||||
pick_a = _cli_str_or_none(getattr(args, "account_id", None))
|
||||
pick_i = _cli_str_or_none(getattr(args, "article_id", None))
|
||||
acc = pick_a or t_acc
|
||||
art = pick_i or t_art
|
||||
return cmd_publish(account_id=acc, article_id=art)
|
||||
pick_t = _cli_str_or_none(getattr(args, "target", None))
|
||||
pick_i = _cli_str_or_none(getattr(args, "input_id", None))
|
||||
target = pick_t or t_target
|
||||
input_id = pick_i or t_input
|
||||
return cmd_run(target=target, input_id=input_id)
|
||||
|
||||
|
||||
def _print_full_usage() -> None:
|
||||
print("模板技能(main.py)可用命令:")
|
||||
print(" python main.py publish [账号id [文章id]] [-a 账号] [-i 文章id]")
|
||||
print(" python main.py logs [--limit N] [--status s] [--account-id a]")
|
||||
print("通用业务技能模板(main.py)可用命令:")
|
||||
print(" python main.py run [target [input_id]] [-t target] [-i input_id]")
|
||||
print(" python main.py logs [--limit N] [--status s] [--task-type t] [--target-id tid]")
|
||||
print(" python main.py log-get <log_id>")
|
||||
print(" python main.py health")
|
||||
print(" python main.py version")
|
||||
@@ -61,24 +61,27 @@ def _print_full_usage() -> None:
|
||||
def build_parser() -> ZhArgumentParser:
|
||||
p = ZhArgumentParser(
|
||||
prog="main.py",
|
||||
description="模板技能:发布命令骨架、日志查询、健康检查、版本输出。",
|
||||
description="通用业务技能模板:任务执行命令骨架、日志查询、健康检查、版本输出。",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
sub = p.add_subparsers(dest="cmd", required=True, parser_class=ZhArgumentParser)
|
||||
|
||||
sp = sub.add_parser("publish", help="发布型技能命令骨架")
|
||||
sp.add_argument("--account-id", "-a", default=None, metavar="账号id")
|
||||
sp.add_argument("--article-id", "-i", default=None, metavar="文章id")
|
||||
sp.add_argument("publish_tail", nargs="*", metavar="位置参数")
|
||||
sp.set_defaults(handler=_handle_publish)
|
||||
sp = sub.add_parser("run", help="任务执行命令骨架")
|
||||
sp.add_argument("--target", "-t", default=None, metavar="目标")
|
||||
sp.add_argument("--input-id", "-i", default=None, metavar="输入id", dest="input_id")
|
||||
sp.add_argument("run_tail", nargs="*", metavar="位置参数")
|
||||
sp.set_defaults(handler=_handle_run)
|
||||
|
||||
sp = sub.add_parser("logs", help="查看发布记录")
|
||||
sp = sub.add_parser("logs", help="查看任务日志")
|
||||
sp.add_argument("--limit", type=int, default=10)
|
||||
sp.add_argument("--status", default=None)
|
||||
sp.add_argument("--account-id", default=None)
|
||||
sp.set_defaults(handler=lambda a: cmd_logs(limit=a.limit, status=a.status, account_id=a.account_id))
|
||||
sp.add_argument("--task-type", default=None, dest="task_type")
|
||||
sp.add_argument("--target-id", default=None, dest="target_id")
|
||||
sp.set_defaults(handler=lambda a: cmd_logs(
|
||||
limit=a.limit, status=a.status, task_type=a.task_type, target_id=a.target_id
|
||||
))
|
||||
|
||||
sp = sub.add_parser("log-get", help="按 log_id 查看单条发布记录(JSON)")
|
||||
sp = sub.add_parser("log-get", help="按 log_id 查看单条任务日志(JSON)")
|
||||
sp.add_argument("log_id")
|
||||
sp.set_defaults(handler=lambda a: cmd_log_get(a.log_id))
|
||||
|
||||
@@ -97,8 +100,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
if not argv:
|
||||
_print_full_usage()
|
||||
return 1
|
||||
if len(argv) == 2 and argv[0] not in {"publish", "logs", "log-get", "health", "version", "-h", "--help"}:
|
||||
return cmd_publish(account_id=argv[0], article_id=argv[1])
|
||||
if len(argv) == 2 and argv[0] not in {"run", "logs", "log-get", "health", "version", "-h", "--help"}:
|
||||
return cmd_run(target=argv[0], input_id=argv[1])
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
return int(args.handler(args))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""SQLite 连接与日志表迁移模板。"""
|
||||
"""SQLite 连接与任务日志表迁移模板。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,13 +17,15 @@ def init_db() -> None:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS publish_logs (
|
||||
CREATE TABLE IF NOT EXISTS task_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id TEXT NOT NULL,
|
||||
article_id INTEGER NOT NULL,
|
||||
article_title TEXT,
|
||||
task_type TEXT NOT NULL,
|
||||
target_id TEXT,
|
||||
input_id TEXT,
|
||||
input_title TEXT,
|
||||
status TEXT NOT NULL,
|
||||
error_msg TEXT,
|
||||
result_summary TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
"""publish_logs 表读写模板。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.timeutil import now_unix
|
||||
|
||||
|
||||
def save_publish_log(
|
||||
account_id: str,
|
||||
article_id: int,
|
||||
article_title: str,
|
||||
status: str,
|
||||
error_msg: Optional[str] = None,
|
||||
) -> int:
|
||||
init_db()
|
||||
now = now_unix()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO publish_logs (account_id, article_id, article_title, status, error_msg, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(account_id, int(article_id), article_title or "", status, error_msg, now, now),
|
||||
)
|
||||
new_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return new_id
|
||||
|
||||
|
||||
def list_publish_logs(
|
||||
limit: int,
|
||||
status: Optional[str] = None,
|
||||
account_id: Optional[str] = None,
|
||||
) -> List[Tuple[Any, ...]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sql = (
|
||||
"SELECT id, account_id, article_id, article_title, status, error_msg, created_at, updated_at "
|
||||
"FROM publish_logs WHERE 1=1 "
|
||||
)
|
||||
params: List[Any] = []
|
||||
if status:
|
||||
sql += "AND status = ? "
|
||||
params.append(status)
|
||||
if account_id:
|
||||
sql += "AND account_id = ? "
|
||||
params.append(account_id)
|
||||
sql += "ORDER BY created_at DESC, id DESC LIMIT ?"
|
||||
params.append(int(limit))
|
||||
cur.execute(sql, tuple(params))
|
||||
return list(cur.fetchall())
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_publish_log_by_id(log_id: int) -> Optional[Tuple[Any, ...]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id, account_id, article_id, article_title, status, error_msg, created_at, updated_at FROM publish_logs WHERE id = ?",
|
||||
(int(log_id),),
|
||||
)
|
||||
return cur.fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
88
scripts/db/task_logs_repository.py
Normal file
88
scripts/db/task_logs_repository.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""task_logs 表读写模板。
|
||||
|
||||
通用业务日志仓储:记录每次任务执行的 task_type / target / input / 状态 / 结果摘要。
|
||||
不假设任何特定业务(发布、对账、审核等都可复用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.timeutil import now_unix
|
||||
|
||||
|
||||
def save_task_log(
|
||||
task_type: str,
|
||||
target_id: Optional[str] = None,
|
||||
input_id: Optional[str] = None,
|
||||
input_title: Optional[str] = None,
|
||||
status: str = "success",
|
||||
error_msg: Optional[str] = None,
|
||||
result_summary: Optional[str] = None,
|
||||
) -> int:
|
||||
init_db()
|
||||
now = now_unix()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO task_logs
|
||||
(task_type, target_id, input_id, input_title, status, error_msg, result_summary, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(task_type, target_id, input_id, input_title or "", status, error_msg, result_summary, now, now),
|
||||
)
|
||||
new_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return new_id
|
||||
|
||||
|
||||
def list_task_logs(
|
||||
limit: int,
|
||||
status: Optional[str] = None,
|
||||
task_type: Optional[str] = None,
|
||||
target_id: Optional[str] = None,
|
||||
) -> List[Tuple[Any, ...]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sql = (
|
||||
"SELECT id, task_type, target_id, input_id, input_title, status, error_msg, result_summary, "
|
||||
"created_at, updated_at FROM task_logs WHERE 1=1 "
|
||||
)
|
||||
params: List[Any] = []
|
||||
if status:
|
||||
sql += "AND status = ? "
|
||||
params.append(status)
|
||||
if task_type:
|
||||
sql += "AND task_type = ? "
|
||||
params.append(task_type)
|
||||
if target_id:
|
||||
sql += "AND target_id = ? "
|
||||
params.append(target_id)
|
||||
sql += "ORDER BY created_at DESC, id DESC LIMIT ?"
|
||||
params.append(int(limit))
|
||||
cur.execute(sql, tuple(params))
|
||||
return list(cur.fetchall())
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_task_log_by_id(log_id: int) -> Optional[Tuple[Any, ...]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id, task_type, target_id, input_id, input_title, status, error_msg, result_summary, "
|
||||
"created_at, updated_at FROM task_logs WHERE id = ?",
|
||||
(int(log_id),),
|
||||
)
|
||||
return cur.fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -43,14 +43,10 @@ def get_user_id() -> str:
|
||||
def _looks_like_skills_root(path: str) -> bool:
|
||||
if not path or not os.path.isdir(path):
|
||||
return False
|
||||
# 通过常见基础技能存在与否,判断这是不是 skills 根目录
|
||||
# 这里列举的是平台基础设施类技能,不包含具体业务技能
|
||||
for marker in (
|
||||
"llm-manager",
|
||||
"content-manager",
|
||||
"account-manager",
|
||||
"sohu-publisher",
|
||||
"toutiao-publisher",
|
||||
"gongzhonghao-publisher",
|
||||
"weibo-publisher",
|
||||
"skill-template",
|
||||
):
|
||||
if os.path.isdir(os.path.join(path, marker)):
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""后台自动化占位模块模板。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
async def publish(account: Dict[str, Any], article: Dict[str, Any], account_id: str) -> str:
|
||||
_ = (account, article, account_id)
|
||||
return "ERROR:NOT_IMPLEMENTED 请复制模板后将本文件改名为具体平台模块并实现后台自动化逻辑"
|
||||
@@ -1,4 +1,8 @@
|
||||
"""兄弟技能 CLI 调用模板。"""
|
||||
"""兄弟技能 CLI 调用模板。
|
||||
|
||||
通用工具:通过子进程调用同级其他 skill 的 main.py,并解析 JSON 输出。
|
||||
具体调用哪些兄弟技能,由具体业务 skill 决定(在 task_service.py 中按需 import 调用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,7 +16,19 @@ from util.logging_config import subprocess_env_with_trace
|
||||
from util.runtime_paths import get_skills_root
|
||||
|
||||
|
||||
def _call_json_script(script_path: str, args: List[str]) -> Optional[Dict[str, Any]]:
|
||||
def call_sibling_json(skill_slug: str, args: List[str]) -> Optional[Dict[str, Any]]:
|
||||
"""通用兄弟技能调用器。
|
||||
|
||||
Args:
|
||||
skill_slug: 兄弟技能的 slug(即同级目录名)。
|
||||
args: 传给 main.py 的命令行参数列表。
|
||||
|
||||
Returns:
|
||||
若兄弟技能输出可解析的 JSON 对象则返回 dict;否则返回 None。
|
||||
"""
|
||||
script_path = os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
if not os.path.isfile(script_path):
|
||||
return None
|
||||
proc = subprocess.run(
|
||||
[sys.executable, script_path, *args],
|
||||
capture_output=True,
|
||||
@@ -31,9 +47,19 @@ def _call_json_script(script_path: str, args: List[str]) -> Optional[Dict[str, A
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def get_account_manager_main_path() -> str:
|
||||
return os.path.join(get_skills_root(), "account-manager", "scripts", "main.py")
|
||||
def get_sibling_main_path(skill_slug: str) -> str:
|
||||
"""获取兄弟技能的 main.py 绝对路径。
|
||||
|
||||
使用示例(在你的 task_service.py 中):
|
||||
from service.sibling_bridge import get_sibling_main_path, call_sibling_json
|
||||
# 调用名为 account-manager 的兄弟技能:
|
||||
result = call_sibling_json("account-manager", ["list", "--limit", "10"])
|
||||
"""
|
||||
return os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
|
||||
|
||||
def get_content_manager_main_path() -> str:
|
||||
return os.path.join(get_skills_root(), "content-manager", "scripts", "main.py")
|
||||
# ============================================================
|
||||
# 复制本模板后,按需在你自己的 task_service.py 中调用上面的工具。
|
||||
# 不要在本文件中硬编码具体兄弟技能函数(如 get_account_manager_main_path),
|
||||
# 那是发布类技能的特定需求,不属于通用模板。
|
||||
# ============================================================
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
"""发布编排、日志查询模板。"""
|
||||
"""任务编排、日志查询模板。
|
||||
|
||||
通用业务编排层:负责参数校验、鉴权、调用具体业务实现、写入任务日志。
|
||||
复制后在 cmd_run 中实现真正的业务逻辑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -6,39 +10,47 @@ import json
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
from db import publish_logs_repository as plr
|
||||
from db import task_logs_repository as tlr
|
||||
from service.entitlement_service import check_entitlement
|
||||
from util.constants import SKILL_SLUG, SKILL_VERSION
|
||||
from util.timeutil import unix_to_iso
|
||||
|
||||
|
||||
def cmd_publish(account_id: Optional[str] = None, article_id: Optional[str] = None) -> int:
|
||||
_ = (account_id, article_id)
|
||||
def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int:
|
||||
"""通用任务执行入口模板。复制后请实现真实业务逻辑。"""
|
||||
_ = (target, input_id)
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
print(f"❌ {reason}")
|
||||
return 1
|
||||
print("❌ 这是模板仓库,请复制后在 scripts/service/ 中实现真正的发布逻辑。")
|
||||
print("❌ 这是模板仓库,请复制后在 scripts/service/task_service.py 中实现 cmd_run 的真实业务逻辑。")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_logs(limit: int = 10, status: Optional[str] = None, account_id: Optional[str] = None) -> int:
|
||||
def cmd_logs(
|
||||
limit: int = 10,
|
||||
status: Optional[str] = None,
|
||||
task_type: Optional[str] = None,
|
||||
target_id: Optional[str] = None,
|
||||
) -> int:
|
||||
if limit <= 0:
|
||||
limit = 10
|
||||
rows = plr.list_publish_logs(limit, status, account_id)
|
||||
rows = tlr.list_task_logs(limit, status, task_type, target_id)
|
||||
if not rows:
|
||||
print("暂无发布记录")
|
||||
print("暂无任务日志")
|
||||
return 0
|
||||
|
||||
sep_line = "_" * 39
|
||||
for idx, r in enumerate(rows):
|
||||
rid, aid, arid, title, st, err, cat, uat = r
|
||||
rid, ttype, tid, iid, ititle, st, err, rsum, cat, uat = r
|
||||
print(f"id:{rid}")
|
||||
print(f"account_id:{aid or ''}")
|
||||
print(f"article_id:{arid}")
|
||||
print(f"article_title:{title or ''}")
|
||||
print(f"task_type:{ttype or ''}")
|
||||
print(f"target_id:{tid or ''}")
|
||||
print(f"input_id:{iid or ''}")
|
||||
print(f"input_title:{ititle or ''}")
|
||||
print(f"status:{st or ''}")
|
||||
print(f"error_msg:{err or ''}")
|
||||
print(f"result_summary:{rsum or ''}")
|
||||
print(f"created_at:{unix_to_iso(cat) or str(cat or '')}")
|
||||
print(f"updated_at:{unix_to_iso(uat) or str(uat or '')}")
|
||||
if idx != len(rows) - 1:
|
||||
@@ -51,20 +63,22 @@ def cmd_log_get(log_id: str) -> int:
|
||||
if not str(log_id).isdigit():
|
||||
print("❌ log_id 必须是数字")
|
||||
return 1
|
||||
row = plr.get_publish_log_by_id(int(log_id))
|
||||
row = tlr.get_task_log_by_id(int(log_id))
|
||||
if not row:
|
||||
print("❌ 没有这条发布记录")
|
||||
print("❌ 没有这条任务日志")
|
||||
return 1
|
||||
rid, aid, arid, title, st, err, cat, uat = row
|
||||
rid, ttype, tid, iid, ititle, st, err, rsum, cat, uat = row
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"id": int(rid),
|
||||
"account_id": aid,
|
||||
"article_id": int(arid),
|
||||
"article_title": title,
|
||||
"task_type": ttype,
|
||||
"target_id": tid,
|
||||
"input_id": iid,
|
||||
"input_title": ititle,
|
||||
"status": st,
|
||||
"error_msg": err,
|
||||
"result_summary": rsum,
|
||||
"created_at": unix_to_iso(cat),
|
||||
"updated_at": unix_to_iso(uat),
|
||||
},
|
||||
@@ -1,5 +1,5 @@
|
||||
"""技能标识与版本(复制后请修改)。"""
|
||||
|
||||
SKILL_SLUG = "your-skill-slug"
|
||||
SKILL_VERSION = "1.0.0"
|
||||
SKILL_VERSION = "1.0.14"
|
||||
LOG_LOGGER_NAME = "openclaw.skill.your_skill_slug"
|
||||
|
||||
10
tests/.gitignore
vendored
Normal file
10
tests/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
# 测试运行产物与本地密钥,勿提交
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
desktop/artifacts/
|
||||
integration/artifacts/
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
!.env.sample
|
||||
173
tests/README.md
173
tests/README.md
@@ -1,8 +1,171 @@
|
||||
# tests
|
||||
# skill-template 测试说明(企业数字员工技能)
|
||||
|
||||
这里放模板复制后的单元测试或最小回归测试。
|
||||
本目录提供面向 **ERP / TMS / WMS / 船司 / 报关 / 邮件 / 浏览器 / LLM / RPA** 等外联场景的**分层测试骨架**:默认仅内存与本地 SQLite;**真实 API / 真实 RPA** 必须通过环境变量显式授权,且仅以 ``*.sample`` 或复制后的文件提供范式。
|
||||
|
||||
模板仓库本身不强制附带业务测试,但建议新 skill 至少补:
|
||||
复制为新技能后,请保留隔离数据根与 profile 策略,再按域扩展用例。
|
||||
|
||||
- `health` / `version` 最小冒烟测试
|
||||
- 关键 `service` 层函数的单元测试
|
||||
---
|
||||
|
||||
## 我该把测试写在哪里?
|
||||
|
||||
人类开发者与 Cursor 等 AI 工具在加用例前,先对照下表决定**文件落点**与**是否默认执行**:
|
||||
|
||||
| 场景 | 放在哪里 | 默认是否运行 | 说明 |
|
||||
|------|----------|--------------|------|
|
||||
| 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 注入外部依赖 |
|
||||
| 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`(或兼容键名 `OPENCLOW_TEST_TARGET`)后按需运行 |
|
||||
| 仿真 RPA / 页面操作 | `tests/integration/test_simulator_rpa_contract.py.sample` | 否 | 用 localhost / 仿真页面,不碰真实系统 |
|
||||
| 真实 API | `tests/integration/test_real_api_contract.py.sample` | 否 | 必须 `OPENCLAW_TEST_TARGET=real_api` 且 `ALLOW_REAL_API=1` |
|
||||
| 真实 RPA | `tests/integration/test_real_rpa_contract.py.sample` | 否 | 最高风险,只能手动触发 |
|
||||
| 桌面宿主 E2E | `tests/desktop/test_desktop_smoke.py.sample` | 否 | 需要 pytest + `jiangchang_desktop_sdk` |
|
||||
|
||||
说明:`python tests/run_tests.py` **只**收集 `tests/` **根目录**下的 `test_*.py`;子目录里的 `*.sample` 与 desktop 用例**不会**被默认发现。
|
||||
|
||||
---
|
||||
|
||||
## 新技能最小测试清单
|
||||
|
||||
从本模板复制出新技能仓库后,建议至少逐项确认:
|
||||
|
||||
- [ ] `python tests/run_tests.py -v` 能通过。
|
||||
- [ ] `python scripts/main.py health` 能通过。
|
||||
- [ ] `python scripts/main.py version` 输出 JSON,且 `skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。
|
||||
- [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。
|
||||
- [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API,不打开真实 RPA。
|
||||
- [ ] 至少有 1 个成功路径测试。
|
||||
- [ ] 至少有 1 个缺必填字段 / 非法输入测试。
|
||||
- [ ] 如果有 adapter,至少覆盖 timeout / unauthorized / invalid response(可用 fake 模拟)。
|
||||
- [ ] 如果有解析 / 计算 / 校验类业务,至少保留 1 组 golden fixture(脱敏)。
|
||||
- [ ] 真实 API / 真实 RPA 测试只放 `tests/integration/`,并且默认 `.sample`,不默认运行。
|
||||
|
||||
---
|
||||
|
||||
## 1. 默认必跑(unittest)
|
||||
|
||||
在**技能仓库根目录**执行:
|
||||
|
||||
```powershell
|
||||
$env:PYTHONDONTWRITEBYTECODE = "1"
|
||||
python tests/run_tests.py
|
||||
python tests/run_tests.py -v
|
||||
python tests/run_tests.py cli_smoke
|
||||
python tests/run_tests.py test_cli_smoke
|
||||
```
|
||||
|
||||
### 1.1 收集范围
|
||||
|
||||
- ``run_tests.py`` **只**发现 ``tests/`` **根目录**下 ``test_*.py``。
|
||||
- **不递归**:``tests/samples/``、``tests/integration/``、``tests/desktop/``(其中文件为 ``*.sample`` 或需 pytest 单独跑)。
|
||||
- 启动时把 ``scripts/`` 与 ``tests/`` 加入 ``sys.path``。
|
||||
- Windows 下将 **stdout/stderr** 包装为 **UTF-8**。
|
||||
|
||||
### 1.2 默认套件覆盖
|
||||
|
||||
| 能力 | 文件 |
|
||||
|------|------|
|
||||
| CLI 冒烟(import ``cli.app.main``) | ``test_cli_smoke.py`` |
|
||||
| **subprocess 真实入口** ``python scripts/main.py`` | ``test_entrypoint_subprocess.py`` |
|
||||
| 运行路径与 **CLAW_*/JIANGCHANG_*** 隔离 | ``test_runtime_paths.py`` |
|
||||
| ``SKILL.md`` slug 与 ``constants.SKILL_SLUG`` | ``test_skill_metadata.py`` |
|
||||
| DB / ``publish_logs`` 骨架冒烟 | ``test_db_smoke.py`` |
|
||||
| **adapter profile / 外呼授权策略** | ``test_adapter_profile_policy.py`` + ``adapter_test_utils.py``(非 ``test_`` 前缀,不自动当用例收集) |
|
||||
|
||||
### 1.3 数据隔离(``_support.IsolatedDataRoot``)
|
||||
|
||||
同时设置(进入同一临时目录 / 用户):
|
||||
|
||||
| ``CLAW_DATA_ROOT`` | ``JIANGCHANG_DATA_ROOT`` |
|
||||
|--------------------|---------------------------|
|
||||
| 同一 ``tempfile.mkdtemp(prefix="skill-test-")`` | 同上 |
|
||||
|
||||
| ``CLAW_USER_ID`` | ``JIANGCHANG_USER_ID`` |
|
||||
|------------------|-------------------------|
|
||||
| ``_test`` | ``_test`` |
|
||||
|
||||
退出时四个键均恢复(原不存在则 ``pop``),并删除临时目录。
|
||||
|
||||
### 1.4 产物与密钥
|
||||
|
||||
- ``tests/.gitignore`` 忽略 ``__pycache__``、``.pytest_cache``、``*.pyc``、``desktop/artifacts/``、``integration/artifacts/``、``.env`` 等。
|
||||
- 推荐运行前设置 ``PYTHONDONTWRITEBYTECODE=1`` 减少 ``.pyc``。
|
||||
|
||||
---
|
||||
|
||||
## 2. 可选:Service / Golden(``tests/samples/*.sample``)
|
||||
|
||||
- 展示 **service 契约** 与 **fixture 回归** 写法;**默认不执行**。
|
||||
- 启用:复制 ``tests/samples/test_service_contract.py.sample`` 等为 ``tests/test_*.py``(去掉 ``.sample``),按业务修改后再 ``python tests/run_tests.py``。
|
||||
- 脱敏样例数据见 ``tests/fixtures/README.md`` 与 ``sample_request.json`` / ``expected_response.json``;profile 结构见 ``adapter_profiles.sample.yaml``。
|
||||
|
||||
---
|
||||
|
||||
## 3. 可选:Integration(``tests/integration/*.sample``)
|
||||
|
||||
- **默认不跑**;文件均为 ``*.py.sample``。
|
||||
- 说明与开关见 **`tests/integration/README.md`**。
|
||||
- **禁止**在样例中硬编码真实 token、密码、生产 URL;凭证须来自密钥库或受控环境变量。
|
||||
|
||||
---
|
||||
|
||||
## 4. 可选:Desktop E2E(pytest)
|
||||
|
||||
见 **`tests/desktop/README.md`**。示例为 `test_desktop_smoke.py.sample`,需复制为 `test_desktop_smoke.py` 后用 pytest 运行。
|
||||
|
||||
---
|
||||
|
||||
## 5. 环境变量:测试档位与授权
|
||||
|
||||
### 5.1 测试档位(二选一变量名,后者为历史拼写兼容)
|
||||
|
||||
- ``OPENCLAW_TEST_TARGET`` 或 ``OPENCLOW_TEST_TARGET``
|
||||
|
||||
**合法取值**(非法值将使 ``get_test_target()`` 抛 ``ValueError``):
|
||||
|
||||
| 取值 | 含义 |
|
||||
|------|------|
|
||||
| ``unit`` | **默认**:单元 / 内存 / mock,不跑仿真与真实外联 |
|
||||
| ``mock`` | 与 ``unit`` 类似的安全档位(显式语义) |
|
||||
| ``simulator_api`` | 仅允许 **仿真 HTTP** 类集成(如 localhost) |
|
||||
| ``simulator_rpa`` | 仅允许 **仿真页面 / 录播 RPA** |
|
||||
| ``real_api`` | 真实 API(另需 ``ALLOW_REAL_API=1``) |
|
||||
| ``real_rpa`` | 真实 RPA(另需 ``ALLOW_REAL_RPA=1``) |
|
||||
|
||||
未设置时等价 ``unit``。
|
||||
|
||||
### 5.2 授权开关(显式 ``1``)
|
||||
|
||||
| 变量 | 作用 |
|
||||
|------|------|
|
||||
| ``ALLOW_REAL_API=1`` | 允许 ``real_api`` profile 访问真实 HTTP 通道 |
|
||||
| ``ALLOW_REAL_RPA=1`` | 允许 ``real_rpa`` profile 驱动真实浏览器/RPA |
|
||||
| ``ALLOW_WRITE_ACTIONS=1`` | 在 ``real_*`` 下允许**写**操作(提交表单、下单等) |
|
||||
|
||||
### 5.3 默认安全策略(``adapter_test_utils``)
|
||||
|
||||
- 默认 ``unit``:不访问真实 API、不跑真实 RPA、不做写操作、不读取真实密钥、不写真实数据根。
|
||||
- ``assert_no_real_network_env()`` 断言默认未误开 ``ALLOW_REAL_*``(用于必跑用例自检)。
|
||||
|
||||
---
|
||||
|
||||
## AI 编程工具注意事项(Cursor 等)
|
||||
|
||||
以下约束适用于为本仓库或复制出的技能编写/修改测试时,**避免误伤业务与生产**:
|
||||
|
||||
- **不要为了**让测试通过去改业务代码,除非用户明确要求修改实现。
|
||||
- **不要**把真实外部系统调用写进默认的 `tests/test_*.py`(默认套件须无外联、无真实浏览器)。
|
||||
- **不要**把 `*.sample` 改名为可执行测试或移入根目录并去掉 `.sample`,除非用户明确要求启用 integration / 真实联调。
|
||||
- **不要**硬编码真实凭证、token、cookie、生产 URL;占位请用明显虚构域名(如 `example.invalid`)或文档约定的 `credential_ref`。
|
||||
- 默认测试只能使用 **mock、stub、`FakeAdapter`、fixtures、隔离 SQLite** 等安全手段。
|
||||
- 业务逻辑应优先在 **service 层** 编写与测试,不要只断言 CLI 文案。
|
||||
- 异常路径应返回**结构化错误**(如统一错误码/字段),避免裸异常直接穿透到 CLI。
|
||||
- 有真实系统联调需求时,测试应写在 `tests/integration/`,并配合 `OPENCLAW_TEST_TARGET` / `ALLOW_REAL_*` / `ALLOW_WRITE_ACTIONS` 等**显式开关**;不得默认开启。
|
||||
|
||||
---
|
||||
|
||||
## 6. 与 content-manager 的关系
|
||||
|
||||
- **未**复制 article / media / prompt / NotebookLM 等业务测试。
|
||||
- 本骨架面向**通用外联技能**;业务契约请放在各自技能的 ``tests/samples`` / ``tests/integration`` 复制件中实现。
|
||||
|
||||
77
tests/_support.py
Normal file
77
tests/_support.py
Normal file
@@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试公共支撑。
|
||||
|
||||
1. 将 scripts/ 加入 sys.path,便于 `from cli…` / `from db…` / `from util…` 等导入。
|
||||
2. `IsolatedDataRoot`:同时设置 CLAW_* 与 JIANGCHANG_* 数据根与用户 ID,
|
||||
与 `jiangchang_skill_core.runtime_env` 的优先级一致(CLAW_* 优先),
|
||||
避免只设 JIANGCHANG_* 时仍读到真实 CLAW_DATA_ROOT。
|
||||
退出时四个变量均恢复;原不存在的键会删除;并 rmtree 临时目录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from typing import Optional
|
||||
|
||||
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_SKILL_ROOT = os.path.abspath(os.path.join(_TESTS_DIR, ".."))
|
||||
_SCRIPTS_DIR = os.path.join(_SKILL_ROOT, "scripts")
|
||||
|
||||
if _SCRIPTS_DIR not in sys.path:
|
||||
sys.path.insert(0, _SCRIPTS_DIR)
|
||||
|
||||
_ISOLATION_KEYS = (
|
||||
"CLAW_DATA_ROOT",
|
||||
"JIANGCHANG_DATA_ROOT",
|
||||
"CLAW_USER_ID",
|
||||
"JIANGCHANG_USER_ID",
|
||||
)
|
||||
|
||||
|
||||
def get_scripts_dir() -> str:
|
||||
return _SCRIPTS_DIR
|
||||
|
||||
|
||||
def get_skill_root() -> str:
|
||||
return _SKILL_ROOT
|
||||
|
||||
|
||||
class IsolatedDataRoot:
|
||||
"""
|
||||
在独立临时目录下模拟数据根,避免污染本机默认数据目录。
|
||||
|
||||
进入上下文时(同一套隔离值写入 CLAW_* 与 JIANGCHANG_*):
|
||||
- CLAW_DATA_ROOT / JIANGCHANG_DATA_ROOT -> 同一 tempfile.mkdtemp(prefix='skill-test-')
|
||||
- CLAW_USER_ID / JIANGCHANG_USER_ID -> _test(与业务默认用户区分)
|
||||
|
||||
退出时:四个变量均恢复为进入前状态(若原先未设置则 pop),并删除临时目录。
|
||||
"""
|
||||
|
||||
def __init__(self, user_id: str = "_test") -> None:
|
||||
self._tmp: Optional[str] = None
|
||||
self._old: dict[str, Optional[str]] = {}
|
||||
self._user_id = user_id
|
||||
|
||||
def __enter__(self) -> str:
|
||||
self._tmp = tempfile.mkdtemp(prefix="skill-test-")
|
||||
for k in _ISOLATION_KEYS:
|
||||
self._old[k] = os.environ.get(k)
|
||||
os.environ["CLAW_DATA_ROOT"] = self._tmp
|
||||
os.environ["JIANGCHANG_DATA_ROOT"] = self._tmp
|
||||
os.environ["CLAW_USER_ID"] = self._user_id
|
||||
os.environ["JIANGCHANG_USER_ID"] = self._user_id
|
||||
return self._tmp
|
||||
|
||||
def __exit__(self, *exc_info: object) -> None:
|
||||
for k in _ISOLATION_KEYS:
|
||||
v = self._old.get(k)
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
if self._tmp and os.path.isdir(self._tmp):
|
||||
shutil.rmtree(self._tmp, ignore_errors=True)
|
||||
self._tmp = None
|
||||
142
tests/adapter_test_utils.py
Normal file
142
tests/adapter_test_utils.py
Normal file
@@ -0,0 +1,142 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
企业技能对接外部系统(ERP / TMS / WMS / 船司 / 报关 / 邮件 / 浏览器 / LLM / RPA)时,
|
||||
测试侧共用的 **profile / 授权 / 禁止真实外呼** 工具。
|
||||
|
||||
- 仅标准库;不发起 HTTP;不启动浏览器。
|
||||
- 真实 API / RPA 契约测试请放在 ``tests/integration/*.sample``,并配合环境变量显式授权。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Final
|
||||
|
||||
# 允许的 OPENCLAW_TEST_TARGET / OPENCLOW_TEST_TARGET 取值(后者为历史拼写兼容)
|
||||
ALLOWED_TEST_TARGETS: Final[frozenset[str]] = frozenset(
|
||||
{
|
||||
"unit",
|
||||
"mock",
|
||||
"simulator_api",
|
||||
"simulator_rpa",
|
||||
"real_api",
|
||||
"real_rpa",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _raw_test_target_env() -> str:
|
||||
return (os.environ.get("OPENCLAW_TEST_TARGET") or os.environ.get("OPENCLOW_TEST_TARGET") or "").strip()
|
||||
|
||||
|
||||
def get_test_target() -> str:
|
||||
"""
|
||||
读取 ``OPENCLAW_TEST_TARGET`` 或 ``OPENCLOW_TEST_TARGET``(兼容旧拼写)。
|
||||
|
||||
未设置时返回 ``unit``。非法取值抛出 ``ValueError``,便于尽早发现拼写错误。
|
||||
"""
|
||||
raw = _raw_test_target_env()
|
||||
if not raw:
|
||||
return "unit"
|
||||
if raw not in ALLOWED_TEST_TARGETS:
|
||||
raise ValueError(
|
||||
f"Invalid test target {raw!r}. Allowed: {sorted(ALLOWED_TEST_TARGETS)}"
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def real_access_allowed(profile: str) -> bool:
|
||||
"""
|
||||
判断当前环境是否允许对 ``profile`` 做「真实通道」访问(仍不代替业务鉴权)。
|
||||
|
||||
- ``real_api``:需要 ``ALLOW_REAL_API == "1"``。
|
||||
- ``real_rpa``:需要 ``ALLOW_REAL_RPA == "1"``。
|
||||
- 写操作另需 ``ALLOW_WRITE_ACTIONS == "1"``(由 ``should_skip_profile(..., write=True)`` 组合检查)。
|
||||
"""
|
||||
if profile == "real_api":
|
||||
return os.environ.get("ALLOW_REAL_API", "") == "1"
|
||||
if profile == "real_rpa":
|
||||
return os.environ.get("ALLOW_REAL_RPA", "") == "1"
|
||||
if profile in ("mock", "simulator_api", "simulator_rpa"):
|
||||
return True
|
||||
raise ValueError(f"unknown profile for real_access_allowed: {profile!r}")
|
||||
|
||||
|
||||
def should_skip_profile(profile: str, write: bool = False) -> tuple[bool, str]:
|
||||
"""
|
||||
返回 ``(should_skip, reason)``。
|
||||
|
||||
策略摘要:
|
||||
- ``mock``:永不跳过(内存 / FakeAdapter,无外呼)。
|
||||
- ``simulator_api``:仅当 ``get_test_target() == "simulator_api"`` 时不跳过。
|
||||
- ``simulator_rpa``:仅当 target 为 ``simulator_rpa`` 时不跳过。
|
||||
- ``real_api``:target 须为 ``real_api`` 且 ``ALLOW_REAL_API=1``;``write=True`` 还须 ``ALLOW_WRITE_ACTIONS=1``。
|
||||
- ``real_rpa``:target 须为 ``real_rpa`` 且 ``ALLOW_REAL_RPA=1``;``write=True`` 还须 ``ALLOW_WRITE_ACTIONS=1``。
|
||||
"""
|
||||
target = get_test_target()
|
||||
|
||||
if profile == "mock":
|
||||
return (False, "")
|
||||
|
||||
if profile == "simulator_api":
|
||||
if target != "simulator_api":
|
||||
return (True, f"OPENCLAW_TEST_TARGET must be simulator_api (got {target!r})")
|
||||
return (False, "")
|
||||
|
||||
if profile == "simulator_rpa":
|
||||
if target != "simulator_rpa":
|
||||
return (True, f"OPENCLAW_TEST_TARGET must be simulator_rpa (got {target!r})")
|
||||
return (False, "")
|
||||
|
||||
if profile == "real_api":
|
||||
if target != "real_api":
|
||||
return (True, f"OPENCLAW_TEST_TARGET must be real_api (got {target!r})")
|
||||
if os.environ.get("ALLOW_REAL_API", "") != "1":
|
||||
return (True, "ALLOW_REAL_API is not 1")
|
||||
if write and os.environ.get("ALLOW_WRITE_ACTIONS", "") != "1":
|
||||
return (True, "ALLOW_WRITE_ACTIONS is not 1 (write requested)")
|
||||
return (False, "")
|
||||
|
||||
if profile == "real_rpa":
|
||||
if target != "real_rpa":
|
||||
return (True, f"OPENCLAW_TEST_TARGET must be real_rpa (got {target!r})")
|
||||
if os.environ.get("ALLOW_REAL_RPA", "") != "1":
|
||||
return (True, "ALLOW_REAL_RPA is not 1")
|
||||
if write and os.environ.get("ALLOW_WRITE_ACTIONS", "") != "1":
|
||||
return (True, "ALLOW_WRITE_ACTIONS is not 1 (write requested)")
|
||||
return (False, "")
|
||||
|
||||
raise ValueError(f"unknown profile: {profile!r}")
|
||||
|
||||
|
||||
class FakeAdapter:
|
||||
"""
|
||||
模拟外部系统 adapter,用于单元测试中的超时 / 鉴权 / 畸形响应等分支。
|
||||
|
||||
``mode``:``success`` | ``timeout`` | ``invalid_response`` | ``unauthorized``
|
||||
"""
|
||||
|
||||
def __init__(self, mode: str = "success") -> None:
|
||||
if mode not in ("success", "timeout", "invalid_response", "unauthorized"):
|
||||
raise ValueError(f"unsupported FakeAdapter mode: {mode!r}")
|
||||
self._mode = mode
|
||||
|
||||
def call(self, payload: Any) -> Any:
|
||||
if self._mode == "success":
|
||||
return {"success": True, "data": {"echo": payload}}
|
||||
if self._mode == "timeout":
|
||||
raise TimeoutError("simulated upstream timeout")
|
||||
if self._mode == "invalid_response":
|
||||
return object() # 非 dict,模拟无法解析的响应体
|
||||
if self._mode == "unauthorized":
|
||||
raise PermissionError("simulated 401/403")
|
||||
raise RuntimeError("unreachable")
|
||||
|
||||
|
||||
def assert_no_real_network_env() -> None:
|
||||
"""
|
||||
断言当前进程未显式打开「真实外呼」授权开关(默认安全 CI / 本地开发)。
|
||||
|
||||
若需在受控环境跑真实集成,请显式设置 ``ALLOW_REAL_*`` 并使用 ``tests/integration/*.sample``。
|
||||
"""
|
||||
assert os.environ.get("ALLOW_REAL_API", "") != "1", "ALLOW_REAL_API must not be 1 in default unit tests"
|
||||
assert os.environ.get("ALLOW_REAL_RPA", "") != "1", "ALLOW_REAL_RPA must not be 1 in default unit tests"
|
||||
34
tests/desktop/README.md
Normal file
34
tests/desktop/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# 可选桌面 E2E(pytest)
|
||||
|
||||
本目录用于**匠厂桌面 + jiangchang_desktop_sdk** 的端到端冒烟,**不是** `python tests/run_tests.py` 默认路径的一部分。
|
||||
|
||||
## 依赖
|
||||
|
||||
- `pytest`
|
||||
- `jiangchang_desktop_sdk`(由 `conftest.py` 按多级路径尝试加入 `sys.path`,见该文件说明)
|
||||
- 匠厂桌面已安装或开发态可启动,且 `jiangchang://` 协议可用
|
||||
|
||||
## 为什么不默认跑
|
||||
|
||||
- 需要真实宿主环境,无法在纯 CI/无头环境稳定复现。
|
||||
- `unittest` 的 `tests/run_tests.py` **只发现** `tests/` 根目录下 `test_*.py`,**不递归**本目录。
|
||||
- 示例文件为 **`test_desktop_smoke.py.sample`**,避免被误收集。
|
||||
|
||||
## 如何启用
|
||||
|
||||
1. 将 `test_desktop_smoke.py.sample` **复制或重命名**为 `test_desktop_smoke.py`。
|
||||
2. 按你的技能名称、路由关键词、期望输出修改 `ask` 与断言。
|
||||
3. 运行:
|
||||
|
||||
```powershell
|
||||
pytest tests/desktop/test_desktop_smoke.py -v -s
|
||||
```
|
||||
|
||||
失败时,`conftest.py` 中的 `failure_snapshot_dir` fixture 会将现场目录指向 `tests/desktop/artifacts/`(需自行避免将大文件提交进仓库)。
|
||||
|
||||
## 与后端测试的关系
|
||||
|
||||
- **后端 / CLI / DB**:请使用仓库根目录下 `python tests/run_tests.py`(见 `tests/README.md`)。
|
||||
- **桌面 E2E**:仅在本目录用 **pytest** 维护,二者互补、互不替代。
|
||||
|
||||
若仅需验证 **service 业务逻辑**、契约与 golden 回归,**不要**写 desktop E2E;desktop 只用于验证**宿主 UI、路由、`jiangchang://` 协议、真实用户交互链路**等与桌面宿主强相关的行为。
|
||||
76
tests/desktop/conftest.py
Normal file
76
tests/desktop/conftest.py
Normal file
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
可选桌面 E2E:pytest 收集时自动加载,负责把 jiangchang_desktop_sdk 加入 sys.path。
|
||||
|
||||
查找顺序(与 content-manager 对齐思路,去掉业务仓专属路径假设):
|
||||
1. 已 pip install 则直接 import;
|
||||
2. 环境变量 JIANGCHANG_KIT_ROOT → sdk/jiangchang-desktop-sdk/src;
|
||||
3. 自本文件上溯:skill 根 → workspace 根 → OpenClaw 根,拼 jiangchang-platform-kit/sdk/.../src;
|
||||
4. 都找不到则 pytest.exit 给出可操作的排障说明。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _bootstrap_jiangchang_desktop_sdk() -> None:
|
||||
if importlib.util.find_spec("jiangchang_desktop_sdk") is not None:
|
||||
return
|
||||
|
||||
env_kit_root = (os.environ.get("JIANGCHANG_KIT_ROOT") or "").strip()
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
skill_root = os.path.abspath(os.path.join(here, "..", ".."))
|
||||
workspace_root = os.path.abspath(os.path.join(skill_root, ".."))
|
||||
open_claw_root = os.path.abspath(os.path.join(workspace_root, ".."))
|
||||
|
||||
candidates = []
|
||||
if env_kit_root:
|
||||
candidates.append(os.path.join(env_kit_root, "sdk", "jiangchang-desktop-sdk", "src"))
|
||||
candidates.append(
|
||||
os.path.join(workspace_root, "jiangchang-platform-kit", "sdk", "jiangchang-desktop-sdk", "src")
|
||||
)
|
||||
candidates.append(
|
||||
os.path.join(open_claw_root, "jiangchang-platform-kit", "sdk", "jiangchang-desktop-sdk", "src")
|
||||
)
|
||||
|
||||
tried = []
|
||||
for cand in candidates:
|
||||
cand_abs = os.path.abspath(cand)
|
||||
tried.append(cand_abs)
|
||||
if os.path.isdir(cand_abs) and os.path.isdir(os.path.join(cand_abs, "jiangchang_desktop_sdk")):
|
||||
if cand_abs not in sys.path:
|
||||
sys.path.insert(0, cand_abs)
|
||||
return
|
||||
|
||||
pytest.exit(
|
||||
"无法定位 jiangchang_desktop_sdk。请任选一种方式解决:\n"
|
||||
" 1) pip install -e <path-to>/jiangchang-platform-kit/sdk/jiangchang-desktop-sdk\n"
|
||||
" 2) 设置环境变量 JIANGCHANG_KIT_ROOT=<path-to>/jiangchang-platform-kit\n"
|
||||
" 3) 将 jiangchang-platform-kit 与本仓库放在同一 workspace 父级可推断的位置,例如:\n"
|
||||
f" {workspace_root}/jiangchang-platform-kit/ 或 {open_claw_root}/jiangchang-platform-kit/\n"
|
||||
"已尝试的候选路径:\n - " + "\n - ".join(tried),
|
||||
returncode=4,
|
||||
)
|
||||
|
||||
|
||||
_bootstrap_jiangchang_desktop_sdk()
|
||||
|
||||
_ARTIFACT_DIR = os.path.join(os.path.dirname(__file__), "artifacts")
|
||||
|
||||
|
||||
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
|
||||
def pytest_runtest_makereport(item, call):
|
||||
outcome = yield
|
||||
rep = outcome.get_result()
|
||||
setattr(item, f"rep_{rep.when}", rep)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def failure_snapshot_dir() -> str:
|
||||
os.makedirs(_ARTIFACT_DIR, exist_ok=True)
|
||||
return _ARTIFACT_DIR
|
||||
58
tests/desktop/test_desktop_smoke.py.sample
Normal file
58
tests/desktop/test_desktop_smoke.py.sample
Normal file
@@ -0,0 +1,58 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
可选桌面 E2E 示例(默认不执行:文件名后缀为 .sample)。
|
||||
|
||||
启用方式:
|
||||
复制本文件为 test_desktop_smoke.py,按目标技能修改提问文案与断言。
|
||||
运行:pytest tests/desktop/test_desktop_smoke.py -v -s
|
||||
|
||||
依赖:pytest、jiangchang_desktop_sdk、匠厂桌面宿主已就绪。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from jiangchang_desktop_sdk import AskOptions, JiangchangDesktopClient
|
||||
|
||||
_logger = logging.getLogger("skill-template-desktop-e2e-sample")
|
||||
if not _logger.handlers:
|
||||
_logger.setLevel(logging.INFO)
|
||||
_h = logging.StreamHandler()
|
||||
_h.setFormatter(logging.Formatter("[E2E-sample] %(message)s"))
|
||||
_logger.addHandler(_h)
|
||||
|
||||
_ARTIFACT_DIR = os.path.join(os.path.dirname(__file__), "artifacts")
|
||||
|
||||
|
||||
class TestDesktopSmokeSample:
|
||||
"""最小 smoke:拉起桌面、等待网关、发一条与技能路由相关的问句并做宽松断言。"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def connect_and_teardown(self, request):
|
||||
client = JiangchangDesktopClient()
|
||||
_logger.info("ensure_app_running")
|
||||
client.ensure_app_running(wait_timeout_s=30)
|
||||
client.bring_to_front()
|
||||
client.wait_gateway_ready(timeout_ms=30000)
|
||||
self.client = client
|
||||
yield
|
||||
try:
|
||||
rep = getattr(request.node, "rep_call", None)
|
||||
if rep is not None and rep.failed:
|
||||
os.makedirs(_ARTIFACT_DIR, exist_ok=True)
|
||||
paths = client.snapshot(_ARTIFACT_DIR, tag=request.node.name)
|
||||
_logger.error("snapshot: %s", paths)
|
||||
finally:
|
||||
client.disconnect()
|
||||
|
||||
def test_gateway_and_simple_ask(self) -> None:
|
||||
"""请将 SKILL 名与路由关键词改成你复制后的真实技能。"""
|
||||
answer = self.client.ask(
|
||||
"请使用当前已安装技能执行一次 health 检查并返回 OK 或等价结果。",
|
||||
AskOptions(timeout=120000, new_task=True),
|
||||
)
|
||||
assert answer
|
||||
assert "OK" in answer or "ok" in answer.lower() or "健康" in answer
|
||||
27
tests/fixtures/README.md
vendored
Normal file
27
tests/fixtures/README.md
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# fixtures(脱敏样例)
|
||||
|
||||
本目录存放 **golden case / contract test** 用的输入、期望输出与 **adapter profile 样例**。
|
||||
|
||||
## 规则
|
||||
|
||||
- 只能放**虚构、脱敏、可公开**的数据(演示租户、演示 request_id 等)。
|
||||
- **禁止**:真实客户名、真实订单/提单号、真实报关单、真实 token/cookie、真实内网 URL、生产环境凭证。
|
||||
- `adapter_profiles.sample.yaml` 中的 URL 须使用 `localhost`、`example.invalid` 等明显占位;`credential_ref` 仅表达「从密钥库引用」的约定,**不得**内嵌密钥。
|
||||
|
||||
## 与本仓库测试的对应关系
|
||||
|
||||
| 文件 | 用途 |
|
||||
|------|------|
|
||||
| `sample_request.json` | 通用请求体样例,供 ``tests/samples/test_golden_cases.py.sample`` 演示读取。 |
|
||||
| `expected_response.json` | 与上配套的期望摘要字段(业务复制后按域替换)。 |
|
||||
| `adapter_profiles.sample.yaml` | 五类运行方式(mock / simulator_api / simulator_rpa / real_api / real_rpa)的配置表达样例。 |
|
||||
|
||||
---
|
||||
|
||||
## 给 AI 工具的替换规则
|
||||
|
||||
- 可以按业务**重命名字段**、增减键名,但必须保持**虚构、脱敏**;不得把真实客户标识原样搬进仓库。
|
||||
- 可以**新增**更多 fixture 文件,例如 `case_valid_001.json`、`case_missing_required_001.json`,并在测试中通过相对路径读取。
|
||||
- **禁止**将真实企业数据、真实单证截图中的文字、真实报关要素未经处理直接复制进 `fixtures/`。
|
||||
- 若用例来自真实客户样本,须先**脱敏、泛化、替换编号与地名**,再作为模板数据提交。
|
||||
|
||||
40
tests/fixtures/adapter_profiles.sample.yaml
vendored
Normal file
40
tests/fixtures/adapter_profiles.sample.yaml
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
# 样例:五类 adapter 运行方式(复制到业务仓后按环境改名;勿提交真实凭证)
|
||||
runtime:
|
||||
profile: mock
|
||||
|
||||
adapters:
|
||||
demo_external_system:
|
||||
interface: demo
|
||||
profile: mock
|
||||
|
||||
mock:
|
||||
target: mock
|
||||
channel: none
|
||||
|
||||
simulator_api:
|
||||
target: simulator
|
||||
channel: api
|
||||
base_url: http://localhost:5180/api/demo
|
||||
timeout_seconds: 10
|
||||
|
||||
simulator_rpa:
|
||||
target: simulator
|
||||
channel: rpa
|
||||
entry_url: http://localhost:5180/select
|
||||
timeout_seconds: 30
|
||||
|
||||
real_api:
|
||||
target: real
|
||||
channel: api
|
||||
base_url: https://example.invalid/api
|
||||
credential_ref: vault://tenant/demo/external-system/api
|
||||
write_enabled: false
|
||||
timeout_seconds: 20
|
||||
|
||||
real_rpa:
|
||||
target: real
|
||||
channel: rpa
|
||||
entry_url: https://example.invalid/portal
|
||||
credential_ref: vault://tenant/demo/external-system/rpa
|
||||
write_enabled: false
|
||||
timeout_seconds: 60
|
||||
6
tests/fixtures/expected_response.json
vendored
Normal file
6
tests/fixtures/expected_response.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"status": "ok"
|
||||
}
|
||||
}
|
||||
11
tests/fixtures/sample_request.json
vendored
Normal file
11
tests/fixtures/sample_request.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"request_id": "req_test_001",
|
||||
"tenant_id": "tenant_demo",
|
||||
"actor": "tester",
|
||||
"parameters": {
|
||||
"input_text": "demo input",
|
||||
"options": {
|
||||
"dry_run": true
|
||||
}
|
||||
}
|
||||
}
|
||||
53
tests/integration/README.md
Normal file
53
tests/integration/README.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# integration(可选集成 / 真实外联)
|
||||
|
||||
本目录**默认不执行**:
|
||||
|
||||
- ``python tests/run_tests.py`` 只收集 ``tests/`` 根目录下 ``test_*.py``,**不会**进入本目录。
|
||||
- 本目录下文件一律为 ``*.py.sample``,pytest / unittest **默认也不会**按普通 ``test_*.py`` 收集。
|
||||
|
||||
## 与 samples 的区别
|
||||
|
||||
| 维度 | `tests/samples/` | `tests/integration/` |
|
||||
|------|------------------|------------------------|
|
||||
| 目的 | 默认可**升级**为根目录 `test_*.py` 的 **业务单元 / service 契约 / golden** 范式 | **外联联调**范式:网络、浏览器、仿真或真实系统 |
|
||||
| 默认执行 | `.sample` 不执行;复制到根目录并改名后才进入默认套件 | **永远不**作为默认 unittest 的一部分;复制后仍需显式环境变量与手动/CI 任务触发 |
|
||||
| 典型内容 | `FakeAdapter`、fixture、隔离 DB | `localhost` 仿真、真实 API(授权)、真实 RPA(最高风险) |
|
||||
|
||||
**原则**:只要会访问**网络**、**浏览器**、**真实或仿真外部系统**,应优先放在 `integration`(并保持 `.sample` 直至团队同意启用),而不是写进默认 `tests/test_*.py`。
|
||||
|
||||
## 何时使用
|
||||
|
||||
| 场景 | 建议 ``OPENCLAW_TEST_TARGET`` | 其它条件 |
|
||||
|------|------------------------------|----------|
|
||||
| 本地 / CI 对接**仿真 HTTP** | ``simulator_api`` | 仿真服务如 ``http://localhost:5180`` |
|
||||
| **仿真页面** / 录播 RPA | ``simulator_rpa`` | 本地页面或沙箱浏览器 profile |
|
||||
| **真实 API**(只读优先) | ``real_api`` | ``ALLOW_REAL_API=1``;写操作另需 ``ALLOW_WRITE_ACTIONS=1`` |
|
||||
| **真实 RPA**(最高风险) | ``real_rpa`` | ``ALLOW_REAL_RPA=1``;**仅手动触发** |
|
||||
|
||||
## 环境变量(与 ``adapter_test_utils`` 一致)
|
||||
|
||||
- **目标档位**(二选一键名,后者为历史拼写):``OPENCLAW_TEST_TARGET`` 或 ``OPENCLOW_TEST_TARGET``
|
||||
取值:``unit`` | ``mock`` | ``simulator_api`` | ``simulator_rpa`` | ``real_api`` | ``real_rpa``
|
||||
默认未设置等价于 ``unit``。
|
||||
|
||||
- **授权开关**(显式 ``1`` 才启用):
|
||||
- ``ALLOW_REAL_API=1``
|
||||
- ``ALLOW_REAL_RPA=1``
|
||||
- ``ALLOW_WRITE_ACTIONS=1``(对写操作 / 提交表单类步骤)
|
||||
|
||||
## 安全约束
|
||||
|
||||
- **禁止**在样例或复制后的测试代码中硬编码真实账号、密码、token、cookie、生产 URL。
|
||||
- 凭证应来自**平台密钥库**、受控环境变量或本机安全配置(``.env`` 已列入 ``tests/.gitignore``,勿提交)。
|
||||
- 真实 RPA 可能对 ERP/TMS/WMS 等产生真实操作;**务必**沙箱账号、只读权限,并由人工触发 CI job。
|
||||
|
||||
## 如何运行某个样例
|
||||
|
||||
1. 将目标 ``*.sample`` 复制为 ``test_*.py``(去掉 ``.sample``)。
|
||||
2. 按技能修改其中的占位 URL / 路由 / 断言。
|
||||
3. 使用 **pytest** 指向该文件(或整目录),并导出上表所需环境变量。
|
||||
|
||||
```powershell
|
||||
$env:OPENCLAW_TEST_TARGET = "simulator_api"
|
||||
pytest tests/integration/test_simulator_api_contract.py -v
|
||||
```
|
||||
24
tests/integration/test_real_api_contract.py.sample
Normal file
24
tests/integration/test_real_api_contract.py.sample
Normal file
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制为 test_real_api_contract.py;需 OPENCLAW_TEST_TARGET=real_api 且 ALLOW_REAL_API=1。
|
||||
"""真实 HTTP API(只读优先;默认跳过)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import should_skip_profile
|
||||
|
||||
|
||||
class TestRealApiContractSample(unittest.TestCase):
|
||||
def test_skip_by_default(self) -> None:
|
||||
skip, reason = should_skip_profile("real_api", write=False)
|
||||
if skip:
|
||||
raise unittest.SkipTest(reason)
|
||||
# 写操作示例(复制后使用):
|
||||
# skip_w, _ = should_skip_profile("real_api", write=True)
|
||||
# 需要 ALLOW_WRITE_ACTIONS=1
|
||||
# 禁止在此文件写入真实 token;从 vault / 环境注入读取 endpoint。
|
||||
self.assertFalse(skip)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
26
tests/integration/test_real_rpa_contract.py.sample
Normal file
26
tests/integration/test_real_rpa_contract.py.sample
Normal file
@@ -0,0 +1,26 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制为 test_real_rpa_contract.py;需 OPENCLAW_TEST_TARGET=real_rpa 且 ALLOW_REAL_RPA=1。
|
||||
"""
|
||||
真实 RPA / 桌面自动化(**最高风险**,仅手动触发)。
|
||||
|
||||
默认只读思路示例:打开沙箱门户、读取标题、**不提交表单**。
|
||||
任何写操作必须 ``should_skip_profile('real_rpa', write=True)`` 且 ``ALLOW_WRITE_ACTIONS=1``。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import should_skip_profile
|
||||
|
||||
|
||||
class TestRealRpaContractSample(unittest.TestCase):
|
||||
def test_skip_by_default(self) -> None:
|
||||
skip, reason = should_skip_profile("real_rpa", write=False)
|
||||
if skip:
|
||||
raise unittest.SkipTest(reason)
|
||||
# 真实技能中:连接企业沙箱门户,执行只读断言;禁止默认操作生产系统。
|
||||
self.assertFalse(skip)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
24
tests/integration/test_simulator_api_contract.py.sample
Normal file
24
tests/integration/test_simulator_api_contract.py.sample
Normal file
@@ -0,0 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制为 test_simulator_api_contract.py 后,在 OPENCLAW_TEST_TARGET=simulator_api 下用 pytest 或 unittest 运行。
|
||||
"""仿真 HTTP API 契约(默认跳过;不引入 requests 运行时依赖)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import should_skip_profile
|
||||
|
||||
|
||||
class TestSimulatorApiContractSample(unittest.TestCase):
|
||||
"""演示:仅当 ``OPENCLAW_TEST_TARGET=simulator_api`` 时不跳过。"""
|
||||
|
||||
def test_skip_unless_simulator_api_target(self) -> None:
|
||||
skip, reason = should_skip_profile("simulator_api")
|
||||
if skip:
|
||||
raise unittest.SkipTest(reason)
|
||||
# 真实技能中:在此使用 urllib 访问 localhost 仿真,或通过 adapter factory 注入 stub。
|
||||
# 禁止默认连接生产 ERP/TMS。
|
||||
self.assertTrue(True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
21
tests/integration/test_simulator_rpa_contract.py.sample
Normal file
21
tests/integration/test_simulator_rpa_contract.py.sample
Normal file
@@ -0,0 +1,21 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制为 test_simulator_rpa_contract.py 后按需运行;默认跳过。
|
||||
"""仿真页面 / RPA 契约(不默认启动浏览器)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import should_skip_profile
|
||||
|
||||
|
||||
class TestSimulatorRpaContractSample(unittest.TestCase):
|
||||
def test_skip_unless_simulator_rpa_target(self) -> None:
|
||||
skip, reason = should_skip_profile("simulator_rpa")
|
||||
if skip:
|
||||
raise unittest.SkipTest(reason)
|
||||
# 真实技能中:可替换为 Playwright 连接 http://localhost:5180/select 等仿真入口。
|
||||
self.assertFalse(skip)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
62
tests/run_tests.py
Normal file
62
tests/run_tests.py
Normal file
@@ -0,0 +1,62 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""后端 / CLI / DB 单元测试入口(unittest,不强制 pytest)。
|
||||
|
||||
用法:
|
||||
python tests/run_tests.py # 发现 tests/ 根目录下全部 test_*.py
|
||||
python tests/run_tests.py -v # 详细输出
|
||||
python tests/run_tests.py cli_smoke # 仅匹配 test_cli_smoke.py
|
||||
python tests/run_tests.py test_cli_smoke
|
||||
|
||||
说明:
|
||||
只发现本目录(tests/)下一层的 test_*.py;不递归 ``samples/``、``integration/``、
|
||||
``desktop/``(后三者提供 ``*.sample`` 或 pytest 专用用例,见 ``tests/README.md``)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_SKILL_ROOT = os.path.abspath(os.path.join(_TESTS_DIR, ".."))
|
||||
_SCRIPTS_DIR = os.path.abspath(os.path.join(_SKILL_ROOT, "scripts"))
|
||||
|
||||
for _p in (_SCRIPTS_DIR, _TESTS_DIR):
|
||||
if _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
|
||||
# Windows 下统一 stdout/stderr 为 UTF-8,避免 GBK 控制台中文/emoji 报错
|
||||
if sys.platform == "win32":
|
||||
import io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def _pattern_from_argv(argv: list[str]) -> str:
|
||||
for a in argv[1:]:
|
||||
if a.startswith("-"):
|
||||
continue
|
||||
s = a if a.startswith("test_") else f"test_{a}"
|
||||
if not s.endswith(".py"):
|
||||
s = f"{s}.py"
|
||||
return s
|
||||
return "test_*.py"
|
||||
|
||||
|
||||
def _verbosity_from_argv(argv: list[str]) -> int:
|
||||
return 2 if ("-v" in argv or "--verbose" in argv) else 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
pattern = _pattern_from_argv(sys.argv)
|
||||
verbosity = _verbosity_from_argv(sys.argv)
|
||||
loader = unittest.TestLoader()
|
||||
suite = loader.discover(_TESTS_DIR, pattern=pattern)
|
||||
runner = unittest.TextTestRunner(verbosity=verbosity)
|
||||
result = runner.run(suite)
|
||||
return 0 if result.wasSuccessful() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
112
tests/samples/README.md
Normal file
112
tests/samples/README.md
Normal file
@@ -0,0 +1,112 @@
|
||||
# samples(业务测试样例,默认不执行)
|
||||
|
||||
本目录存放**可复制到根目录的业务测试范式**,面向「企业数字员工技能」中 **ERP、TMS、WMS、船司、报关、邮件、LLM、RPA** 等外联场景下的 **service / golden** 测法说明。
|
||||
|
||||
---
|
||||
|
||||
## 作用
|
||||
|
||||
- 这里的文件是 **`.py.sample`**:`python tests/run_tests.py` **不会**收集本目录(`run_tests.py` 只发现 `tests/` 根目录下的 `test_*.py`)。
|
||||
- 人类或 AI 需要启用范式时:**复制**到 `tests/test_<名称>.py`(去掉 `.sample`),再按业务改 import、断言与 fixture 路径。
|
||||
- **禁止**把真实联调、真实网络、真实 RPA 写进复制后的默认用例;此类内容应放在 `tests/integration/*.sample` 并配合环境变量开关。
|
||||
|
||||
---
|
||||
|
||||
## 两类样例文件
|
||||
|
||||
### 1. `test_service_contract.py.sample`
|
||||
|
||||
**适合:**
|
||||
|
||||
- 技能有清晰的 **service 层入口**,例如 `run(...)`、`handle(...)`、`execute(...)`。
|
||||
- 需要验证:**成功路径**、**参数/校验错误**、**adapter 异常被转换为业务可读错误**。
|
||||
- 需要用 **`FakeAdapter`**(见 `tests/adapter_test_utils.py`)或自建 **stub** 替代 ERP、TMS、WMS、船司、报关、LLM、RPA 等,**不**发真实 HTTP、**不**开真实浏览器。
|
||||
|
||||
### 2. `test_golden_cases.py.sample`
|
||||
|
||||
**适合:**
|
||||
|
||||
- **解析类**:邮件/单证/PDF/Excel 等结构化输出。
|
||||
- **计算类**:费用、税费、分摊、账单字段。
|
||||
- **校验类**:合规、字段一致性、状态机规则。
|
||||
|
||||
推荐配合根目录下的 **`tests/fixtures/sample_request.json`** 与 **`tests/fixtures/expected_response.json`**(复制技能后按域替换字段,保持脱敏)。
|
||||
|
||||
---
|
||||
|
||||
## 如何启用 service contract 样例
|
||||
|
||||
1. **复制文件**
|
||||
`tests/samples/test_service_contract.py.sample`
|
||||
→ `tests/test_service_contract.py`(或 `tests/test_<domain>_service_contract.py`,须符合根目录 `test_*.py` 命名以便 `run_tests.py` 收集)。
|
||||
|
||||
2. **替换示例 import**
|
||||
把注释中的示意:
|
||||
`# from service.your_service import run`
|
||||
改为真实模块,例如:
|
||||
`from service.quote_service import run_quote`
|
||||
(具体路径以技能代码为准。)
|
||||
|
||||
3. **注入假外部依赖**
|
||||
- **不要**在默认用例里直接 `requests` 访问 ERP/TMS/WMS 等。
|
||||
- **不要**打开真实网页或驱动真实 RPA。
|
||||
- **不要**调用真实 LLM;可 stub 返回固定 JSON。
|
||||
- 对 **timeout / unauthorized / invalid_response** 等分支,用 `FakeAdapter` 或自建 fake 模拟(与 `adapter_test_utils` 思路一致)。
|
||||
|
||||
4. **至少保留三类断言习惯**
|
||||
- **成功路径**:返回 `success: true` 或与技能约定的成功结构。
|
||||
- **参数错误**:缺必填字段时返回**结构化** error(字段/码),而非未捕获裸异常。
|
||||
- **外部异常**:adapter 超时、鉴权失败、脏响应等被转换为**可读、可重试标识明确**的错误形态(按产品约定)。
|
||||
|
||||
5. **给 AI 的提示**
|
||||
复制后全文搜索 `your_service`、`TODO`、`伪代码` 等占位符并替换;不要留下指向真实客户的示例数据。
|
||||
|
||||
---
|
||||
|
||||
## 如何启用 golden case 样例
|
||||
|
||||
1. **复制文件**
|
||||
`tests/samples/test_golden_cases.py.sample`
|
||||
→ `tests/test_golden_cases.py`(或 `tests/test_<domain>_golden.py`)。
|
||||
|
||||
2. **按业务修改 fixtures**(仍须脱敏)
|
||||
- `tests/fixtures/sample_request.json`:请求或输入快照。
|
||||
- `tests/fixtures/expected_response.json`:期望摘要或关键字段。
|
||||
可新增多组文件,如 `case_valid_001.json`,并在测试中显式读取路径。
|
||||
|
||||
3. **断言建议(避免脆弱用例)**
|
||||
- 比较**关键字段**,避免对整段 JSON 做机械全文 diff。
|
||||
- **忽略**时间戳、随机 id、`trace_id` 等非确定字段。
|
||||
- 对列表:断言**长度**、**关键元素**、**排序规则**(若业务保证顺序)。
|
||||
- 对金额/数量:断言 Decimal 字符串、或允许文档约定的小范围误差。
|
||||
|
||||
4. **与 service 的关系**
|
||||
golden 用例仍应通过 **service 层**(或纯函数)得到输出,再与 fixture 对比,而不是从 CLI 字符串 scrape。
|
||||
|
||||
---
|
||||
|
||||
## 不应该写在 samples 复制件里的内容
|
||||
|
||||
以下若出现,应移到 **`tests/integration/*.sample`** 或 **`tests/desktop/*.sample`**,并加环境变量授权说明:
|
||||
|
||||
- 访问**真实** API 或内网服务。
|
||||
- 打开**真实** RPA 页面或生产门户。
|
||||
- 读取**真实**客户文件、生产数据库。
|
||||
- 在测试中写入**真实**数据根或共享盘。
|
||||
- 任何真实 **token / cookie / 密码** 字面量。
|
||||
- 耗时极长、强依赖宿主 UI 抖动、无法在 CI 稳定复现的用例(不要塞进默认 `tests/test_*.py`)。
|
||||
|
||||
---
|
||||
|
||||
## 推荐命名(复制到根目录后)
|
||||
|
||||
| 用途 | 示例文件名 |
|
||||
|------|------------|
|
||||
| Service 契约 | `tests/test_service_contract.py` |
|
||||
| Golden / fixture 回归 | `tests/test_golden_cases.py` |
|
||||
| 领域规则 | `tests/test_<domain>_rules.py` |
|
||||
| 校验逻辑 | `tests/test_<domain>_validation.py` |
|
||||
|
||||
命名需满足:`tests/` 根目录下 `test_*.py`,以便 `python tests/run_tests.py` 默认发现。
|
||||
|
||||
更多分层说明见 **`tests/README.md`**(「我该把测试写在哪里?」与「新技能最小测试清单」)。
|
||||
37
tests/samples/test_golden_cases.py.sample
Normal file
37
tests/samples/test_golden_cases.py.sample
Normal file
@@ -0,0 +1,37 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 样例:复制为 ``tests/test_golden_cases.py`` 后运行;默认不收集。
|
||||
"""
|
||||
Golden fixture 回归(示意)。
|
||||
|
||||
- 从 ``tests/fixtures/`` 读取脱敏 JSON。
|
||||
- 调用 service 层(复制后替换为真实 import)。
|
||||
- 断言关键字段,而非全文 diff(外部系统常带时间戳/非确定性字段)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
|
||||
|
||||
def _fixtures_dir() -> str:
|
||||
return os.path.join(os.path.dirname(__file__), "..", "fixtures")
|
||||
|
||||
|
||||
class TestGoldenCasesSample(unittest.TestCase):
|
||||
def test_sample_request_matches_expected_shape(self) -> None:
|
||||
req_path = os.path.join(_fixtures_dir(), "sample_request.json")
|
||||
exp_path = os.path.join(_fixtures_dir(), "expected_response.json")
|
||||
with open(req_path, encoding="utf-8") as f:
|
||||
req = json.load(f)
|
||||
with open(exp_path, encoding="utf-8") as f:
|
||||
exp = json.load(f)
|
||||
self.assertEqual(req["request_id"], "req_test_001")
|
||||
self.assertTrue(req["parameters"]["options"]["dry_run"])
|
||||
# 示意:out = run(req); 然后 assert out["success"] == exp["success"] 等关键字段
|
||||
self.assertTrue(exp["success"])
|
||||
self.assertEqual(exp["data"]["status"], "ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
46
tests/samples/test_service_contract.py.sample
Normal file
46
tests/samples/test_service_contract.py.sample
Normal file
@@ -0,0 +1,46 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 本文件为样例:复制到 ``tests/test_service_contract.py``(或业务仓 tests 根)后按实际 service 改名运行。
|
||||
# 默认 **不会** 被 ``python tests/run_tests.py`` 收集(扩展名为 .sample)。
|
||||
"""
|
||||
Service 层契约测试范式(示意)。
|
||||
|
||||
复制为真实技能后:
|
||||
1. 将 ``from service.your_service import run`` 替换为实际模块与入口函数。
|
||||
2. 用 ``FakeAdapter`` / 内存 stub 替代真实 ERP/TMS/WMS 等外呼。
|
||||
3. 需要真实外网或真实 RPA 时,勿在本文件直接写死凭证;改用 ``tests/integration/*.sample`` + 环境开关。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import FakeAdapter
|
||||
|
||||
|
||||
# from service.your_service import run # noqa: ERA001 — 复制后取消注释并实现
|
||||
|
||||
|
||||
class TestServiceContractSample(unittest.TestCase):
|
||||
"""三类常见契约:成功路径、结构化错误、上游超时转可重试错误。"""
|
||||
|
||||
def test_success_path_returns_success_true(self) -> None:
|
||||
# 示意:run(payload, adapter=FakeAdapter("success")) -> {"success": True, ...}
|
||||
ad = FakeAdapter("success")
|
||||
out = ad.call({"op": "ping"})
|
||||
self.assertTrue(out.get("success"))
|
||||
|
||||
def test_missing_required_field_returns_structured_error_not_bare_exception(self) -> None:
|
||||
# 示意:业务层应对必填字段做校验,返回 {"success": False, "error": {"code": "...", "message": "..."}}
|
||||
err = {"success": False, "error": {"code": "VALIDATION", "message": "missing shipment_id"}}
|
||||
self.assertFalse(err["success"])
|
||||
self.assertIn("code", err["error"])
|
||||
|
||||
def test_adapter_timeout_maps_to_retriable_error(self) -> None:
|
||||
# 示意:捕获 TimeoutError 后映射为业务可重试错误码,而不是让裸异常穿透 CLI
|
||||
ad = FakeAdapter("timeout")
|
||||
with self.assertRaises(TimeoutError):
|
||||
ad.call({})
|
||||
# 真实实现中:except TimeoutError: return {"success": False, "error": {"code": "UPSTREAM_TIMEOUT", "retriable": True}}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
159
tests/test_adapter_profile_policy.py
Normal file
159
tests/test_adapter_profile_policy.py
Normal file
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""adapter profile / 环境开关策略:默认不触碰真实 API 与真实 RPA。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from adapter_test_utils import (
|
||||
ALLOWED_TEST_TARGETS,
|
||||
FakeAdapter,
|
||||
assert_no_real_network_env,
|
||||
get_test_target,
|
||||
should_skip_profile,
|
||||
)
|
||||
|
||||
|
||||
def _save_env(keys: tuple[str, ...]) -> dict[str, str | None]:
|
||||
return {k: os.environ.get(k) for k in keys}
|
||||
|
||||
|
||||
def _restore_env(saved: dict[str, str | None]) -> None:
|
||||
for k, v in saved.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
_ENV_KEYS = (
|
||||
"OPENCLAW_TEST_TARGET",
|
||||
"OPENCLOW_TEST_TARGET",
|
||||
"ALLOW_REAL_API",
|
||||
"ALLOW_REAL_RPA",
|
||||
"ALLOW_WRITE_ACTIONS",
|
||||
)
|
||||
|
||||
|
||||
class TestAdapterProfilePolicy(unittest.TestCase):
|
||||
def test_get_test_target_reads_opencylow_typo_alias(self) -> None:
|
||||
"""兼容环境变量历史拼写 OPENCLOW_TEST_TARGET。"""
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
os.environ.pop("OPENCLAW_TEST_TARGET", None)
|
||||
os.environ.pop("OPENCLOW_TEST_TARGET", None)
|
||||
os.environ["OPENCLOW_TEST_TARGET"] = "mock"
|
||||
self.assertEqual(get_test_target(), "mock")
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_get_test_target_defaults_to_unit(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
for k in _ENV_KEYS:
|
||||
os.environ.pop(k, None)
|
||||
self.assertEqual(get_test_target(), "unit")
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_get_test_target_invalid_raises(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
for k in _ENV_KEYS:
|
||||
os.environ.pop(k, None)
|
||||
os.environ["OPENCLAW_TEST_TARGET"] = "not_a_valid_target"
|
||||
with self.assertRaises(ValueError):
|
||||
get_test_target()
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_allowed_targets_contains_expected(self) -> None:
|
||||
self.assertTrue({"unit", "mock", "simulator_api", "real_api"}.issubset(ALLOWED_TEST_TARGETS))
|
||||
|
||||
def test_simulator_api_runs_when_target_matches(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
os.environ["OPENCLAW_TEST_TARGET"] = "simulator_api"
|
||||
skip, _ = should_skip_profile("simulator_api")
|
||||
self.assertFalse(skip)
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_unit_target_skips_simulator_and_real_profiles(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
for k in _ENV_KEYS:
|
||||
os.environ.pop(k, None)
|
||||
self.assertEqual(get_test_target(), "unit")
|
||||
for prof in ("simulator_api", "simulator_rpa", "real_api", "real_rpa"):
|
||||
skip, reason = should_skip_profile(prof)
|
||||
self.assertTrue(skip, msg=f"{prof}: {reason}")
|
||||
skip_mock, _ = should_skip_profile("mock")
|
||||
self.assertFalse(skip_mock)
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_real_api_requires_allow_flag(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
os.environ["OPENCLAW_TEST_TARGET"] = "real_api"
|
||||
os.environ.pop("ALLOW_REAL_API", None)
|
||||
skip, reason = should_skip_profile("real_api")
|
||||
self.assertTrue(skip)
|
||||
self.assertIn("ALLOW_REAL_API", reason)
|
||||
os.environ["ALLOW_REAL_API"] = "1"
|
||||
skip2, _ = should_skip_profile("real_api", write=False)
|
||||
self.assertFalse(skip2)
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_real_api_write_requires_allow_write_actions(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
os.environ["OPENCLAW_TEST_TARGET"] = "real_api"
|
||||
os.environ["ALLOW_REAL_API"] = "1"
|
||||
os.environ.pop("ALLOW_WRITE_ACTIONS", None)
|
||||
skip, reason = should_skip_profile("real_api", write=True)
|
||||
self.assertTrue(skip)
|
||||
self.assertIn("ALLOW_WRITE_ACTIONS", reason)
|
||||
os.environ["ALLOW_WRITE_ACTIONS"] = "1"
|
||||
skip2, _ = should_skip_profile("real_api", write=True)
|
||||
self.assertFalse(skip2)
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_real_rpa_requires_allow_rpa_flag(self) -> None:
|
||||
saved = _save_env(_ENV_KEYS)
|
||||
try:
|
||||
os.environ["OPENCLAW_TEST_TARGET"] = "real_rpa"
|
||||
os.environ.pop("ALLOW_REAL_RPA", None)
|
||||
skip, reason = should_skip_profile("real_rpa")
|
||||
self.assertTrue(skip)
|
||||
self.assertIn("ALLOW_REAL_RPA", reason)
|
||||
os.environ["ALLOW_REAL_RPA"] = "1"
|
||||
skip2, _ = should_skip_profile("real_rpa", write=False)
|
||||
self.assertFalse(skip2)
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
def test_fake_adapter_modes(self) -> None:
|
||||
self.assertEqual(FakeAdapter("success").call({"a": 1})["success"], True)
|
||||
with self.assertRaises(TimeoutError):
|
||||
FakeAdapter("timeout").call({})
|
||||
bad = FakeAdapter("invalid_response").call({})
|
||||
self.assertNotIsInstance(bad, dict)
|
||||
with self.assertRaises(PermissionError):
|
||||
FakeAdapter("unauthorized").call({})
|
||||
|
||||
def test_assert_no_real_network_env(self) -> None:
|
||||
saved = _save_env(("ALLOW_REAL_API", "ALLOW_REAL_RPA"))
|
||||
try:
|
||||
os.environ.pop("ALLOW_REAL_API", None)
|
||||
os.environ.pop("ALLOW_REAL_RPA", None)
|
||||
assert_no_real_network_env()
|
||||
finally:
|
||||
_restore_env(saved)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
75
tests/test_cli_smoke.py
Normal file
75
tests/test_cli_smoke.py
Normal file
@@ -0,0 +1,75 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通用 CLI 冒烟:用法、health、version、logs、log-get(不触网、不深测 run 占位)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
|
||||
from _support import IsolatedDataRoot
|
||||
|
||||
# scripts/ 已由 _support 注入 sys.path
|
||||
from cli.app import main
|
||||
from util.constants import SKILL_SLUG
|
||||
|
||||
|
||||
class TestCliSmoke(unittest.TestCase):
|
||||
def test_main_empty_argv_shows_usage_and_nonzero(self) -> None:
|
||||
buf = io.StringIO()
|
||||
err = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(err):
|
||||
rc = main([])
|
||||
self.assertEqual(rc, 1)
|
||||
out = buf.getvalue()
|
||||
self.assertIn("通用业务技能模板", out)
|
||||
self.assertIn("health", out)
|
||||
|
||||
def test_health_zero(self) -> None:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
|
||||
rc = main(["health"])
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
def test_version_json_and_matches_constants_slug(self) -> None:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
|
||||
rc = main(["version"])
|
||||
self.assertEqual(rc, 0)
|
||||
payload = json.loads(buf.getvalue().strip())
|
||||
self.assertIn("version", payload)
|
||||
self.assertIn("skill", payload)
|
||||
self.assertEqual(payload["skill"], SKILL_SLUG)
|
||||
|
||||
def test_logs_empty_returns_zero(self) -> None:
|
||||
with IsolatedDataRoot():
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
|
||||
rc = main(["logs"])
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertIn("暂无", buf.getvalue())
|
||||
|
||||
def test_log_get_non_numeric_returns_nonzero(self) -> None:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
|
||||
rc = main(["log-get", "not-a-number"])
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertIn("数字", buf.getvalue())
|
||||
|
||||
def test_run_placeholder_returns_nonzero_without_network(self) -> None:
|
||||
"""占位 run:不验证业务成功,仅确认模板提示且退出码非 0(无 AUTH_BASE 时不发 HTTP)。"""
|
||||
old_auth = os.environ.pop("JIANGCHANG_AUTH_BASE_URL", None)
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
|
||||
rc = main(["run"])
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertIn("模板", buf.getvalue())
|
||||
finally:
|
||||
if old_auth is not None:
|
||||
os.environ["JIANGCHANG_AUTH_BASE_URL"] = old_auth
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
43
tests/test_db_smoke.py
Normal file
43
tests/test_db_smoke.py
Normal file
@@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""task_logs 表:init 幂等、写入与查询(全程隔离数据目录)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from _support import IsolatedDataRoot
|
||||
|
||||
|
||||
class TestDbSmoke(unittest.TestCase):
|
||||
def test_init_db_idempotent_and_crud_smoke(self) -> None:
|
||||
with IsolatedDataRoot():
|
||||
from db.connection import init_db
|
||||
from db import task_logs_repository as tlr
|
||||
|
||||
init_db()
|
||||
init_db() # 幂等
|
||||
|
||||
new_id = tlr.save_task_log(
|
||||
task_type="demo_task",
|
||||
target_id="tgt-1",
|
||||
input_id="42",
|
||||
input_title="t",
|
||||
status="success",
|
||||
error_msg=None,
|
||||
result_summary=None,
|
||||
)
|
||||
self.assertIsInstance(new_id, int)
|
||||
self.assertGreater(new_id, 0)
|
||||
|
||||
rows = tlr.list_task_logs(limit=10)
|
||||
self.assertTrue(any(r[0] == new_id for r in rows))
|
||||
|
||||
row = tlr.get_task_log_by_id(new_id)
|
||||
self.assertIsNotNone(row)
|
||||
self.assertEqual(int(row[0]), new_id)
|
||||
|
||||
missing = tlr.get_task_log_by_id(999_999)
|
||||
self.assertIsNone(missing)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
51
tests/test_entrypoint_subprocess.py
Normal file
51
tests/test_entrypoint_subprocess.py
Normal file
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通过 subprocess 调用 ``python scripts/main.py``,验证真实入口(非仅 import main)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from _support import IsolatedDataRoot, get_skill_root
|
||||
|
||||
|
||||
def _run_main(args: list[str], timeout: int = 15) -> subprocess.CompletedProcess[str]:
|
||||
root = get_skill_root()
|
||||
main_py = os.path.join(root, "scripts", "main.py")
|
||||
env = os.environ.copy()
|
||||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||||
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
||||
return subprocess.run(
|
||||
[sys.executable, main_py, *args],
|
||||
cwd=root,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
class TestEntrypointSubprocess(unittest.TestCase):
|
||||
def test_health_exit_zero(self) -> None:
|
||||
with IsolatedDataRoot():
|
||||
cp = _run_main(["health"])
|
||||
self.assertEqual(cp.returncode, 0, msg=cp.stderr + cp.stdout)
|
||||
|
||||
def test_version_json_and_skill_slug(self) -> None:
|
||||
with IsolatedDataRoot():
|
||||
cp = _run_main(["version"])
|
||||
self.assertEqual(cp.returncode, 0, msg=cp.stderr + cp.stdout)
|
||||
payload = json.loads(cp.stdout.strip())
|
||||
self.assertIn("version", payload)
|
||||
self.assertIn("skill", payload)
|
||||
from util.constants import SKILL_SLUG
|
||||
|
||||
self.assertEqual(payload["skill"], SKILL_SLUG)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
65
tests/test_runtime_paths.py
Normal file
65
tests/test_runtime_paths.py
Normal file
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""util.runtime_paths:技能根、DB 路径、数据目录均落在隔离数据根下。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from _support import IsolatedDataRoot, get_skill_root
|
||||
|
||||
_FAKE_CLAW_ROOT = r"D:\jiangchang-data"
|
||||
|
||||
|
||||
class TestRuntimePaths(unittest.TestCase):
|
||||
def test_paths_under_isolated_root(self) -> None:
|
||||
win_default = r"D:\jiangchang-data"
|
||||
with IsolatedDataRoot() as tmp:
|
||||
import importlib
|
||||
|
||||
import util.runtime_paths as rp
|
||||
|
||||
importlib.reload(rp)
|
||||
|
||||
skill_root = rp.get_skill_root()
|
||||
self.assertTrue(os.path.isdir(skill_root))
|
||||
self.assertTrue(os.path.isfile(os.path.join(skill_root, "SKILL.md")))
|
||||
|
||||
db_path = rp.get_db_path()
|
||||
self.assertTrue(os.path.normpath(db_path).startswith(os.path.normpath(tmp)))
|
||||
self.assertNotIn(win_default, db_path)
|
||||
|
||||
data_dir = rp.get_skill_data_dir()
|
||||
self.assertTrue(os.path.normpath(data_dir).startswith(os.path.normpath(tmp)))
|
||||
self.assertIn("_test", data_dir.replace("\\", "/"))
|
||||
self.assertNotIn(win_default, data_dir)
|
||||
|
||||
self.assertEqual(get_skill_root(), skill_root)
|
||||
|
||||
def test_isolation_overrides_prefixed_claw_data_root(self) -> None:
|
||||
"""先设假的 CLAW_DATA_ROOT,再进入隔离;get_db_path 必须落在 tempdir(防漏设 CLAW_*)。"""
|
||||
saved = {k: os.environ.get(k) for k in ("CLAW_DATA_ROOT", "JIANGCHANG_DATA_ROOT", "CLAW_USER_ID", "JIANGCHANG_USER_ID")}
|
||||
try:
|
||||
os.environ["CLAW_DATA_ROOT"] = _FAKE_CLAW_ROOT
|
||||
os.environ["JIANGCHANG_DATA_ROOT"] = _FAKE_CLAW_ROOT
|
||||
with IsolatedDataRoot() as tmp:
|
||||
import importlib
|
||||
|
||||
import util.runtime_paths as rp
|
||||
|
||||
importlib.reload(rp)
|
||||
db_path = rp.get_db_path()
|
||||
norm_db = os.path.normcase(os.path.normpath(db_path))
|
||||
norm_tmp = os.path.normcase(os.path.normpath(tmp))
|
||||
self.assertTrue(norm_db.startswith(norm_tmp), msg=f"db_path={db_path!r} tmp={tmp!r}")
|
||||
norm_fake = os.path.normcase(os.path.normpath(_FAKE_CLAW_ROOT))
|
||||
self.assertFalse(norm_db.startswith(norm_fake), msg=f"db_path must not be under fake CLAW root: {db_path!r}")
|
||||
finally:
|
||||
for k, v in saved.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
55
tests/test_skill_metadata.py
Normal file
55
tests/test_skill_metadata.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SKILL.md 与 util.constants.SKILL_SLUG 一致性(防复制后漏改 constants)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
|
||||
from _support import get_skill_root
|
||||
|
||||
|
||||
def _parse_openclaw_slug(skill_md_text: str) -> str:
|
||||
"""从 YAML frontmatter 中解析 metadata.openclaw.slug(无 PyYAML 依赖)。"""
|
||||
parts = skill_md_text.split("---", 2)
|
||||
if len(parts) < 2:
|
||||
raise ValueError("missing frontmatter")
|
||||
fm = parts[1]
|
||||
lines = fm.splitlines()
|
||||
for i, line in enumerate(lines):
|
||||
if re.match(r"^\s+openclaw:\s*$", line):
|
||||
for j in range(i + 1, len(lines)):
|
||||
inner = lines[j]
|
||||
if inner.strip() and inner[0] not in (" ", "\t"):
|
||||
break
|
||||
m = re.match(r"^(\s+)slug:\s*(.+)\s*$", inner)
|
||||
if m:
|
||||
return m.group(2).strip().strip("\"'")
|
||||
break
|
||||
raise ValueError("slug not found under openclaw")
|
||||
|
||||
|
||||
class TestSkillMetadata(unittest.TestCase):
|
||||
def test_skill_slug_alignment(self) -> None:
|
||||
root = get_skill_root()
|
||||
skill_dir = os.path.basename(root)
|
||||
md_path = os.path.join(root, "SKILL.md")
|
||||
with open(md_path, encoding="utf-8") as f:
|
||||
md = f.read()
|
||||
slug_md = _parse_openclaw_slug(md)
|
||||
|
||||
from util.constants import SKILL_SLUG
|
||||
|
||||
self.assertEqual(slug_md, SKILL_SLUG, "SKILL.md slug 必须与 constants.SKILL_SLUG 一致")
|
||||
|
||||
if skill_dir == "skill-template":
|
||||
# 模板仓库本体:允许占位 slug
|
||||
self.assertEqual(SKILL_SLUG, "your-skill-slug")
|
||||
else:
|
||||
self.assertNotEqual(SKILL_SLUG, "your-skill-slug", "复制为真实技能后不得保留占位 slug")
|
||||
self.assertEqual(SKILL_SLUG, skill_dir)
|
||||
self.assertEqual(slug_md, skill_dir)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user