@buaa_smat/hometrans 0.1.19 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +18 -0
  2. package/agents/code-reviewer.md +1 -1
  3. package/agents/self-tester.md +33 -354
  4. package/agents/test-case-generation-generator.md +1 -1
  5. package/dist/cli/config-store.js +4 -84
  6. package/dist/cli/config.js +6 -8
  7. package/dist/cli/init.js +29 -36
  8. package/dist/cli/uninstall.js +2 -2
  9. package/env-requirements.json +5 -4
  10. package/package.json +3 -5
  11. package/resource/project_architecture.svg +1 -1
  12. package/skills/hmos-convert-pipeline/SKILL.md +31 -21
  13. package/skills/hmos-incremental-ui-align/README.md +5 -5
  14. package/skills/hmos-incremental-ui-align/SKILL.md +2 -2
  15. package/skills/hmos-integration-test/README.md +58 -17
  16. package/skills/hmos-integration-test/SKILL.md +107 -40
  17. package/{tools/test-tools/autotest/engine → skills/hmos-integration-test/scripts}/report-tool.ts +71 -53
  18. package/skills/hmos-integration-test/scripts/resolve-metadata-tool.ts +125 -0
  19. package/skills/hmos-integration-test/scripts/self-test-runner.ts +756 -0
  20. package/{tools/test-tools/autotest/engine → skills/hmos-integration-test/scripts}/testcases-tool.ts +38 -45
  21. package/skills/hmos-test-case-generation/references/contract.md +3 -3
  22. package/tools/test-tools/autotest/config.ts +0 -175
  23. package/tools/test-tools/autotest/deps/autotest-agent-0.1.1.tgz +0 -0
  24. package/tools/test-tools/autotest/docs/README.md +0 -266
  25. package/tools/test-tools/autotest/docs/testcases_schema.md +0 -143
  26. package/tools/test-tools/autotest/engine/batch-launcher.ts +0 -327
  27. package/tools/test-tools/autotest/engine/self-test-runner.ts +0 -961
  28. package/tools/test-tools/autotest/paths.ts +0 -41
  29. package/tools/test-tools/autotest/resolve-metadata-tool.ts +0 -143
  30. package/tools/test-tools/autotest/runner/logger.ts +0 -45
  31. package/tools/test-tools/autotest/runner/process-utils.ts +0 -41
  32. package/tools/test-tools/autotest/validate.ts +0 -167
