@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.
- package/README.md +18 -0
- package/agents/code-reviewer.md +1 -1
- package/agents/self-tester.md +33 -354
- package/agents/test-case-generation-generator.md +1 -1
- package/dist/cli/config-store.js +4 -84
- package/dist/cli/config.js +6 -8
- package/dist/cli/init.js +29 -36
- package/dist/cli/uninstall.js +2 -2
- package/env-requirements.json +5 -4
- package/package.json +3 -5
- package/resource/project_architecture.svg +1 -1
- package/skills/hmos-convert-pipeline/SKILL.md +31 -21
- package/skills/hmos-incremental-ui-align/README.md +5 -5
- package/skills/hmos-incremental-ui-align/SKILL.md +2 -2
- package/skills/hmos-integration-test/README.md +58 -17
- package/skills/hmos-integration-test/SKILL.md +107 -40
- package/{tools/test-tools/autotest/engine → skills/hmos-integration-test/scripts}/report-tool.ts +71 -53
- package/skills/hmos-integration-test/scripts/resolve-metadata-tool.ts +125 -0
- package/skills/hmos-integration-test/scripts/self-test-runner.ts +756 -0
- package/{tools/test-tools/autotest/engine → skills/hmos-integration-test/scripts}/testcases-tool.ts +38 -45
- package/skills/hmos-test-case-generation/references/contract.md +3 -3
- package/tools/test-tools/autotest/config.ts +0 -175
- package/tools/test-tools/autotest/deps/autotest-agent-0.1.1.tgz +0 -0
- package/tools/test-tools/autotest/docs/README.md +0 -266
- package/tools/test-tools/autotest/docs/testcases_schema.md +0 -143
- package/tools/test-tools/autotest/engine/batch-launcher.ts +0 -327
- package/tools/test-tools/autotest/engine/self-test-runner.ts +0 -961
- package/tools/test-tools/autotest/paths.ts +0 -41
- package/tools/test-tools/autotest/resolve-metadata-tool.ts +0 -143
- package/tools/test-tools/autotest/runner/logger.ts +0 -45
- package/tools/test-tools/autotest/runner/process-utils.ts +0 -41
- package/tools/test-tools/autotest/validate.ts +0 -167
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Self-Test Runner — orchestrates HAP install/uninstall + batch test execution.
|
|
4
|
+
*
|
|
5
|
+
* Mode (selected by flags, NOT subcommands):
|
|
6
|
+
* default (run) — hdc uninstall + hdc install + spawn batch_runner + poll until done.
|
|
7
|
+
* --status — report state from output files (summary.json / task_results.jsonl).
|
|
8
|
+
*
|
|
9
|
+
* STDOUT carries strict JSON; all logging goes to stderr / the log file.
|
|
10
|
+
*/
|
|
11
|
+
import { execFileSync, spawn, spawnSync } from 'node:child_process';
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
|
|
18
|
+
const HAP_INSTALL_WAIT = 3;
|
|
19
|
+
const INSTALL_TIMEOUT = 120;
|
|
20
|
+
const DEFAULT_CATEGORY = 'self_test';
|
|
21
|
+
const PER_CASE_TIMEOUT_SEC = 720;
|
|
22
|
+
|
|
23
|
+
// ---- logging ----
|
|
24
|
+
|
|
25
|
+
let logStream: fs.WriteStream | null = null;
|
|
26
|
+
|
|
27
|
+
function log(level: string, msg: string): void {
|
|
28
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
29
|
+
const d = new Date();
|
|
30
|
+
const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
31
|
+
const line = `[${ts}] ${level} ${msg}`;
|
|
32
|
+
if (logStream) logStream.write(line + '\n');
|
|
33
|
+
process.stderr.write(line + '\n');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const logger = {
|
|
37
|
+
info: (m: string) => log('INFO', m),
|
|
38
|
+
warning: (m: string) => log('WARNING', m),
|
|
39
|
+
error: (m: string) => log('ERROR', m),
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
function setupLogging(outputDir: string): void {
|
|
43
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
44
|
+
const d = new Date();
|
|
45
|
+
const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
46
|
+
const logPath = path.join(outputDir, `self_test_${ts}.log`);
|
|
47
|
+
fs.mkdirSync(path.dirname(logPath), { recursive: true });
|
|
48
|
+
logStream = fs.createWriteStream(logPath, { encoding: 'utf-8' });
|
|
49
|
+
logger.info(`日志文件: ${logPath}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ---- helpers ----
|
|
53
|
+
|
|
54
|
+
function timestampForFile(d: Date): string {
|
|
55
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
56
|
+
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sleep(sec: number): void {
|
|
60
|
+
if (sec <= 0) return;
|
|
61
|
+
if (process.platform === 'win32') {
|
|
62
|
+
spawnSync('powershell.exe', ['-NoProfile', '-Command', `Start-Sleep -Seconds ${sec}`], { stdio: 'ignore', timeout: sec * 1000 + 5000, windowsHide: true });
|
|
63
|
+
} else {
|
|
64
|
+
spawnSync('sleep', [String(sec)], { stdio: 'ignore', timeout: sec * 1000 + 5000 });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function findOnPath(name: string): string | null {
|
|
69
|
+
const finder = process.platform === 'win32' ? 'where' : 'which';
|
|
70
|
+
try {
|
|
71
|
+
const out = execFileSync(finder, [name], { encoding: 'utf-8', windowsHide: true, timeout: 5000 });
|
|
72
|
+
const first = out.split(/\r?\n/).find((l) => l.trim());
|
|
73
|
+
return first ? first.trim() : null;
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isProcessAlive(pid: number | undefined): boolean {
|
|
80
|
+
if (pid === undefined) return false;
|
|
81
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function killProcessTree(pid: number | undefined): void {
|
|
85
|
+
if (!pid) return;
|
|
86
|
+
if (process.platform === 'win32') {
|
|
87
|
+
// /T kills the whole descendant tree, /F forces termination
|
|
88
|
+
try { spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); } catch { /* already dead */ }
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
// POSIX: a detached child is a process-group leader, so -pid targets the whole group
|
|
92
|
+
try { process.kill(-pid, 'SIGKILL'); return; } catch { /* group gone */ }
|
|
93
|
+
try { process.kill(pid, 'SIGKILL'); } catch { /* already dead */ }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function getHdc(): string {
|
|
97
|
+
const found = findOnPath('hdc');
|
|
98
|
+
if (!found) { logger.error('hdc 未找到'); process.exit(1); }
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Dependency-free scan of a top-level YAML block (e.g. `agent:` / `device:`)
|
|
103
|
+
// for a direct-child scalar key. Only matches the key at the block's
|
|
104
|
+
// direct-child indent, so a deeper-nested same-named key (e.g. agent.unified.mode)
|
|
105
|
+
// is never misread as the top-level value. Best-effort — batch_runner re-reads
|
|
106
|
+
// the yaml itself, so this only needs to forward the common flat form.
|
|
107
|
+
function readYamlDirectChild(yamlPath: string, block: string, key: string): string {
|
|
108
|
+
try {
|
|
109
|
+
let text = fs.readFileSync(yamlPath, 'utf-8');
|
|
110
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
|
111
|
+
const lines = text.split(/\r?\n/);
|
|
112
|
+
let i = 0;
|
|
113
|
+
const blockRe = new RegExp(`^${block}:\\s*(#.*)?$`);
|
|
114
|
+
for (; i < lines.length; i++) if (blockRe.test(lines[i])) break;
|
|
115
|
+
if (i >= lines.length) return '';
|
|
116
|
+
// The first non-blank/non-comment line after `block:` defines the direct-child indent.
|
|
117
|
+
let childIndent = -1;
|
|
118
|
+
for (i++; i < lines.length; i++) {
|
|
119
|
+
const ln = lines[i];
|
|
120
|
+
if (ln.trim() === '' || /^\s*#/.test(ln)) continue;
|
|
121
|
+
childIndent = ln.match(/^(\s+)/)?.[1].length ?? 0;
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
if (childIndent <= 0) return '';
|
|
125
|
+
const keyRe = new RegExp(`^ {${childIndent}}${key}:\\s*["']?([A-Za-z0-9_-]+)["']?\\s*(#.*)?$`);
|
|
126
|
+
for (; i < lines.length; i++) {
|
|
127
|
+
const ln = lines[i];
|
|
128
|
+
if (ln.trim() === '' || /^\s*#/.test(ln)) continue;
|
|
129
|
+
const indent = ln.match(/^(\s+)/)?.[1].length ?? 0;
|
|
130
|
+
if (indent < childIndent) break; // dedented → block ended
|
|
131
|
+
if (indent === childIndent) {
|
|
132
|
+
const m = ln.match(keyRe);
|
|
133
|
+
if (m) return m[1];
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return '';
|
|
137
|
+
} catch {
|
|
138
|
+
return '';
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Read `agent.mode` to forward to batch_runner via --mode. batch_runner 0.0.3+
|
|
143
|
+
// also reads the nested `agent.unified.mode` itself; this forwarding is
|
|
144
|
+
// belt-and-suspenders so the flat `agent.mode` form is honored even if that read regresses.
|
|
145
|
+
function readAgentModeFromYaml(yamlPath: string): string {
|
|
146
|
+
return readYamlDirectChild(yamlPath, 'agent', 'mode');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Read `device.device_sn` so `hdc install`/`uninstall` can target a specific device
|
|
150
|
+
// (-t <sn>). Without it, bare `hdc install` fails with "need connect-key" when
|
|
151
|
+
// more than one device is connected.
|
|
152
|
+
function readDeviceSnFromYaml(yamlPath: string): string {
|
|
153
|
+
return readYamlDirectChild(yamlPath, 'device', 'device_sn');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Refresh model.unified.api_key in autotest.yaml from the HOMETRANS_MODEL_API_KEY
|
|
157
|
+
// env var if it's set and differs — so api_key rotation takes effect immediately
|
|
158
|
+
// without regenerating the yaml. Only touches the unified block (not
|
|
159
|
+
// execute/decision slots, which may carry different keys for layered mode).
|
|
160
|
+
function refreshApiKeyFromEnv(yamlPath: string): void {
|
|
161
|
+
const envKey = process.env.HOMETRANS_MODEL_API_KEY;
|
|
162
|
+
if (!envKey || envKey.includes('placeholder')) return;
|
|
163
|
+
try {
|
|
164
|
+
let text = fs.readFileSync(yamlPath, 'utf-8');
|
|
165
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
|
166
|
+
const lines = text.split(/\r?\n/);
|
|
167
|
+
let inModel = false, inUnified = false, unifiedIndent = -1, replaced = false;
|
|
168
|
+
for (let i = 0; i < lines.length; i++) {
|
|
169
|
+
const ln = lines[i];
|
|
170
|
+
if (/^model:\s*(#.*)?$/.test(ln)) { inModel = true; inUnified = false; continue; }
|
|
171
|
+
if (inModel && !/^\s/.test(ln) && ln.trim() && !/^#/.test(ln)) { inModel = false; inUnified = false; continue; }
|
|
172
|
+
if (inModel && /^\s+unified:\s*(#.*)?$/.test(ln)) { inUnified = true; unifiedIndent = (ln.match(/^(\s+)/)?.[1]?.length ?? 2) + 1; continue; }
|
|
173
|
+
if (inUnified) {
|
|
174
|
+
const indent = (ln.match(/^(\s+)/)?.[1]?.length ?? 0);
|
|
175
|
+
if (indent <= unifiedIndent - 1 && ln.trim() && !/^#/.test(ln)) { inUnified = false; continue; }
|
|
176
|
+
const m = ln.match(/^(\s+)api_key:\s*["']?([^"'\s#]+)["']?\s*(#.*)?$/);
|
|
177
|
+
if (m && m[2] !== envKey) { lines[i] = `${m[1]}api_key: "${envKey}"`; replaced = true; }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (replaced) {
|
|
181
|
+
fs.writeFileSync(yamlPath, lines.join('\n'), 'utf-8');
|
|
182
|
+
logger.info('autotest.yaml model.unified.api_key 已从 HOMETRANS_MODEL_API_KEY 环境变量刷新');
|
|
183
|
+
}
|
|
184
|
+
} catch { /* yaml read/parse failure is non-fatal — batch_runner will report config errors */ }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---- arg parsing ----
|
|
188
|
+
|
|
189
|
+
interface RunArgs {
|
|
190
|
+
testcases: string;
|
|
191
|
+
hap: string;
|
|
192
|
+
bundleName: string;
|
|
193
|
+
taskDir: string;
|
|
194
|
+
outputDir?: string;
|
|
195
|
+
category: string;
|
|
196
|
+
config?: string;
|
|
197
|
+
timeout?: number | 'auto';
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function parseRunArgs(argv: string[]): RunArgs {
|
|
201
|
+
const args: Partial<RunArgs> = { category: DEFAULT_CATEGORY, taskDir: 'task' };
|
|
202
|
+
for (let i = 0; i < argv.length; i++) {
|
|
203
|
+
const a = argv[i];
|
|
204
|
+
const next = (): string => { if (i + 1 >= argv.length) { console.error(`Missing value for ${a}`); process.exit(1); } return argv[++i]; };
|
|
205
|
+
switch (a) {
|
|
206
|
+
case '--testcases': args.testcases = next(); break;
|
|
207
|
+
case '--hap': args.hap = next(); break;
|
|
208
|
+
case '--bundle-name': args.bundleName = next(); break;
|
|
209
|
+
case '--task-dir': args.taskDir = next(); break;
|
|
210
|
+
case '--output-dir': args.outputDir = next(); break;
|
|
211
|
+
case '--category': args.category = next(); break;
|
|
212
|
+
case '--config': args.config = next(); break;
|
|
213
|
+
case '--timeout': { const v = next(); args.timeout = v === 'auto' ? 'auto' : Number(v); break; }
|
|
214
|
+
case '-h': case '--help':
|
|
215
|
+
console.log(`Usage: self-test-runner [options]
|
|
216
|
+
|
|
217
|
+
Options:
|
|
218
|
+
--testcases <path> 测试用例文件,JSON 数组或 JSONL
|
|
219
|
+
--hap <path> 签名包:单个 .hap/.hsp 文件、目录,或逗号分隔
|
|
220
|
+
--bundle-name <name> 包名
|
|
221
|
+
--task-dir <dir> 任务目录 (default: "task")
|
|
222
|
+
--output-dir <dir> 日志目录
|
|
223
|
+
--category <name> 测试分类名称 (default: "self_test")
|
|
224
|
+
--config <path> autotest.yaml 路径(默认 ~/.hometrans/autotest.yaml)
|
|
225
|
+
--timeout <sec> 阻塞直到终态或超时(秒),或 auto
|
|
226
|
+
-h, --help display this help
|
|
227
|
+
`);
|
|
228
|
+
process.exit(0);
|
|
229
|
+
default:
|
|
230
|
+
console.error(`Unknown option: ${a}`);
|
|
231
|
+
process.exit(1);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
for (const req of ['testcases', 'hap', 'bundleName'] as const) {
|
|
235
|
+
if (!args[req]) { console.error(`Missing required option: --${req.replace(/([A-Z])/g, '-$1').toLowerCase()}`); process.exit(1); }
|
|
236
|
+
}
|
|
237
|
+
return args as RunArgs;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---- HAP install ----
|
|
241
|
+
|
|
242
|
+
function runCmd(cmd: string[], opts: { check?: boolean; timeout?: number } = {}): { returncode: number; stdout: string; stderr: string } {
|
|
243
|
+
const { check = true, timeout } = opts;
|
|
244
|
+
logger.info(`>>> ${cmd.join(' ')}`);
|
|
245
|
+
const result = spawnSync(cmd[0], cmd.slice(1), {
|
|
246
|
+
encoding: 'utf-8',
|
|
247
|
+
timeout: timeout ? timeout * 1000 : undefined,
|
|
248
|
+
maxBuffer: 1024 * 1024 * 1024,
|
|
249
|
+
windowsHide: true,
|
|
250
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
251
|
+
});
|
|
252
|
+
if (result.error) { logger.error(`命令异常: ${result.error.message}`); throw result.error; }
|
|
253
|
+
const status = result.status ?? 0;
|
|
254
|
+
if (status !== 0) {
|
|
255
|
+
logger.warning(`退出码=${status}`);
|
|
256
|
+
if (result.stdout) logger.warning(` stdout: ${result.stdout.trim()}`);
|
|
257
|
+
if (result.stderr) logger.warning(` stderr: ${result.stderr.trim()}`);
|
|
258
|
+
if (check) process.exit(status);
|
|
259
|
+
}
|
|
260
|
+
return { returncode: status, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function installHaps(hapArg: string, hdcCmd: string[]): void {
|
|
264
|
+
const entries = hapArg.split(',').map((s) => s.trim()).filter(Boolean);
|
|
265
|
+
if (entries.length === 0) { logger.error('hap-path 为空'); process.exit(1); }
|
|
266
|
+
const pkgs: string[] = [];
|
|
267
|
+
for (const e of entries) {
|
|
268
|
+
if (!fs.existsSync(e)) { logger.error(`hap 路径不存在: ${e}`); process.exit(1); }
|
|
269
|
+
const stat = fs.statSync(e);
|
|
270
|
+
const lower = e.toLowerCase();
|
|
271
|
+
if (stat.isDirectory()) {
|
|
272
|
+
const found = fs.readdirSync(e).filter((f) => f.toLowerCase().endsWith('.hap') || f.toLowerCase().endsWith('.hsp')).sort().map((f) => path.join(e, f));
|
|
273
|
+
if (found.length === 0) { logger.error(`目录内无 .hap/.hsp 包: ${e}`); process.exit(1); }
|
|
274
|
+
pkgs.push(...found);
|
|
275
|
+
} else if (lower.endsWith('.hap') || lower.endsWith('.hsp')) {
|
|
276
|
+
pkgs.push(e);
|
|
277
|
+
} else {
|
|
278
|
+
logger.error(`既不是目录也不是 .hap/.hsp 文件: ${e}`); process.exit(1);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const seen = new Set<string>();
|
|
282
|
+
const deduped = pkgs.map((p) => path.resolve(p)).filter((p) => (seen.has(p) ? false : (seen.add(p), true)));
|
|
283
|
+
if (!deduped.some((p) => p.toLowerCase().endsWith('.hap'))) { logger.error(`缺少 entry HAP: ${hapArg}`); process.exit(1); }
|
|
284
|
+
|
|
285
|
+
logger.info(`安装 ${deduped.length} 个包: ${deduped.map((p) => path.basename(p)).join(', ')}`);
|
|
286
|
+
const result = runCmd([...hdcCmd, 'install', '-r', ...deduped], { timeout: INSTALL_TIMEOUT, check: false });
|
|
287
|
+
const combined = `${result.stdout.trim()}\n${result.stderr.trim()}`;
|
|
288
|
+
const combinedLower = combined.toLowerCase();
|
|
289
|
+
const hasError = combined.includes('msg:error') || combinedLower.includes('failed to install') || (combined.includes('code:') && combinedLower.includes('error:'));
|
|
290
|
+
const hasSuccess = combinedLower.includes('successfully');
|
|
291
|
+
if (result.returncode === 0 && !hasError && hasSuccess) { logger.info('安装成功'); sleep(HAP_INSTALL_WAIT); }
|
|
292
|
+
else if (result.returncode === 0 && !hasError) { logger.warning(`安装结果不确定: ${combined}`); sleep(HAP_INSTALL_WAIT); }
|
|
293
|
+
else { logger.error(`安装失败: rc=${result.returncode}, output=${combined}`); process.exit(1); }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ---- testcases JSONL normalizer ----
|
|
297
|
+
|
|
298
|
+
function prepareTestcasesJsonl(inputPath: string, taskSubdir: string): string {
|
|
299
|
+
if (!fs.existsSync(inputPath)) { logger.error(`测试用例文件不存在: ${inputPath}`); process.exit(1); }
|
|
300
|
+
let text = fs.readFileSync(inputPath, 'utf-8');
|
|
301
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
|
302
|
+
const stripped = text.trimStart();
|
|
303
|
+
if (!stripped) { logger.error(`测试用例文件为空: ${inputPath}`); process.exit(1); }
|
|
304
|
+
|
|
305
|
+
if (stripped[0] === '[') {
|
|
306
|
+
let arr: unknown;
|
|
307
|
+
try { arr = JSON.parse(text); } catch (e) { logger.error(`JSON 解析失败: ${e}`); process.exit(1); }
|
|
308
|
+
if (!Array.isArray(arr)) { logger.error('根不是数组'); process.exit(1); }
|
|
309
|
+
const outPath = path.join(taskSubdir, 'testcases.jsonl');
|
|
310
|
+
const { createHash } = crypto;
|
|
311
|
+
const lines = arr.map((entry: any, idx: number) => {
|
|
312
|
+
if (!entry || typeof entry !== 'object') { logger.error(`用例 #${idx + 1} 不是 JSON 对象`); process.exit(1); }
|
|
313
|
+
if (!entry.uuid) {
|
|
314
|
+
const seed = typeof entry.case_name === 'string' && entry.case_name ? entry.case_name : `case_${idx + 1}`;
|
|
315
|
+
entry.uuid = createHash('md5').update(seed, 'utf-8').digest('hex').slice(0, 8);
|
|
316
|
+
}
|
|
317
|
+
if (!('spec' in entry)) entry.spec = '';
|
|
318
|
+
return JSON.stringify(entry);
|
|
319
|
+
});
|
|
320
|
+
fs.writeFileSync(outPath, lines.join('\n') + '\n', 'utf-8');
|
|
321
|
+
logger.info(`已将 JSON 数组转换为 JSONL: ${outPath}(${arr.length} 条用例)`);
|
|
322
|
+
return outPath;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const lines = text.split(/\r?\n/).filter((l) => l.trim());
|
|
326
|
+
lines.forEach((line, i) => {
|
|
327
|
+
try { JSON.parse(line); } catch (e) { logger.error(`JSONL 第 ${i + 1} 行解析失败: ${e}`); process.exit(1); }
|
|
328
|
+
});
|
|
329
|
+
logger.info(`测试用例文件已为 JSONL: ${inputPath}(${lines.length} 条用例)`);
|
|
330
|
+
return inputPath;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---- batch runner path ----
|
|
334
|
+
|
|
335
|
+
// Resolve the global npm root(s) where `npm install -g` places packages.
|
|
336
|
+
// Used as a fallback when the script runs from a location with no
|
|
337
|
+
// node_modules ancestor (e.g. the opencode skill dir), so the skill's own
|
|
338
|
+
// self-test-runner.ts can still locate @autotest/agent installed globally
|
|
339
|
+
// as a dependency of @buaa_smat/hometrans.
|
|
340
|
+
let _globalRootsCache: string[] | null = null;
|
|
341
|
+
function globalNodeModulesRoots(): string[] {
|
|
342
|
+
if (_globalRootsCache) return _globalRootsCache;
|
|
343
|
+
const roots = new Set<string>();
|
|
344
|
+
// `npm root -g` is the most reliable source.
|
|
345
|
+
try {
|
|
346
|
+
const out = execFileSync('npm', ['root', '-g'], { encoding: 'utf-8', timeout: 15000, windowsHide: true });
|
|
347
|
+
const p = out.trim();
|
|
348
|
+
if (p) roots.add(p);
|
|
349
|
+
} catch { /* npm not on PATH or timed out */ }
|
|
350
|
+
// Heuristic fallbacks (cross-platform) in case `npm root -g` is unavailable.
|
|
351
|
+
const home = os.homedir();
|
|
352
|
+
if (process.platform === 'win32') {
|
|
353
|
+
if (process.env.APPDATA) roots.add(path.join(process.env.APPDATA, 'npm', 'node_modules'));
|
|
354
|
+
} else {
|
|
355
|
+
roots.add('/usr/local/lib/node_modules');
|
|
356
|
+
roots.add('/usr/lib/node_modules');
|
|
357
|
+
roots.add(path.join(home, '.npm-global', 'lib', 'node_modules'));
|
|
358
|
+
roots.add(path.join(home, '.npm', 'lib', 'node_modules'));
|
|
359
|
+
}
|
|
360
|
+
_globalRootsCache = [...roots].filter((r) => r);
|
|
361
|
+
return _globalRootsCache;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function batchRunnerPath(): string {
|
|
365
|
+
const rel = path.join('@autotest', 'agent', 'dist', 'tools', 'batch_runner.js');
|
|
366
|
+
// 1. Walk up from the script's own location (works when the script lives
|
|
367
|
+
// inside a project that has @autotest/agent in its node_modules tree,
|
|
368
|
+
// e.g. the HomeTrans repo during development).
|
|
369
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
370
|
+
let dir = here;
|
|
371
|
+
for (let i = 0; i < 20 && dir; i++) {
|
|
372
|
+
const candidate = path.join(dir, 'node_modules', rel);
|
|
373
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
374
|
+
const parent = path.dirname(dir);
|
|
375
|
+
if (parent === dir) break;
|
|
376
|
+
dir = parent;
|
|
377
|
+
}
|
|
378
|
+
// 2. Fallback: global npm root. @autotest/agent is either hoisted to the
|
|
379
|
+
// global root itself, or nested under the globally-installed
|
|
380
|
+
// @buaa_smat/hometrans package.
|
|
381
|
+
for (const root of globalNodeModulesRoots()) {
|
|
382
|
+
const hoisted = path.join(root, rel);
|
|
383
|
+
if (fs.existsSync(hoisted)) return hoisted;
|
|
384
|
+
const nested = path.join(root, '@buaa_smat', 'hometrans', 'node_modules', rel);
|
|
385
|
+
if (fs.existsSync(nested)) return nested;
|
|
386
|
+
}
|
|
387
|
+
return '';
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Locate the @buaa_smat/hometrans package.json (repo dev copy or installed
|
|
391
|
+
// copy, local or global) so we can read the exact @autotest/agent version
|
|
392
|
+
// hometrans depends on — auto-install then pins that version instead of
|
|
393
|
+
// "latest" (which could pull a version without the required fixes).
|
|
394
|
+
function findHometransPackageJson(): string | null {
|
|
395
|
+
const tryRead = (p: string): string | null => {
|
|
396
|
+
if (!fs.existsSync(p)) return null;
|
|
397
|
+
try {
|
|
398
|
+
const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
|
|
399
|
+
if (pkg && pkg.name === '@buaa_smat/hometrans') return p;
|
|
400
|
+
} catch { /* not a valid package.json */ }
|
|
401
|
+
return null;
|
|
402
|
+
};
|
|
403
|
+
// 1. repo dev context: walk up from the script dir; the repo root itself is
|
|
404
|
+
// the hometrans package.
|
|
405
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
406
|
+
let dir = here;
|
|
407
|
+
for (let i = 0; i < 20 && dir; i++) {
|
|
408
|
+
const self = tryRead(path.join(dir, 'package.json'));
|
|
409
|
+
if (self) return self;
|
|
410
|
+
const nested = tryRead(path.join(dir, 'node_modules', '@buaa_smat', 'hometrans', 'package.json'));
|
|
411
|
+
if (nested) return nested;
|
|
412
|
+
const parent = path.dirname(dir);
|
|
413
|
+
if (parent === dir) break;
|
|
414
|
+
dir = parent;
|
|
415
|
+
}
|
|
416
|
+
// 2. global npm root: <root>/@buaa_smat/hometrans/package.json
|
|
417
|
+
for (const root of globalNodeModulesRoots()) {
|
|
418
|
+
const g = tryRead(path.join(root, '@buaa_smat', 'hometrans', 'package.json'));
|
|
419
|
+
if (g) return g;
|
|
420
|
+
}
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Ensure @autotest/agent's batch_runner.js is findable. If batchRunnerPath()
|
|
425
|
+
// cannot locate it, auto-install @autotest/agent (pinned to the version
|
|
426
|
+
// hometrans depends on) and retry. This self-heals the common "forgot to
|
|
427
|
+
// install / hometrans install didn't pull the dep" case so the skill doesn't
|
|
428
|
+
// hard-fail on a missing agent.
|
|
429
|
+
function ensureAutotestAgent(): string {
|
|
430
|
+
const found = batchRunnerPath();
|
|
431
|
+
if (found) return found;
|
|
432
|
+
|
|
433
|
+
// Resolve the required version from hometrans's package.json.
|
|
434
|
+
let versionSpec = '';
|
|
435
|
+
const hometransPkg = findHometransPackageJson();
|
|
436
|
+
if (hometransPkg) {
|
|
437
|
+
try {
|
|
438
|
+
const deps = JSON.parse(fs.readFileSync(hometransPkg, 'utf-8')).dependencies || {};
|
|
439
|
+
versionSpec = (deps['@autotest/agent'] || '').trim();
|
|
440
|
+
} catch { /* ignore */ }
|
|
441
|
+
}
|
|
442
|
+
const installSpec = versionSpec ? `@autotest/agent@${versionSpec}` : '@autotest/agent';
|
|
443
|
+
logger.info(`@autotest/agent 未找到,尝试自动安装: npm install -g ${installSpec}`);
|
|
444
|
+
|
|
445
|
+
let installOk = false;
|
|
446
|
+
try {
|
|
447
|
+
const result = spawnSync('npm', ['install', '-g', installSpec], {
|
|
448
|
+
encoding: 'utf-8', timeout: 180000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
|
|
449
|
+
});
|
|
450
|
+
installOk = result.status === 0;
|
|
451
|
+
if (!installOk) {
|
|
452
|
+
const tail = ((result.stderr || '') + (result.stdout || '')).trim().slice(-400);
|
|
453
|
+
logger.warning(`自动安装退出码=${result.status}: ${tail}`);
|
|
454
|
+
}
|
|
455
|
+
} catch (e) {
|
|
456
|
+
logger.warning(`自动安装异常: ${e instanceof Error ? e.message : String(e)}`);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// npm install may have changed the global root layout; drop the cache and retry.
|
|
460
|
+
_globalRootsCache = null;
|
|
461
|
+
const retry = batchRunnerPath();
|
|
462
|
+
if (retry) {
|
|
463
|
+
logger.info(`@autotest/agent 自动安装成功 → ${retry}`);
|
|
464
|
+
return retry;
|
|
465
|
+
}
|
|
466
|
+
if (!installOk) {
|
|
467
|
+
logger.error(
|
|
468
|
+
`自动安装失败。@autotest/agent${versionSpec ? `@${versionSpec}` : ''} 可能未发布到 npm。` +
|
|
469
|
+
`请手动安装对应 tarball:\`npm install -g <autotest-agent-tarball.tgz>\`,` +
|
|
470
|
+
`或重装 hometrans:\`npm install -g @buaa_smat/hometrans\`。`,
|
|
471
|
+
);
|
|
472
|
+
} else {
|
|
473
|
+
logger.error('自动安装报告成功但 batch_runner.js 仍未找到;请检查 npm 全局目录权限或路径。');
|
|
474
|
+
}
|
|
475
|
+
return '';
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ---- status probe ----
|
|
479
|
+
|
|
480
|
+
function findTaskSubdir(taskDir: string): string | null {
|
|
481
|
+
if (!fs.existsSync(taskDir)) return null;
|
|
482
|
+
try {
|
|
483
|
+
const candidates = fs.readdirSync(taskDir, { withFileTypes: true }).filter((e) => e.isDirectory() && e.name.startsWith('task_')).map((e) => e.name).sort().reverse();
|
|
484
|
+
return candidates.length ? path.join(taskDir, candidates[0]) : null;
|
|
485
|
+
} catch { return null; }
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function findLatestLog(outputDir: string): string | null {
|
|
489
|
+
if (!fs.existsSync(outputDir)) return null;
|
|
490
|
+
try {
|
|
491
|
+
const entries = fs.readdirSync(outputDir, { withFileTypes: true });
|
|
492
|
+
const selfTest = entries.filter((e) => e.isFile() && e.name.startsWith('self_test_') && e.name.endsWith('.log')).map((e) => e.name).sort().reverse();
|
|
493
|
+
const batchLog = entries.filter((e) => e.isFile() && e.name === 'batch_stdout.log').map((e) => e.name);
|
|
494
|
+
const ordered = [...selfTest, ...batchLog];
|
|
495
|
+
return ordered.length ? path.join(outputDir, ordered[0]) : null;
|
|
496
|
+
} catch { return null; }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function probeStatus(taskDir: string, outputDir: string): { status: string; taskSubdir: string | null; casesDone: number; lastCase: string; logTail: string; passCount?: number; failCount?: number; unknownCount?: number; passRate?: string | number } {
|
|
500
|
+
const taskSubdir = findTaskSubdir(taskDir);
|
|
501
|
+
if (!taskSubdir) return { status: 'NOT_STARTED', taskSubdir: null, casesDone: 0, lastCase: '', logTail: '' };
|
|
502
|
+
|
|
503
|
+
let casesDone = 0;
|
|
504
|
+
let lastCase = '';
|
|
505
|
+
const jsonlFile = path.join(taskSubdir, 'task_results.jsonl');
|
|
506
|
+
if (fs.existsSync(jsonlFile)) {
|
|
507
|
+
const text = fs.readFileSync(jsonlFile, 'utf-8').trim();
|
|
508
|
+
const lines = text ? text.split(/\r?\n/) : [];
|
|
509
|
+
casesDone = lines.length;
|
|
510
|
+
if (lines.length) {
|
|
511
|
+
try { const last = JSON.parse(lines[lines.length - 1]); if (typeof last.case_name === 'string') lastCase = last.case_name; } catch { }
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
let logTail = '';
|
|
516
|
+
const logFile = findLatestLog(outputDir);
|
|
517
|
+
if (logFile && fs.existsSync(logFile)) {
|
|
518
|
+
const text = fs.readFileSync(logFile, 'utf-8').trim();
|
|
519
|
+
logTail = (text ? text.split(/\r?\n/) : []).slice(-5).join('\n');
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const summaryFile = path.join(taskSubdir, 'summary.json');
|
|
523
|
+
if (fs.existsSync(summaryFile)) {
|
|
524
|
+
let summary: Record<string, unknown> = {};
|
|
525
|
+
try { summary = JSON.parse(fs.readFileSync(summaryFile, 'utf-8')); } catch { }
|
|
526
|
+
const num = (v: unknown, f: number) => (typeof v === 'number' ? v : f);
|
|
527
|
+
return {
|
|
528
|
+
status: 'COMPLETED', taskSubdir, casesDone: num(summary.total_cases, casesDone), lastCase,
|
|
529
|
+
passCount: num(summary.pass_count, 0), failCount: num(summary.fail_count, 0),
|
|
530
|
+
unknownCount: num(summary.unknown_count, 0), passRate: (summary.pass_rate as string | number | undefined) ?? 0, logTail,
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
return { status: 'RUNNING', taskSubdir, casesDone, lastCase, logTail };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ---- run command ----
|
|
538
|
+
|
|
539
|
+
async function cmdRun(args: RunArgs): Promise<void> {
|
|
540
|
+
const taskDir = path.resolve(args.taskDir);
|
|
541
|
+
fs.mkdirSync(taskDir, { recursive: true });
|
|
542
|
+
const outputDir = args.outputDir ? path.resolve(args.outputDir) : taskDir;
|
|
543
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
544
|
+
|
|
545
|
+
setupLogging(outputDir);
|
|
546
|
+
logger.info(`参数: testcases=${args.testcases}, hap=${args.hap}, bundle=${args.bundleName}, config=${args.config ?? '(default)'}`);
|
|
547
|
+
|
|
548
|
+
const taskSubdir = path.join(taskDir, `task_${timestampForFile(new Date())}`);
|
|
549
|
+
fs.mkdirSync(taskSubdir, { recursive: true });
|
|
550
|
+
const stdoutLog = path.join(taskDir, 'batch_stdout.log');
|
|
551
|
+
|
|
552
|
+
// Resolve autotest.yaml
|
|
553
|
+
const configPath = args.config || path.join(os.homedir(), '.hometrans', 'autotest.yaml');
|
|
554
|
+
if (!fs.existsSync(configPath)) {
|
|
555
|
+
logger.error(`autotest.yaml not found: ${configPath}`);
|
|
556
|
+
console.log(JSON.stringify({ status: 'FAILED', error: `autotest.yaml not found: ${configPath}` }));
|
|
557
|
+
process.exit(1);
|
|
558
|
+
}
|
|
559
|
+
logger.info(`Config: ${configPath}`);
|
|
560
|
+
|
|
561
|
+
// Read agent.mode from autotest.yaml and forward it to batch_runner via
|
|
562
|
+
// --mode. Without this, batch_runner (<= 0.0.2) defaults to "single" even
|
|
563
|
+
// when the yaml says "layered", so Planner+Executor never activates.
|
|
564
|
+
const agentMode = readAgentModeFromYaml(configPath);
|
|
565
|
+
if (agentMode) logger.info(`autotest.yaml agent.mode = "${agentMode}" → --mode ${agentMode}`);
|
|
566
|
+
else logger.info('autotest.yaml agent.mode not set → batch_runner defaults to "single"');
|
|
567
|
+
|
|
568
|
+
// HAP install/uninstall
|
|
569
|
+
const hdc = getHdc();
|
|
570
|
+
// Read device_sn from autotest.yaml so hdc install/uninstall can target a
|
|
571
|
+
// specific device (-t <sn>). Without it, bare `hdc install` fails with
|
|
572
|
+
// "need connect-key" when ≥2 devices are connected — and worse, install could
|
|
573
|
+
// land on device A while batch_runner auto-detects device B, testing the
|
|
574
|
+
// wrong (stale) app. So when device_sn is unset AND ≥2 devices are connected,
|
|
575
|
+
// fail fast and tell the user to pin a device in autotest.yaml. With exactly
|
|
576
|
+
// one device, bare hdc auto-detects it correctly.
|
|
577
|
+
const deviceSn = readDeviceSnFromYaml(configPath);
|
|
578
|
+
let hdcCmd: string[];
|
|
579
|
+
if (deviceSn) {
|
|
580
|
+
hdcCmd = [hdc, '-t', deviceSn];
|
|
581
|
+
logger.info(`autotest.yaml device.device_sn = "${deviceSn}" → hdc -t ${deviceSn}`);
|
|
582
|
+
} else {
|
|
583
|
+
const targets = runCmd([hdc, 'list', 'targets'], { check: false, timeout: 15 }).stdout
|
|
584
|
+
.split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !/^\[|empty/i.test(s));
|
|
585
|
+
if (targets.length > 1) {
|
|
586
|
+
logger.error(
|
|
587
|
+
`autotest.yaml 未设 device.device_sn,但连了 ${targets.length} 台设备(${targets.join(', ')})。` +
|
|
588
|
+
`请在 ~/.hometrans/autotest.yaml 的 device.device_sn 指定目标设备,` +
|
|
589
|
+
`避免 install 与 batch_runner 跑在不同设备上。`,
|
|
590
|
+
);
|
|
591
|
+
console.log(JSON.stringify({
|
|
592
|
+
status: 'FAILED',
|
|
593
|
+
error: `device.device_sn not set in autotest.yaml; ${targets.length} devices connected (${targets.join(', ')}); set device.device_sn to pin the target`,
|
|
594
|
+
}));
|
|
595
|
+
process.exit(1);
|
|
596
|
+
}
|
|
597
|
+
hdcCmd = [hdc];
|
|
598
|
+
logger.info(`autotest.yaml device.device_sn not set; ${targets.length} device(s) connected → hdc auto-detect`);
|
|
599
|
+
}
|
|
600
|
+
logger.info(`=== Step 2a: uninstall ${args.bundleName} ===`);
|
|
601
|
+
runCmd([...hdcCmd, 'uninstall', args.bundleName], { timeout: INSTALL_TIMEOUT, check: false });
|
|
602
|
+
logger.info(`=== Step 2b: install ${args.hap} ===`);
|
|
603
|
+
installHaps(args.hap, hdcCmd);
|
|
604
|
+
|
|
605
|
+
// Prepare testcases
|
|
606
|
+
const testcasesJsonl = prepareTestcasesJsonl(path.resolve(args.testcases), taskSubdir);
|
|
607
|
+
|
|
608
|
+
// Resolve timeout
|
|
609
|
+
let effectiveTimeout: number | undefined;
|
|
610
|
+
if (args.timeout === 'auto') {
|
|
611
|
+
const caseCount = fs.readFileSync(testcasesJsonl, 'utf-8').split(/\r?\n/).filter((l) => l.trim()).length;
|
|
612
|
+
effectiveTimeout = Math.max(caseCount, 1) * PER_CASE_TIMEOUT_SEC;
|
|
613
|
+
logger.info(`--timeout auto: ${caseCount} 条用例 × ${PER_CASE_TIMEOUT_SEC}s = ${effectiveTimeout}s`);
|
|
614
|
+
} else if (args.timeout && typeof args.timeout === 'number') {
|
|
615
|
+
effectiveTimeout = args.timeout;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Refresh model.unified.api_key from HOMETRANS_MODEL_API_KEY env if it has
|
|
619
|
+
// been rotated since the yaml was last generated (Step 0a skips regeneration
|
|
620
|
+
// when the yaml exists, so without this the env var rotation would be silently
|
|
621
|
+
// ignored).
|
|
622
|
+
refreshApiKeyFromEnv(configPath);
|
|
623
|
+
|
|
624
|
+
// Build batch command — ensure @autotest/agent is installed (auto-install if missing)
|
|
625
|
+
const runnerJs = ensureAutotestAgent();
|
|
626
|
+
if (!runnerJs) {
|
|
627
|
+
logger.error('batch_runner.js not found and auto-install failed (see warnings above)');
|
|
628
|
+
console.log(JSON.stringify({ status: 'FAILED', error: 'batch_runner.js not found; @autotest/agent auto-install failed' }));
|
|
629
|
+
process.exit(1);
|
|
630
|
+
}
|
|
631
|
+
const cmd = ['node', runnerJs, '--task-dir', taskSubdir, '--testcases', testcasesJsonl, '--category', args.category, '--config', configPath];
|
|
632
|
+
if (agentMode) cmd.push('--mode', agentMode);
|
|
633
|
+
|
|
634
|
+
logger.info('=== Step 3: 启动 AutoTest batch_runner ===');
|
|
635
|
+
|
|
636
|
+
// Spawn detached and poll
|
|
637
|
+
const logFd = fs.openSync(stdoutLog, 'w');
|
|
638
|
+
const proc = spawn(cmd[0], cmd.slice(1), {
|
|
639
|
+
cwd: taskSubdir,
|
|
640
|
+
stdio: ['ignore', logFd, logFd],
|
|
641
|
+
env: process.env,
|
|
642
|
+
detached: true,
|
|
643
|
+
windowsHide: true,
|
|
644
|
+
});
|
|
645
|
+
proc.unref();
|
|
646
|
+
logger.info(`后台进程 PID=${proc.pid}`);
|
|
647
|
+
fs.closeSync(logFd);
|
|
648
|
+
|
|
649
|
+
// No timeout: return immediately
|
|
650
|
+
if (!effectiveTimeout) {
|
|
651
|
+
console.log(JSON.stringify({ status: 'RUNNING', pid: proc.pid, task_dir: taskDir, task_subdir: taskSubdir }));
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Poll until terminal
|
|
656
|
+
const start = Date.now();
|
|
657
|
+
while (true) {
|
|
658
|
+
const r = probeStatus(taskDir, outputDir);
|
|
659
|
+
|
|
660
|
+
if (r.status === 'COMPLETED') {
|
|
661
|
+
console.log(JSON.stringify({
|
|
662
|
+
status: 'COMPLETED', task_subdir: r.taskSubdir, cases_done: r.casesDone,
|
|
663
|
+
pass_count: r.passCount ?? 0, fail_count: r.failCount ?? 0, unknown_count: r.unknownCount ?? 0,
|
|
664
|
+
pass_rate: r.passRate ?? 0, log_tail: r.logTail,
|
|
665
|
+
}));
|
|
666
|
+
process.exit(0);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// CRASHED detection: batch process died without producing summary.json.
|
|
670
|
+
// Without this, a spawn-time crash (ConfigManager error, missing dep, JS
|
|
671
|
+
// exception) would be misreported as TIMEOUT after waiting the full budget.
|
|
672
|
+
const procAlive = isProcessAlive(proc.pid);
|
|
673
|
+
if (!procAlive) {
|
|
674
|
+
logger.error(`batch_runner 进程 PID=${proc.pid} 已退出但无 summary.json → CRASHED`);
|
|
675
|
+
console.log(JSON.stringify({
|
|
676
|
+
status: 'CRASHED', task_subdir: r.taskSubdir, cases_done: r.casesDone,
|
|
677
|
+
last_case: r.lastCase, log_tail: r.logTail,
|
|
678
|
+
}));
|
|
679
|
+
process.exit(3);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const elapsed = (Date.now() - start) / 1000;
|
|
683
|
+
if (elapsed >= effectiveTimeout) {
|
|
684
|
+
killProcessTree(proc.pid);
|
|
685
|
+
console.log(JSON.stringify({
|
|
686
|
+
status: 'TIMEOUT', task_subdir: r.taskSubdir, cases_done: r.casesDone,
|
|
687
|
+
last_case: r.lastCase, log_tail: r.logTail,
|
|
688
|
+
}));
|
|
689
|
+
process.exit(5);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
sleep(60);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// ---- status command ----
|
|
697
|
+
|
|
698
|
+
function cmdStatus(taskDir: string, outputDir?: string): void {
|
|
699
|
+
const r = probeStatus(path.resolve(taskDir), outputDir ? path.resolve(outputDir) : path.resolve(taskDir));
|
|
700
|
+
if (r.status === 'NOT_STARTED') { console.log(JSON.stringify({ status: 'NOT_STARTED' })); process.exit(4); }
|
|
701
|
+
if (r.status === 'COMPLETED') {
|
|
702
|
+
console.log(JSON.stringify({
|
|
703
|
+
status: 'COMPLETED', task_subdir: r.taskSubdir, cases_done: r.casesDone,
|
|
704
|
+
pass_count: r.passCount ?? 0, fail_count: r.failCount ?? 0, unknown_count: r.unknownCount ?? 0,
|
|
705
|
+
pass_rate: r.passRate ?? 0, log_tail: r.logTail,
|
|
706
|
+
}));
|
|
707
|
+
process.exit(0);
|
|
708
|
+
}
|
|
709
|
+
console.log(JSON.stringify({ status: r.status, cases_done: r.casesDone, last_case: r.lastCase, task_subdir: r.taskSubdir, log_tail: r.logTail }));
|
|
710
|
+
process.exit(r.status === 'RUNNING' ? 2 : 3);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// ---- entry ----
|
|
714
|
+
|
|
715
|
+
const args = process.argv.slice(2);
|
|
716
|
+
|
|
717
|
+
// Parse args: --status flag switches to status mode, otherwise run mode
|
|
718
|
+
const isStatus = args.includes('--status');
|
|
719
|
+
const filtered = args.filter((a) => a !== '--status');
|
|
720
|
+
|
|
721
|
+
if (filtered.includes('-h') || filtered.includes('--help')) {
|
|
722
|
+
if (isStatus) {
|
|
723
|
+
console.log('Usage: self-test-runner --status --task-dir <dir> [--output-dir <dir>]');
|
|
724
|
+
} else {
|
|
725
|
+
console.log(`Usage: self-test-runner [options]
|
|
726
|
+
|
|
727
|
+
Options:
|
|
728
|
+
--testcases <path> 测试用例文件,JSON 数组或 JSONL
|
|
729
|
+
--hap <path> 签名包:单个 .hap/.hsp 文件、目录,或逗号分隔
|
|
730
|
+
--bundle-name <name> 包名
|
|
731
|
+
--task-dir <dir> 任务目录 (default: "task")
|
|
732
|
+
--output-dir <dir> 日志目录
|
|
733
|
+
--category <name> 测试分类名称 (default: "self_test")
|
|
734
|
+
--config <path> autotest.yaml 路径(默认 ~/.hometrans/autotest.yaml)
|
|
735
|
+
--timeout <sec> 阻塞直到终态或超时(秒),或 auto
|
|
736
|
+
--status 查询执行状态(而非运行)
|
|
737
|
+
-h, --help display this help
|
|
738
|
+
`);
|
|
739
|
+
}
|
|
740
|
+
process.exit(0);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
if (isStatus) {
|
|
744
|
+
// Status mode: only need --task-dir and --output-dir
|
|
745
|
+
let taskDir = '';
|
|
746
|
+
let outputDir: string | undefined;
|
|
747
|
+
for (let i = 0; i < filtered.length; i++) {
|
|
748
|
+
if (filtered[i] === '--task-dir') taskDir = filtered[++i];
|
|
749
|
+
else if (filtered[i] === '--output-dir') outputDir = filtered[++i];
|
|
750
|
+
}
|
|
751
|
+
if (!taskDir) { console.error('Missing required option: --task-dir'); process.exit(1); }
|
|
752
|
+
cmdStatus(taskDir, outputDir);
|
|
753
|
+
} else {
|
|
754
|
+
// Run mode (default)
|
|
755
|
+
cmdRun(parseRunArgs(filtered));
|
|
756
|
+
}
|