@@ -1,143 +0,0 @@
1
- # testcases.json 生成规范
2
-
3
- > 本文件是 `testcases.json` 的**唯一权威格式定义**。
4
- > 生成 `testcases.json` 时,必须严格遵循本规范。
5
-
6
- ---
7
-
8
- ## 1. 文件结构
9
-
10
- 根元素必须是 **JSON 数组 `[]`**,每个元素是一个测试用例对象。
11
-
12
- ```json
13
- [
14
- { ... },
15
- { ... }
16
- ]
17
- ```
18
-
19
- ## 2. 测试用例对象(4 个必填字段)
20
-
21
- | 字段 | 类型 | 说明 | 示例 |
22
- |------|------|------|------|
23
- | `case_name` | `string` | 测试场景标题,来自 `### Scenario:` | `"冷启动初始化后正常进入主页面"` |
24
- | `bundle_name` | `string` | HarmonyOS 应用包名 | `"com.example.tuku"` |
25
- | `app_name` | `string` | 应用显示名称(不要翻译,保持原始值) | `"Tuku"` |
26
- | `test_steps` | `string` | 测试步骤文本(见下方模板) | 见第 3 节 |
27
-
28
- > **不允许**出现其他字段(如 `id`、`priority`、`preconditions`、`spec_id` 等)。
29
-
30
- ## 3. `test_steps` 字符串模板
31
-
32
- 每个测试用例的 `test_steps` 必须严格按以下模板生成:
33
-
34
- ```
35
- 动作:{actions}
36
- 预期结果:{expected_results}
37
- ```
38
-
39
- `test_steps` 中**只包含** `动作:` 和 `预期结果:` 两行,不包含任何段落头(如 `【说明】`、`【待测应用信息】`、`【测试用例】` 等)。
40
-
41
- ### 变量说明
42
-
43
- | 变量 | 来源 | 处理规则 |
44
- |------|------|----------|
45
- | `{actions}` | `test_case.md` 中的 `- 动作:` 行 | 所有应用名引用(如"图库应用"、"Tuku"等)替换为 `bundle_name` |
46
- | `{expected_results}` | `test_case.md` 中的 `- 预期结果:` 行 | 原样使用,同样执行 app_name → bundle_name 替换 |
47
-
48
- ## 4. 完整示例
49
-
50
- ```json
51
- [
52
- {
53
- "case_name": "冷启动初始化后正常进入主页面",
54
- "bundle_name": "com.example.tuku",
55
- "app_name": "Tuku",
56
- "test_steps": "动作:打开com.example.tuku\n预期结果:文件夹网格主页面成功展示文件夹列表"
57
- },
58
- {
59
- "case_name": "首次打开应用-授权通过-展示所有文件夹",
60
- "bundle_name": "com.example.tuku",
61
- "app_name": "Tuku",
62
- "test_steps": "动作:打开com.example.tuku -> 点击允许按钮授予媒体访问权限\n预期结果:权限授予成功,跳转到文件夹网格主页面,可见所有包含媒体的文件夹"
63
- }
64
- ]
65
- ```
66
-
67
- ## 5. 禁止字符串
68
-
69
- 以下字符串**不得出现在 `test_steps` 中的任何位置**。如果 `test_case.md` 源文件中包含这些内容,提取时必须删除或改写:
70
-
71
- | 禁止字符串 | 原因 | 处理方式 |
72
- |------------|------|----------|
73
- | `前置条件` | 前置条件不应进入测试步骤 | 删除含该词的句子 |
74
- | `Spec:` | Spec 引用不应出现 | 删除 |
75
- | `Scenario:` | Scenario 引用不应出现 | 删除 |
76
- | `ability_name:` | 不允许出现在 test_steps 中 | 删除 |
77
- | `module_name:` | 不允许出现在 test_steps 中 | 删除 |
78
-
79
- > **不得出现任何 `【xxx】` 段落头**(如 `【说明】`、`【待测应用信息】`、`【测试用例】`、`【前置条件】` 等)。`test_steps` 只包含 `动作:` 和 `预期结果:` 两行。
80
-
81
- ## 6. 错误格式示例
82
-
83
- ### 错误 1:使用结构化对象数组代替纯文本字符串
84
-
85
- ```json
86
- {
87
- "test_steps": [
88
- { "step": 1, "action": "launch_app", "params": { "bundle_name": "..." } }
89
- ]
90
- }
91
- ```
92
- **正确做法**: `test_steps` 必须是字符串,不是数组。
93
-
94
- ### 错误 2:根元素是对象而非数组
95
-
96
- ```json
97
- {
98
- "spec_id": "SPEC-01",
99
- "test_cases": [ ... ]
100
- }
101
- ```
102
- **正确做法**: 根元素必须是 `[ ... ]`。
103
-
104
- ### 错误 3:包含段落头
105
-
106
- ```json
107
- {
108
- "test_steps": "【说明】\n...\n\n【待测应用信息】\napp_name: Tuku\nbundle_name: com.example.tuku\n\n【测试用例】\n动作:...\n预期结果:..."
109
- }
110
- ```
111
- **正确做法**: `test_steps` 中不允许任何 `【xxx】` 段落头,只包含 `动作:` 和 `预期结果:` 两行。
112
-
113
- ### 错误 4:包含额外字段
114
-
115
- ```json
116
- {
117
- "id": "TC-001",
118
- "priority": "P0",
119
- "preconditions": ["..."],
120
- "case_name": "...",
121
- "test_steps": "..."
122
- }
123
- ```
124
- **正确做法**: 只允许 `case_name`、`bundle_name`、`app_name`、`test_steps` 四个字段。
125
-
126
- ### 错误 5:缺少必要行
127
-
128
- ```json
129
- {
130
- "test_steps": "打开图库应用 -> 检查主页面"
131
- }
132
- ```
133
- **正确做法**: 必须包含 `动作:` 和 `预期结果:` 两行。
134
-
135
- ## 7. 验证
136
-
137
- 生成后必须运行验证脚本:
138
-
139
- ```bash
140
- node "$HOMETRANS_HOME/dist/test-tools/autotest/testcases-tool.js" validate "<path-to-testcases.json>"
141
- ```
142
-
143
- 只有输出 `VALIDATION PASSED` 才算生成成功。
@@ -1,327 +0,0 @@
1
- /**
2
- * Batch launcher — the detached background process that runs the Node.js
3
- * `@autotest/agent` engine programmatically via `new AutoTestAgent({...})`.
4
- *
5
- * Spawned detached by `self-test-runner.ts` `cmdRun` (which writes `batch.pid` +
6
- * emits `{status:'RUNNING', pid}` then exits). This process:
7
- *
8
- * 1. constructs `new AutoTestAgent({ apiKey, modelName, baseUrl, provider,
9
- * deviceSn, ip, port, agentMode })` from the `AUTOTEST_*` env vars that
10
- * `cmdRun` derived from `~/.hometrans/config.json` — so the user's API_KEY
11
- * / model / device flow in through the constructor, no config.yaml needed;
12
- * 2. reads the testcases (JSON array or JSONL — same input as the former
13
- * Python `AutoTest.batch`);
14
- * 3. runs each case via `agent.runTask(test_steps, { reportDir, taskName })`;
15
- * 4. writes `task_results.jsonl` + `summary.json` in the SAME schema the
16
- * Python `AutoTest.batch` produced, so the HomeTrans `status` /
17
- * `report-tool` contract keeps working unchanged.
18
- *
19
- * STDOUT/STDERR are captured to `batch_stdout.log` by the spawner; this process
20
- * exits 0 on completion regardless of per-case pass/fail (a non-zero exit would
21
- * be interpreted as a launch failure by `spawnBatch`).
22
- */
23
- import { createRequire } from 'node:module';
24
- import fs from 'node:fs';
25
- import path from 'node:path';
26
- import { fileURLToPath } from 'node:url';
27
- import { Command } from 'commander';
28
- import type {
29
- AutoTestAgent,
30
- AutoTestAgentConfig,
31
- RunTaskOptions,
32
- TaskResult,
33
- } from '@autotest/agent';
34
-
35
- const require = createRequire(import.meta.url);
36
- const { AutoTestAgent: AutoTestAgentCtor } = require('@autotest/agent') as {
37
- AutoTestAgent: new (config: AutoTestAgentConfig) => AutoTestAgent;
38
- };
39
-
40
- const UTF_8 = 'utf-8';
41
- const CASE_TIMEOUT_MS = 10 * 60 * 1000;
42
- const DEFAULT_PROMPT_VERSION = 'v2.0';
43
-
44
- interface CaseRow {
45
- uuid: string;
46
- spec: string;
47
- case_name: string;
48
- test_steps: string;
49
- execute_mode?: string;
50
- [k: string]: unknown;
51
- }
52
-
53
- interface ResultRow {
54
- exec_index: number;
55
- uuid: string;
56
- spec: string;
57
- case_name: string;
58
- category: string;
59
- test_steps: string;
60
- report_dir: string;
61
- start_time: string;
62
- end_time: string;
63
- duration_seconds: number;
64
- status: 'PASS' | 'FAIL' | 'UNKNOWN';
65
- return_code: number;
66
- reason: string;
67
- }
68
-
69
- interface LauncherArgs {
70
- taskDir: string;
71
- testcases: string;
72
- category: string;
73
- }
74
-
75
- function sanitizeFilename(name: string): string {
76
- return name.replace(/[\\/:*?"<>|]/g, '_');
77
- }
78
-
79
- function formatTimestamp(date: Date): string {
80
- const pad = (n: number) => String(n).padStart(2, '0');
81
- return (
82
- `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
83
- `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
84
- );
85
- }
86
-
87
- function readTestCases(filePath: string): CaseRow[] {
88
- let content = fs.readFileSync(filePath, UTF_8);
89
- if (content.charCodeAt(0) === 0xfeff) content = content.slice(1);
90
- try {
91
- const parsed = JSON.parse(content);
92
- if (Array.isArray(parsed)) return parsed as CaseRow[];
93
- throw new Error('not an array');
94
- } catch {
95
- // Fall back to JSONL.
96
- const cases: CaseRow[] = [];
97
- for (const line of content.split('\n')) {
98
- const trimmed = line.trim();
99
- if (!trimmed) continue;
100
- try {
101
- cases.push(JSON.parse(trimmed) as CaseRow);
102
- } catch {
103
- // skip invalid lines
104
- }
105
- }
106
- return cases;
107
- }
108
- }
109
-
110
- function parseArgs(argv: string[]): LauncherArgs {
111
- const program = new Command();
112
- program.exitOverride();
113
- program
114
- .requiredOption('--task-dir <dir>', '任务目录')
115
- .requiredOption('--testcases <path>', '测试用例文件(JSON 数组或 JSONL)')
116
- .option('--category <name>', '测试分类名称', 'self_test');
117
- try {
118
- program.parse(argv, { from: 'user' });
119
- } catch (err) {
120
- const e = err as { code?: string };
121
- if (e.code === 'commander.helpDisplayed') {
122
- process.exit(0);
123
- }
124
- console.error('用法: node batch-launcher.ts --task-dir <dir> --testcases <path> [--category <name>]');
125
- process.exit(2);
126
- }
127
- const opts = program.opts() as LauncherArgs;
128
- return { taskDir: opts.taskDir, testcases: opts.testcases, category: opts.category };
129
- }
130
-
131
- /** Construct the agent from AUTOTEST_* env vars (set by `cmdRun` from config.json). */
132
- function createAgent(): AutoTestAgent {
133
- const promptVersion = process.env.AUTOTEST_PROMPT_VERSION || DEFAULT_PROMPT_VERSION;
134
- const envPort = process.env.AUTOTEST_PORT;
135
- const envMaxSteps = process.env.AUTOTEST_MAX_STEPS;
136
- const numOrUndef = (raw: string | undefined): number | undefined => {
137
- if (!raw) return undefined;
138
- const n = Number(raw);
139
- return Number.isFinite(n) ? n : undefined;
140
- };
141
- // Resolve the bundled config.yaml inside @autotest/agent so the agent loads
142
- // model/device/agent defaults (base_url, api_key, …) even when AUTOTEST_*
143
- // env vars are not set (e.g. running batch-launcher standalone without
144
- // HomeTrans's config.json → AUTOTEST_* mapping). The ConfigManager converts
145
- // snake_case YAML keys to camelCase before zod validation, so `base_url` in
146
- // the YAML becomes `baseUrl` as the schema expects.
147
- const agentMain = require.resolve('@autotest/agent');
148
- const configPath = path.join(path.dirname(agentMain), 'common', 'config', 'config.yaml');
149
- const config: AutoTestAgentConfig = {
150
- configPath,
151
- apiKey: process.env.AUTOTEST_API_KEY,
152
- modelName: process.env.AUTOTEST_MODEL,
153
- baseUrl: process.env.AUTOTEST_BASE_URL,
154
- provider: process.env.AUTOTEST_PROVIDER,
155
- deviceSn: process.env.AUTOTEST_DEVICE_SN || undefined,
156
- ip: process.env.AUTOTEST_IP,
157
- port: numOrUndef(envPort),
158
- agentMode: (process.env.AUTOTEST_MODE || undefined) as AutoTestAgentConfig['agentMode'],
159
- maxSteps: numOrUndef(envMaxSteps),
160
- // The SingleAgent resolves its prompt version from `model.unified.promptType`
161
- // (loadPrompt(SINGLE, config.model.unified.promptType)), whose zod default is
162
- // 'default' → 'vdefault' (not a real version). Inject the real version through
163
- // configOverrides — the constructor's route for any extra config the user
164
- // wants to set through `new`.
165
- configOverrides: { model: { unified: { promptType: promptVersion } } },
166
- };
167
- return new AutoTestAgentCtor(config);
168
- }
169
-
170
- /** Run one task with a hard timeout (mirrors batch_runner.runWithTimeout). */
171
- function runWithTimeout(
172
- agent: AutoTestAgent,
173
- task: string,
174
- options: RunTaskOptions,
175
- timeoutMs: number,
176
- ): Promise<TaskResult> {
177
- let timer: NodeJS.Timeout | undefined;
178
- const timeout = new Promise<never>((_, reject) => {
179
- timer = setTimeout(
180
- () => reject(new Error(`Execution timed out (exceeded ${timeoutMs / 1000} seconds)`)),
181
- timeoutMs,
182
- );
183
- });
184
- // Promise.race attaches handlers to both promises, so a late runTask
185
- // resolution/rejection after timeout is never "unhandled"; finally clears
186
- // the timer regardless of which settles first.
187
- return Promise.race([agent.runTask(task, options), timeout]).finally(() => {
188
- if (timer) clearTimeout(timer);
189
- });
190
- }
191
-
192
- async function main(): Promise<void> {
193
- const opts = parseArgs(process.argv.slice(2));
194
-
195
- const taskDir = path.resolve(opts.taskDir);
196
- fs.mkdirSync(taskDir, { recursive: true });
197
- const jsonlFile = path.join(taskDir, 'task_results.jsonl');
198
-
199
- const testCases = readTestCases(opts.testcases);
200
- const total = testCases.length;
201
- if (total === 0) {
202
- console.log('No test cases, exiting');
203
- return;
204
- }
205
-
206
- const indexWidth = String(total).length;
207
-
208
- console.log(`Total test cases to execute: ${total}`);
209
- console.log(`Test category: ${opts.category}`);
210
- console.log(`Task directory: ${taskDir}`);
211
- console.log('='.repeat(60));
212
-
213
- // promptVersion is injected via the constructor's configOverrides (see
214
- // createAgent) because AgentAPIImpl reads it from effectiveConfig, not the
215
- // per-call option.
216
- const agent = createAgent();
217
-
218
- let pass = 0;
219
- let fail = 0;
220
- let unknown = 0;
221
- const batchStart = new Date();
222
-
223
- for (let idx = 1; idx <= total; idx++) {
224
- const tc = testCases[idx - 1];
225
- const uuid = String(tc.uuid ?? '');
226
- const spec = String(tc.spec ?? '');
227
- const caseName = String(tc.case_name ?? '');
228
- const testSteps = String(tc.test_steps ?? '');
229
- const caseMode = String(tc.execute_mode ?? '');
230
-
231
- const dirname = uuid
232
- ? sanitizeFilename(`${uuid}_${caseName}`)
233
- : sanitizeFilename(`${String(idx).padStart(indexWidth, '0')}_${caseName}`);
234
- const reportDir = path.join(taskDir, dirname).replace(/\\/g, '/');
235
- fs.mkdirSync(reportDir, { recursive: true });
236
-
237
- console.log('\n' + '-'.repeat(60));
238
- console.log(`[${opts.category}][${String(idx).padStart(indexWidth, '0')}/${total}] Execute: ${caseName}`);
239
- console.log('-'.repeat(60));
240
-
241
- const start = new Date();
242
- const runOpts: RunTaskOptions = {
243
- reportDir,
244
- taskName: caseName,
245
- ...(caseMode ? { agentMode: caseMode as RunTaskOptions['agentMode'] } : {}),
246
- };
247
-
248
- let status: 'PASS' | 'FAIL' | 'UNKNOWN' = 'UNKNOWN';
249
- let reason = '';
250
- let returnCode = 0;
251
-
252
- try {
253
- const taskResult = await runWithTimeout(agent, testSteps, runOpts, CASE_TIMEOUT_MS);
254
- returnCode = taskResult.status === 'failed' ? 1 : 0;
255
- if (taskResult.status === 'completed') {
256
- status = 'PASS';
257
- pass += 1;
258
- } else if (taskResult.status === 'failed') {
259
- status = 'FAIL';
260
- reason = taskResult.errorMessage ?? 'Execution failed';
261
- fail += 1;
262
- } else {
263
- status = 'UNKNOWN';
264
- reason = `agent status=${taskResult.status}`;
265
- unknown += 1;
266
- }
267
- } catch (e) {
268
- returnCode = -1;
269
- status = 'FAIL';
270
- reason = `Execution error: ${e instanceof Error ? e.message : String(e)}`;
271
- fail += 1;
272
- }
273
-
274
- const end = new Date();
275
- const duration = (end.getTime() - start.getTime()) / 1000;
276
-
277
- const row: ResultRow = {
278
- exec_index: idx,
279
- uuid,
280
- spec,
281
- case_name: caseName,
282
- category: opts.category,
283
- test_steps: testSteps,
284
- report_dir: reportDir,
285
- start_time: formatTimestamp(start),
286
- end_time: formatTimestamp(end),
287
- duration_seconds: Math.round(duration * 100) / 100,
288
- status,
289
- return_code: returnCode,
290
- reason,
291
- };
292
- fs.appendFileSync(jsonlFile, JSON.stringify(row) + '\n', UTF_8);
293
-
294
- const icon = status === 'PASS' ? 'OK' : status === 'FAIL' ? 'X' : '?';
295
- console.log(`Result: [${icon}] ${status} | Duration: ${duration.toFixed(2)}s`);
296
- if (reason && status === 'FAIL') console.log(`Reason: ${reason.slice(0, 100)}`);
297
- console.log(`Report: ${reportDir}`);
298
- }
299
-
300
- const summary = {
301
- total_cases: total,
302
- pass_count: pass,
303
- fail_count: fail,
304
- unknown_count: unknown,
305
- pass_rate: `${total ? ((pass / total) * 100).toFixed(2) : '0.00'}%`,
306
- category: opts.category,
307
- start_time: formatTimestamp(batchStart),
308
- end_time: formatTimestamp(new Date()),
309
- task_dir: taskDir.replace(/\\/g, '/'),
310
- };
311
- fs.writeFileSync(path.join(taskDir, 'summary.json'), JSON.stringify(summary, null, 4), UTF_8);
312
-
313
- console.log('\n' + '='.repeat(60));
314
- console.log('Execution complete!');
315
- console.log(`Total cases: ${total}`);
316
- console.log(`Pass: ${pass}`);
317
- console.log(`Fail: ${fail}`);
318
- console.log(`Unknown: ${unknown}`);
319
- console.log(`Pass rate: ${summary.pass_rate}`);
320
- console.log(`Results file: ${jsonlFile}`);
321
- console.log('='.repeat(60));
322
- }
323
-
324
- main().catch((err) => {
325
- console.error('batch-launcher fatal:', err instanceof Error ? err.stack ?? err.message : String(err));
326
- process.exit(1);
327
- });