12 模块多 agent 并行开发(dev+test+fix 每,两层 + barrier):
- T06 PbaSession 事件溯源 + deriveMessages + logged 不变量
- T07 PbaEventBus typed event bus + waterfall + ScopeKey 隔离
- T08 能力接缝三角色(board-link + flash Provider/Registry/consumer)
- T09 compaction 完整工程(token-meter/pruner/summarizer/spill)
- T10 CI 质量门 + snapshot + doc-sync
- T11 类型镜像漂移检测(tsconfig.realpi + type-drift-check)
- T12 子代理 + 工作流编排(parallel/pipeline/InlineSubagentProvider)
- T13 上下文注入三段(inject/steer/followup)
- T14 plan/goal/todo checkpoint logged state(look-ahead 状态机)
- T15 profile/bundle 分层(维修诊断 vs 嵌入式开发,共享 base)
- T16 多 LLM provider 适配(ProviderRegistry + glm-5.2/deepseek)
- T17 审批接缝(fail-closed auto-deny)+ credentials/settings/lsp
集成(串行):
- src/index.ts 公共 re-export(board-link/flash 具名避 shared/types 重名)
- tests/system-integration.test.ts 跨模块 10 闭环(事件溯源→compaction→bus→
接缝→checkpoint→inject→workflow→approval→provider→profile)
- 全量 tsc=0;vitest 39 文件 2449 passed/5 skipped(1044 baseline +~1400 模块 + 10 系统)
- 密钥铁律:\${DROBOTICS_LLM_KEY} 占位,grep sk- 明文 0
68 workflow agent / 0 error / ~3M token;mutation 测试每模块 3-9 seeded bug 全杀。
Co-Authored-By: Claude <noreply@anthropic.com>
2524 lines
106 KiB
TypeScript
2524 lines
106 KiB
TypeScript
/**
|
||
* @module tests/capability-seams
|
||
*
|
||
* T08 能力接缝三角色(board-link + flash)完整测试套件。
|
||
*
|
||
* 被测对象(按契约直 import 命名导出):
|
||
* - board-link: BoardLinkRegistry / DEFAULT_BOARD_LINK_PROVIDERS /
|
||
* RDK_X5_SSH_PROVIDER / RDK_S100_SERIAL_PROVIDER / LOCAL_PROVIDER /
|
||
* parseSshAddress / buildSshArgs / parseSerialAddress / SERIAL_STUB_RESULT /
|
||
* defaultBoardHealthCheck
|
||
* - flash: FlashRegistry / DEFAULT_FLASH_PROVIDERS / DD_PROVIDER / FASTBOOT_PROVIDER /
|
||
* DFU_PROVIDER / OPENOCD_PROVIDER / parseOffset / parseLsblk / deviceBasename /
|
||
* matchesDeviceName / isRootDiskTarget / targetExistsInRows / splitCommand /
|
||
* orchestrateRun / probeDryRun / exitCodeVerify / DD_BLOCK_SIZE / ROOT_MOUNTPOINTS
|
||
*
|
||
* 多测试方法论(每个 describe 块标题标注方法论名):
|
||
* - 等价类划分(有效/无效/边界类)
|
||
* - 边界值分析(off-by-one、空、单元素、max、min)
|
||
* - 决策表(组合输入→期望,覆盖全分支)
|
||
* - 状态转换(register→resolve→dispose→resolve 不可达;重入/再注册)
|
||
* - 变异测试(7 个 seeded bug 内联副本,每个被某条真实测试杀死;
|
||
* kill verification:每个 mutant 通过真实断言确认 FAIL)
|
||
* - 对抗/fuzz(空串/undefined/null/巨大数/畸形引号/并发重入/负 seq/NaN)
|
||
* - 元蜕变/不变式(快照独立性、freeze→篡改抛 TypeError、单调 deny、
|
||
* waterfall 写失败短路=不调 next、fail-closed unusable=拒)
|
||
*
|
||
* mock 注入 ExecFn(scriptedExec / mockExec),无 pi 运行时、无真实硬件、无网络。
|
||
*
|
||
* 变异测试方法论说明:
|
||
* 每个 mutant 是真实逻辑的"单点变异"内联副本。我们对每个 mutant 做两层验证:
|
||
* ① 偏离验证:断言 mutant 输出 ≠ 真实输出(mutant 确实改变了行为)
|
||
* ② kill verification:把 mutant 喂给与真实代码完全相同的断言(expect(...).toBe(...)),
|
||
* 断言该断言抛错(即 mutant 在真实测试下 FAIL → bug 被杀)。
|
||
* 套件本身保持全绿(mutant 测试断言 mutant 确实偏离/确实 FAIL,而非断言 mutant 对)。
|
||
* 每个 mutant 标注:变异点 + 杀它的真实测试名。
|
||
*/
|
||
|
||
import { describe, it, expect, vi } from "vitest";
|
||
import { createHash } from "node:crypto";
|
||
|
||
import {
|
||
BoardLinkRegistry,
|
||
DEFAULT_BOARD_LINK_PROVIDERS,
|
||
RDK_X5_SSH_PROVIDER,
|
||
RDK_S100_SERIAL_PROVIDER,
|
||
LOCAL_PROVIDER,
|
||
parseSshAddress,
|
||
buildSshArgs,
|
||
parseSerialAddress,
|
||
SERIAL_STUB_RESULT,
|
||
defaultBoardHealthCheck,
|
||
} from "../src/capabilities/board-link/index.js";
|
||
import {
|
||
FlashRegistry,
|
||
DEFAULT_FLASH_PROVIDERS,
|
||
DD_PROVIDER,
|
||
FASTBOOT_PROVIDER,
|
||
DFU_PROVIDER,
|
||
OPENOCD_PROVIDER,
|
||
DD_BLOCK_SIZE,
|
||
ROOT_MOUNTPOINTS,
|
||
parseOffset,
|
||
parseLsblk,
|
||
deviceBasename,
|
||
matchesDeviceName,
|
||
isRootDiskTarget,
|
||
targetExistsInRows,
|
||
splitCommand,
|
||
orchestrateRun,
|
||
probeDryRun,
|
||
exitCodeVerify,
|
||
} from "../src/capabilities/flash/index.js";
|
||
import type {
|
||
BoardSpec,
|
||
ExecFn,
|
||
ExecResult,
|
||
ExecOpts,
|
||
FlashMethod,
|
||
} from "../src/shared/types.js";
|
||
import type {
|
||
FlashPlanEx,
|
||
DryRunResult,
|
||
VerifyResult,
|
||
LsblkRow,
|
||
} from "../src/capabilities/flash/types.js";
|
||
|
||
// ============================================================================
|
||
// mock 工厂
|
||
// ============================================================================
|
||
|
||
/** 构造 mock ExecFn:记录调用,返回固定结果(所有命令同结果)。 */
|
||
function mockExec(
|
||
overrides?: Partial<ExecResult>,
|
||
): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } {
|
||
const calls: { command: string; args: string[]; opts?: ExecOpts }[] = [];
|
||
const fn = async (
|
||
command: string,
|
||
args: string[],
|
||
opts?: ExecOpts,
|
||
): Promise<ExecResult> => {
|
||
calls.push({ command, args, opts });
|
||
return {
|
||
stdout: overrides?.stdout ?? "",
|
||
stderr: overrides?.stderr ?? "",
|
||
exitCode: overrides?.exitCode ?? 0,
|
||
};
|
||
};
|
||
return Object.assign(fn, { calls }) as ExecFn & {
|
||
calls: { command: string; args: string[]; opts?: ExecOpts }[];
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构造 scripted ExecFn:按 (command,args) 路由到不同结果。
|
||
* responder 返回 undefined 时默认 exit 0 空输出。
|
||
*/
|
||
function scriptedExec(
|
||
responder: (cmd: string, args: string[]) => ExecResult | undefined,
|
||
): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } {
|
||
const calls: { command: string; args: string[]; opts?: ExecOpts }[] = [];
|
||
const fn = async (
|
||
command: string,
|
||
args: string[],
|
||
opts?: ExecOpts,
|
||
): Promise<ExecResult> => {
|
||
calls.push({ command, args, opts });
|
||
const r = responder(command, args);
|
||
return r ?? { stdout: "", stderr: "", exitCode: 0 };
|
||
};
|
||
return Object.assign(fn, { calls }) as ExecFn & {
|
||
calls: { command: string; args: string[]; opts?: ExecOpts }[];
|
||
};
|
||
}
|
||
|
||
const ok = (stdout = "", stderr = ""): ExecResult => ({ stdout, stderr, exitCode: 0 });
|
||
const fail = (exitCode: number, stderr = ""): ExecResult => ({ stdout: "", stderr, exitCode });
|
||
|
||
/** 构造 ssh BoardSpec。 */
|
||
function sshBoard(id = "x5", address = "root@192.168.1.100:22"): BoardSpec {
|
||
return { id, name: `Board ${id}`, link: "ssh", address, fingerprint: `ssh:${address}` };
|
||
}
|
||
/** 构造 serial BoardSpec。 */
|
||
function serialBoard(id = "s100", address = "/dev/ttyUSB0@115200"): BoardSpec {
|
||
return { id, name: `Board ${id}`, link: "serial", address, fingerprint: `serial:${address}` };
|
||
}
|
||
/** 构造 local BoardSpec。 */
|
||
function localBoard(id = "host"): BoardSpec {
|
||
return { id, name: `Board ${id}`, link: "local", address: "localhost", fingerprint: "local" };
|
||
}
|
||
|
||
// ============================================================================
|
||
// BoardLinkRegistry —— 等价类 + 边界 + 决策表 + 状态转换 + 不变式
|
||
// ============================================================================
|
||
|
||
describe("BoardLinkRegistry — 等价类/决策表:register→resolve→list", () => {
|
||
it("register 单 provider 后 resolve 同 linkType 返回该 provider", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_S100_SERIAL_PROVIDER);
|
||
const p = reg.resolve(serialBoard());
|
||
expect(p.id).toBe("rdk-s100-serial");
|
||
expect(p.linkType).toBe("serial");
|
||
});
|
||
|
||
it("register 三 provider 覆盖 ssh/serial/local 全 linkType(决策表)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
reg.register(RDK_S100_SERIAL_PROVIDER);
|
||
reg.register(LOCAL_PROVIDER);
|
||
expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
expect(reg.resolve(serialBoard()).id).toBe("rdk-s100-serial");
|
||
expect(reg.resolve(localBoard()).id).toBe("local");
|
||
});
|
||
|
||
it("空注册表 resolve 任意 board 抛错(fail-closed unusable=拒)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
expect(() => reg.resolve(sshBoard())).toThrow(/no provider registered/);
|
||
expect(() => reg.resolve(serialBoard())).toThrow(/no provider registered/);
|
||
});
|
||
|
||
it("已注册 ssh+local 但缺 serial → resolve serial 抛错(决策表缺项)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
reg.register(LOCAL_PROVIDER);
|
||
expect(() => reg.resolve(serialBoard())).toThrow(
|
||
/no provider registered for link type "serial"/,
|
||
);
|
||
});
|
||
|
||
it("list 空注册表返回空数组(边界 min)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const snap = reg.list();
|
||
expect(snap).toHaveLength(0);
|
||
});
|
||
|
||
it("list 单元素注册表返回长度 1(边界单元素)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
expect(reg.list()).toHaveLength(1);
|
||
});
|
||
|
||
it("linkType 为畸形值(wifi)→ 抛错含该值(对抗/fuzz)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
const bogus = { ...sshBoard(), link: "wifi" as never };
|
||
expect(() => reg.resolve(bogus)).toThrow(/no provider registered for link type "wifi"/);
|
||
});
|
||
|
||
it("resolve 抛错消息含 board id(诊断不变式)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const b = sshBoard("myboard");
|
||
expect(() => reg.resolve(b)).toThrow(/board id="myboard"/);
|
||
});
|
||
|
||
it("重复 register 同 id provider → 替换,list 长度不变(等价类:override)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const p1 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" };
|
||
const p2 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" };
|
||
reg.register(p1);
|
||
reg.register(p2);
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve(sshBoard())).toBe(p2);
|
||
});
|
||
});
|
||
|
||
describe("BoardLinkRegistry — 状态转换:register→resolve→dispose→resolve(不可达)", () => {
|
||
it("dispose 后该 provider 不可再 resolve(状态迁移到 absent)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const dispose = reg.register(RDK_X5_SSH_PROVIDER);
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
|
||
dispose();
|
||
expect(reg.list()).toHaveLength(0);
|
||
expect(() => reg.resolve(sshBoard())).toThrow();
|
||
});
|
||
|
||
it("dispose 幂等:二次调用无副作用(重入安全)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const dispose = reg.register(RDK_X5_SSH_PROVIDER);
|
||
dispose();
|
||
dispose(); // 不抛
|
||
expect(reg.list()).toHaveLength(0);
|
||
});
|
||
|
||
it("再注册同 provider 后 resolve 复活(状态 absent→present)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const dispose = reg.register(RDK_X5_SSH_PROVIDER);
|
||
dispose();
|
||
expect(() => reg.resolve(sshBoard())).toThrow();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
});
|
||
|
||
it("override 安全:disposer 只删仍是同一实例的条目,不误删后注册的同 id provider", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const p1: typeof RDK_X5_SSH_PROVIDER = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" };
|
||
const p2: typeof RDK_X5_SSH_PROVIDER = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" };
|
||
const dispose1 = reg.register(p1);
|
||
reg.register(p2); // 同 id 替换
|
||
dispose1(); // p1 的 disposer:get(id)===p1? 否(是 p2)→不删
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve(sshBoard())).toBe(p2);
|
||
});
|
||
|
||
it("同 linkType 多 provider 取插入序首个(决策表)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const first = { ...RDK_X5_SSH_PROVIDER, id: "ssh-a" };
|
||
const second = { ...RDK_X5_SSH_PROVIDER, id: "ssh-b" };
|
||
reg.register(first);
|
||
reg.register(second);
|
||
expect(reg.resolve(sshBoard()).id).toBe("ssh-a");
|
||
});
|
||
|
||
it("先 dispose 第一个后第二个同 linkType 升首(状态转换)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const first = { ...RDK_X5_SSH_PROVIDER, id: "ssh-a" };
|
||
const second = { ...RDK_X5_SSH_PROVIDER, id: "ssh-b" };
|
||
const d1 = reg.register(first);
|
||
reg.register(second);
|
||
expect(reg.resolve(sshBoard()).id).toBe("ssh-a");
|
||
d1();
|
||
expect(reg.resolve(sshBoard()).id).toBe("ssh-b");
|
||
});
|
||
|
||
it("完整生命周期:register→resolve→dispose→re-register→resolve(状态环)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const d1 = reg.register(RDK_X5_SSH_PROVIDER);
|
||
expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
d1();
|
||
expect(() => reg.resolve(sshBoard())).toThrow();
|
||
// re-register with different provider instance same id
|
||
const p2 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" };
|
||
const d2 = reg.register(p2);
|
||
expect(reg.resolve(sshBoard())).toBe(p2);
|
||
d2();
|
||
expect(() => reg.resolve(sshBoard())).toThrow();
|
||
});
|
||
|
||
it("交错 register/dispose 多 provider 不互相腐蚀(状态转换复杂序列)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const dSsh = reg.register(RDK_X5_SSH_PROVIDER);
|
||
const dSerial = reg.register(RDK_S100_SERIAL_PROVIDER);
|
||
reg.register(LOCAL_PROVIDER);
|
||
dSsh();
|
||
expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-s100-serial"]);
|
||
dSerial();
|
||
expect(reg.list().map((p) => p.id)).toEqual(["local"]);
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-x5-ssh"]);
|
||
});
|
||
});
|
||
|
||
describe("BoardLinkRegistry — 并发重入/对抗(fuzz)", () => {
|
||
it("并发 register + dispose 互不腐蚀(无共享状态竞争)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const dispose = reg.register(RDK_X5_SSH_PROVIDER);
|
||
reg.register(LOCAL_PROVIDER);
|
||
dispose();
|
||
reg.register(RDK_S100_SERIAL_PROVIDER);
|
||
expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-s100-serial"]);
|
||
});
|
||
|
||
it("dispose 已空注册表不抛(空状态重入)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
const d = reg.register(RDK_X5_SSH_PROVIDER);
|
||
d();
|
||
const d2 = reg.register(RDK_X5_SSH_PROVIDER);
|
||
d2();
|
||
d2();
|
||
expect(reg.list()).toHaveLength(0);
|
||
});
|
||
|
||
it("多注册表实例互不干扰(隔离不变式)", () => {
|
||
const reg1 = new BoardLinkRegistry();
|
||
const reg2 = new BoardLinkRegistry();
|
||
reg1.register(RDK_X5_SSH_PROVIDER);
|
||
// reg2 空 → resolve 抛错
|
||
expect(() => reg2.resolve(sshBoard())).toThrow();
|
||
// reg1 仍可用
|
||
expect(reg1.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
// 在 reg2 注册后不影响 reg1
|
||
reg2.register(LOCAL_PROVIDER);
|
||
expect(reg1.list()).toHaveLength(1);
|
||
expect(reg2.list()).toHaveLength(1);
|
||
});
|
||
});
|
||
|
||
describe("BoardLinkRegistry — 元蜕变/不变式:list 快照独立性", () => {
|
||
it("两次 list() 返回独立数组,mutate 一个不影响注册表与另一快照", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
const a = reg.list() as unknown[];
|
||
const b = reg.list() as unknown[];
|
||
expect(a).not.toBe(b);
|
||
a.push({} as never);
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(b).toHaveLength(1);
|
||
});
|
||
|
||
it("list 返回顺序稳定(插入序不变式,元蜕变)", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
reg.register(RDK_X5_SSH_PROVIDER);
|
||
reg.register(RDK_S100_SERIAL_PROVIDER);
|
||
reg.register(LOCAL_PROVIDER);
|
||
const ids1 = reg.list().map((p) => p.id);
|
||
const ids2 = reg.list().map((p) => p.id);
|
||
expect(ids1).toEqual(ids2);
|
||
expect(ids1).toEqual(["rdk-x5-ssh", "rdk-s100-serial", "local"]);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// parseSshAddress —— 等价类 + 边界值 + 对抗/fuzz
|
||
// ============================================================================
|
||
|
||
describe("parseSshAddress — 等价类/边界值", () => {
|
||
it("user@host:port 全字段", () => {
|
||
expect(parseSshAddress("root@192.168.1.100:2222")).toEqual({
|
||
user: "root",
|
||
host: "192.168.1.100",
|
||
port: 2222,
|
||
});
|
||
});
|
||
it("user@host 无端口 → 默认 22", () => {
|
||
expect(parseSshAddress("root@board")).toEqual({ user: "root", host: "board", port: 22 });
|
||
});
|
||
it("仅 host 无 user → 默认 root", () => {
|
||
expect(parseSshAddress("board")).toEqual({ user: "root", host: "board", port: 22 });
|
||
});
|
||
it("IPv6 带端口 [::1]:2222", () => {
|
||
expect(parseSshAddress("[::1]:2222")).toEqual({ user: "root", host: "::1", port: 2222 });
|
||
});
|
||
it("IPv6 带括号无端口 → 默认 22", () => {
|
||
expect(parseSshAddress("root@[::1]")).toEqual({ user: "root", host: "::1", port: 22 });
|
||
});
|
||
it("空白字符被 trim", () => {
|
||
expect(parseSshAddress(" root@host:2222 ")).toEqual({
|
||
user: "root",
|
||
host: "host",
|
||
port: 2222,
|
||
});
|
||
});
|
||
it("端口 0 被解析为 0(边界 min)", () => {
|
||
expect(parseSshAddress("host:0").port).toBe(0);
|
||
});
|
||
it("端口带前导零 → parseInt 去零(边界)", () => {
|
||
expect(parseSshAddress("host:0022").port).toBe(22);
|
||
});
|
||
it("非数字端口后缀 → 不当端口,host 保留(fail-tolerant)", () => {
|
||
const r = parseSshAddress("host:abc");
|
||
expect(r.host).toBe("host:abc");
|
||
expect(r.port).toBe(22);
|
||
});
|
||
it("多 @ 取第一个(user 在第一个 @ 前)", () => {
|
||
const r = parseSshAddress("a@b@host:2222");
|
||
expect(r.user).toBe("a");
|
||
expect(r.host).toBe("b@host");
|
||
expect(r.port).toBe(2222);
|
||
});
|
||
});
|
||
|
||
describe("parseSshAddress — 对抗/fuzz", () => {
|
||
it("空串 → user root / host 空 / port 22", () => {
|
||
expect(parseSshAddress("")).toEqual({ user: "root", host: "", port: 22 });
|
||
});
|
||
it("仅 @ → user 空 / host 空", () => {
|
||
const r = parseSshAddress("@");
|
||
expect(r.user).toBe("");
|
||
expect(r.host).toBe("");
|
||
});
|
||
it("user@ 无 host → host 空", () => {
|
||
const r = parseSshAddress("root@");
|
||
expect(r.user).toBe("root");
|
||
expect(r.host).toBe("");
|
||
});
|
||
it("仅冒号 → host 保留为 ':' 且 port 22(after 空非数字)", () => {
|
||
const r = parseSshAddress(":");
|
||
expect(r.host).toBe(":");
|
||
expect(r.port).toBe(22);
|
||
});
|
||
it("巨大端口号 → Number 仍解析(不校验 65535 上界)", () => {
|
||
const r = parseSshAddress("host:999999999999");
|
||
expect(r.port).toBe(999999999999);
|
||
});
|
||
it("仅空格 → trim 后空串 → host 空", () => {
|
||
const r = parseSshAddress(" ");
|
||
expect(r.user).toBe("root");
|
||
expect(r.host).toBe("");
|
||
expect(r.port).toBe(22);
|
||
});
|
||
it("host 含多个冒号但尾部非数字(IPv6 无端口)", () => {
|
||
const r = parseSshAddress("root@[fe80::1]");
|
||
expect(r.host).toBe("fe80::1");
|
||
expect(r.port).toBe(22);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// buildSshArgs —— 决策表 + 边界
|
||
// ============================================================================
|
||
|
||
describe("buildSshArgs — 决策表(port 22 vs 非 22 × args 空/非空)", () => {
|
||
it("非默认端口 → 带 -p <port>", () => {
|
||
const board = sshBoard("x5", "root@192.168.1.100:2222");
|
||
expect(buildSshArgs(board, "ls", ["-la"])).toEqual([
|
||
"-p", "2222", "root@192.168.1.100", "ls", "-la",
|
||
]);
|
||
});
|
||
it("默认端口 22 → 不带 -p(减噪)", () => {
|
||
const board = sshBoard("x5", "root@192.168.1.100:22");
|
||
expect(buildSshArgs(board, "ls", ["-la"])).toEqual([
|
||
"root@192.168.1.100", "ls", "-la",
|
||
]);
|
||
});
|
||
it("默认端口 + 空 args → 仅 user@host + command(边界)", () => {
|
||
const board = sshBoard("x5", "root@board");
|
||
expect(buildSshArgs(board, "uname", [])).toEqual(["root@board", "uname"]);
|
||
});
|
||
it("非默认端口 + 空 args → -p + user@host + command", () => {
|
||
const board = sshBoard("x5", "root@board:2222");
|
||
expect(buildSshArgs(board, "uname", [])).toEqual(["-p", "2222", "root@board", "uname"]);
|
||
});
|
||
it("多个 args 原序展开", () => {
|
||
const board = sshBoard("x5", "root@board");
|
||
expect(buildSshArgs(board, "echo", ["a", "b", "c"])).toEqual([
|
||
"root@board", "echo", "a", "b", "c",
|
||
]);
|
||
});
|
||
it("端口 0 → 带 -p 0(非 22 即带 -p,边界 min)", () => {
|
||
const board = sshBoard("x5", "host:0");
|
||
const args = buildSshArgs(board, "ls", []);
|
||
expect(args).toContain("-p");
|
||
expect(args).toContain("0");
|
||
});
|
||
it("空 command + 空 args → 仅 user@host(边界)", () => {
|
||
const board = sshBoard("x5", "root@board");
|
||
expect(buildSshArgs(board, "", [])).toEqual(["root@board", ""]);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// BoardLinkProvider createExec —— 等价类 + 不变式
|
||
// ============================================================================
|
||
|
||
describe("RDK_X5_SSH_PROVIDER createExec — 等价类:包装命令委托 underlying", () => {
|
||
it("createExec 产出 ExecFn 调 underlying('ssh', sshArgs, opts)", async () => {
|
||
const underlying = mockExec();
|
||
const board = sshBoard("x5", "root@192.168.1.100:2222");
|
||
const exec = RDK_X5_SSH_PROVIDER.createExec(board, underlying);
|
||
await exec("ls", ["-la"], { timeout: 5000 });
|
||
|
||
expect(underlying.calls).toHaveLength(1);
|
||
expect(underlying.calls[0].command).toBe("ssh");
|
||
expect(underlying.calls[0].args).toEqual(["-p", "2222", "root@192.168.1.100", "ls", "-la"]);
|
||
expect(underlying.calls[0].opts?.timeout).toBe(5000);
|
||
});
|
||
|
||
it("opts 透传:无 opts 时 underlying 收到 undefined", async () => {
|
||
const underlying = mockExec();
|
||
const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying);
|
||
await exec("uname", []);
|
||
expect(underlying.calls[0].opts).toBeUndefined();
|
||
});
|
||
|
||
it("createExec 返回的 ExecFn 每次调均包装(不变式:委托恒定)", async () => {
|
||
const underlying = mockExec();
|
||
const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying);
|
||
await exec("ls", []);
|
||
await exec("pwd", []);
|
||
expect(underlying.calls).toHaveLength(2);
|
||
expect(underlying.calls.every((c) => c.command === "ssh")).toBe(true);
|
||
});
|
||
|
||
it("id/linkType 契约", () => {
|
||
expect(RDK_X5_SSH_PROVIDER.id).toBe("rdk-x5-ssh");
|
||
expect(RDK_X5_SSH_PROVIDER.linkType).toBe("ssh");
|
||
});
|
||
});
|
||
|
||
describe("RDK_S100_SERIAL_PROVIDER createExec — 不变式:stub 不调 underlying", () => {
|
||
it("createExec 返回 stub,underlying 永不被调用,exitCode 0", async () => {
|
||
const underlying = mockExec();
|
||
const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying);
|
||
const r = await exec("uname", ["-a"]);
|
||
expect(underlying.calls).toHaveLength(0);
|
||
expect(r.exitCode).toBe(0);
|
||
expect(r.stdout).toContain("serial-stub");
|
||
expect(r).toBe(SERIAL_STUB_RESULT); // 同一引用(恒等不变式)
|
||
});
|
||
|
||
it("SERIAL_STUB_RESULT 内容契约:stderr 空 + stdout 标注 stub", () => {
|
||
expect(SERIAL_STUB_RESULT.stderr).toBe("");
|
||
expect(SERIAL_STUB_RESULT.exitCode).toBe(0);
|
||
expect(SERIAL_STUB_RESULT.stdout).toMatch(/serial-stub/);
|
||
});
|
||
|
||
it("多次调用 stub 返回同一引用(元蜕变:恒等不变式)", async () => {
|
||
const underlying = mockExec();
|
||
const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying);
|
||
const r1 = await exec("a", []);
|
||
const r2 = await exec("b", ["x"]);
|
||
expect(r1).toBe(r2);
|
||
expect(r1).toBe(SERIAL_STUB_RESULT);
|
||
});
|
||
|
||
it("id/linkType 契约", () => {
|
||
expect(RDK_S100_SERIAL_PROVIDER.id).toBe("rdk-s100-serial");
|
||
expect(RDK_S100_SERIAL_PROVIDER.linkType).toBe("serial");
|
||
});
|
||
});
|
||
|
||
describe("LOCAL_PROVIDER createExec — 等价类:直透 underlying", () => {
|
||
it("createExec 产出 ExecFn 原样转发 command/args/opts", async () => {
|
||
const underlying = mockExec();
|
||
const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying);
|
||
await exec("echo", ["hi"], { cwd: "/tmp" });
|
||
expect(underlying.calls[0]).toEqual({
|
||
command: "echo", args: ["hi"], opts: { cwd: "/tmp" },
|
||
});
|
||
});
|
||
|
||
it("无 opts 直透 undefined", async () => {
|
||
const underlying = mockExec();
|
||
const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying);
|
||
await exec("uname", []);
|
||
expect(underlying.calls[0].command).toBe("uname");
|
||
expect(underlying.calls[0].opts).toBeUndefined();
|
||
});
|
||
|
||
it("id/linkType 契约", () => {
|
||
expect(LOCAL_PROVIDER.id).toBe("local");
|
||
expect(LOCAL_PROVIDER.linkType).toBe("local");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// defaultBoardHealthCheck —— 决策表 + fail-closed 不变式
|
||
// ============================================================================
|
||
|
||
describe("defaultBoardHealthCheck — 决策表(exit 0 / 非 0 / 抛异常)", () => {
|
||
it("exit 0 → ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.reason).toBeUndefined();
|
||
});
|
||
it("exit 非 0 + stderr 有文 → ok false + reason 含 stderr", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "boom" });
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("probe exit 1");
|
||
expect(r.reason).toContain("boom");
|
||
});
|
||
it("exit 非 0 + stderr 空 → reason 含 (no stderr)(边界)", async () => {
|
||
const exec = mockExec({ exitCode: 2, stderr: "" });
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("(no stderr)");
|
||
});
|
||
it("exec 抛异常 → ok false + reason 含 probe threw(fail-closed)", async () => {
|
||
const exec = (async () => { throw new Error("network unreachable"); }) as ExecFn;
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("probe threw");
|
||
expect(r.reason).toContain("network unreachable");
|
||
});
|
||
it("exec 抛非 Error 对象 → reason 含 String(e)(fail-closed 兜底)", async () => {
|
||
const exec = (async () => { throw "string error"; }) as ExecFn;
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("string error");
|
||
});
|
||
it("exec 抛 undefined → reason 含 'undefined'(fail-closed 兜底)", async () => {
|
||
const exec = (async () => { throw undefined; }) as ExecFn; // eslint-disable-line no-throw-literal
|
||
const r = await defaultBoardHealthCheck(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("probe threw");
|
||
});
|
||
});
|
||
|
||
describe("defaultBoardHealthCheck — 边界/不变式:默认探活命令与超时", () => {
|
||
it("默认探活命令 'true' + 默认超时 10000 透传给 exec", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
await defaultBoardHealthCheck(exec);
|
||
expect(exec.calls[0].command).toBe("true");
|
||
expect(exec.calls[0].args).toEqual([]);
|
||
expect(exec.calls[0].opts?.timeout).toBe(10_000);
|
||
});
|
||
it("自定义探活命令 + 自定义超时透传", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
await defaultBoardHealthCheck(exec, "ls", 5000);
|
||
expect(exec.calls[0].command).toBe("ls");
|
||
expect(exec.calls[0].opts?.timeout).toBe(5000);
|
||
});
|
||
it("超时 0 透传(边界 min)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
await defaultBoardHealthCheck(exec, "true", 0);
|
||
expect(exec.calls[0].opts?.timeout).toBe(0);
|
||
});
|
||
it("负超时透传(对抗:不校验,调用方负责)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
await defaultBoardHealthCheck(exec, "true", -1);
|
||
expect(exec.calls[0].opts?.timeout).toBe(-1);
|
||
});
|
||
});
|
||
|
||
describe("Provider healthCheck 集成 — 不变式:经 createExec 包装后探活", () => {
|
||
it("ssh healthCheck 在板上跑 'true' → underlying 收到 ssh argv 含 'true'", async () => {
|
||
const underlying = mockExec({ exitCode: 0 });
|
||
const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host:2222"), underlying);
|
||
const r = await RDK_X5_SSH_PROVIDER.healthCheck!(exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(underlying.calls[0].command).toBe("ssh");
|
||
expect(underlying.calls[0].args).toContain("true");
|
||
expect(underlying.calls[0].opts?.timeout).toBe(10_000);
|
||
});
|
||
it("local healthCheck 直透 underlying('true', [], {timeout})", async () => {
|
||
const underlying = mockExec({ exitCode: 0 });
|
||
const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying);
|
||
const r = await LOCAL_PROVIDER.healthCheck!(exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(underlying.calls[0].command).toBe("true");
|
||
});
|
||
it("serial healthCheck:stub 永远 exitCode 0 → ok true(stub 恒活)", async () => {
|
||
const underlying = mockExec({ exitCode: 0 });
|
||
const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying);
|
||
const r = await RDK_S100_SERIAL_PROVIDER.healthCheck!(exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(underlying.calls).toHaveLength(0);
|
||
});
|
||
it("ssh healthCheck underlying 抛异常 → ok false(fail-closed 端到端)", async () => {
|
||
const underlying = (async () => { throw new Error("ssh unreachable"); }) as ExecFn;
|
||
const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying);
|
||
const r = await RDK_X5_SSH_PROVIDER.healthCheck!(exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("probe threw");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// parseSerialAddress —— 等价类 + 边界
|
||
// ============================================================================
|
||
|
||
describe("parseSerialAddress — 等价类/边界值", () => {
|
||
it("dev@baudrate 全字段", () => {
|
||
expect(parseSerialAddress("/dev/ttyUSB0@115200")).toEqual({
|
||
dev: "/dev/ttyUSB0",
|
||
baudrate: 115_200,
|
||
});
|
||
});
|
||
it("无 @ 后缀 → 默认 115200", () => {
|
||
expect(parseSerialAddress("/dev/ttyUSB0")).toEqual({
|
||
dev: "/dev/ttyUSB0",
|
||
baudrate: 115_200,
|
||
});
|
||
});
|
||
it("@ 后非数字 → 整串作 dev(fail-tolerant)", () => {
|
||
expect(parseSerialAddress("/dev/ttyUSB0@fast")).toEqual({
|
||
dev: "/dev/ttyUSB0@fast",
|
||
baudrate: 115_200,
|
||
});
|
||
});
|
||
it("baudrate 0(边界 min)", () => {
|
||
expect(parseSerialAddress("/dev/ttyUSB0@0").baudrate).toBe(0);
|
||
});
|
||
it("多 @ 取最后一个", () => {
|
||
expect(parseSerialAddress("/dev/@ttyUSB0@9600")).toEqual({
|
||
dev: "/dev/@ttyUSB0",
|
||
baudrate: 9600,
|
||
});
|
||
});
|
||
it("空串 → dev 空 / 默认 baudrate(边界)", () => {
|
||
expect(parseSerialAddress("")).toEqual({ dev: "", baudrate: 115_200 });
|
||
});
|
||
it("仅 @ → dev '@' / 默认 baudrate(边界)", () => {
|
||
const r = parseSerialAddress("@");
|
||
expect(r.dev).toBe("@");
|
||
expect(r.baudrate).toBe(115_200);
|
||
});
|
||
it("baudrate 带前导零 → parseInt 去零(边界)", () => {
|
||
expect(parseSerialAddress("/dev/ttyUSB0@009600").baudrate).toBe(9600);
|
||
});
|
||
it("仅空格 → dev 空 / 默认 baudrate(边界)", () => {
|
||
expect(parseSerialAddress(" ")).toEqual({ dev: "", baudrate: 115_200 });
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// FlashRegistry —— 等价类 + 状态转换 + 不变式(对称 BoardLinkRegistry)
|
||
// ============================================================================
|
||
|
||
describe("FlashRegistry — 等价类/决策表:register→resolve→list", () => {
|
||
it("register 四 provider 覆盖 dd/fastboot/dfu/openocd(决策表)", () => {
|
||
const reg = new FlashRegistry();
|
||
reg.register(DD_PROVIDER);
|
||
reg.register(FASTBOOT_PROVIDER);
|
||
reg.register(DFU_PROVIDER);
|
||
reg.register(OPENOCD_PROVIDER);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
expect(reg.resolve("fastboot").id).toBe("fastboot");
|
||
expect(reg.resolve("dfu").id).toBe("dfu");
|
||
expect(reg.resolve("openocd").id).toBe("openocd");
|
||
});
|
||
it("空注册表 resolve 任意 method 抛错(fail-closed unusable=拒)", () => {
|
||
const reg = new FlashRegistry();
|
||
expect(() => reg.resolve("dd")).toThrow(/no provider registered for method "dd"/);
|
||
});
|
||
it("已注册 dd+fastboot 但缺 openocd → resolve openocd 抛错", () => {
|
||
const reg = new FlashRegistry();
|
||
reg.register(DD_PROVIDER);
|
||
reg.register(FASTBOOT_PROVIDER);
|
||
expect(() => reg.resolve("openocd")).toThrow(/no provider registered for method "openocd"/);
|
||
});
|
||
it("list 空注册表返回空数组(边界 min)", () => {
|
||
expect(new FlashRegistry().list()).toHaveLength(0);
|
||
});
|
||
it("重复 register 同 method → 替换不增(等价类:override)", () => {
|
||
const reg = new FlashRegistry();
|
||
const p1 = { ...DD_PROVIDER, id: "dd" as FlashMethod };
|
||
const p2 = { ...DD_PROVIDER, id: "dd" as FlashMethod };
|
||
reg.register(p1);
|
||
reg.register(p2);
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve("dd")).toBe(p2);
|
||
});
|
||
});
|
||
|
||
describe("FlashRegistry — 状态转换:dispose→不可达 + 重入", () => {
|
||
it("dispose 后不可 resolve,再注册复活", () => {
|
||
const reg = new FlashRegistry();
|
||
const dispose = reg.register(DD_PROVIDER);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
dispose();
|
||
expect(() => reg.resolve("dd")).toThrow();
|
||
reg.register(DD_PROVIDER);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
});
|
||
it("dispose 幂等", () => {
|
||
const reg = new FlashRegistry();
|
||
const d = reg.register(DD_PROVIDER);
|
||
d(); d();
|
||
expect(reg.list()).toHaveLength(0);
|
||
});
|
||
it("override 安全:同 method 后注册不被前者 disposer 误删", () => {
|
||
const reg = new FlashRegistry();
|
||
const p1 = { ...DD_PROVIDER, id: "dd" as FlashMethod };
|
||
const p2 = { ...DD_PROVIDER, id: "dd" as FlashMethod };
|
||
const d1 = reg.register(p1);
|
||
reg.register(p2);
|
||
d1();
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve("dd")).toBe(p2);
|
||
});
|
||
it("list 快照独立(元蜕变)", () => {
|
||
const reg = new FlashRegistry();
|
||
reg.register(DD_PROVIDER);
|
||
const a = reg.list() as unknown[];
|
||
const b = reg.list() as unknown[];
|
||
expect(a).not.toBe(b);
|
||
a.pop();
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(b).toHaveLength(1);
|
||
});
|
||
it("完整生命周期:register→resolve→dispose→re-register→resolve(状态环)", () => {
|
||
const reg = new FlashRegistry();
|
||
const d1 = reg.register(DD_PROVIDER);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
d1();
|
||
expect(() => reg.resolve("dd")).toThrow();
|
||
reg.register(FASTBOOT_PROVIDER);
|
||
expect(reg.resolve("fastboot").id).toBe("fastboot");
|
||
expect(() => reg.resolve("dd")).toThrow();
|
||
reg.register(DD_PROVIDER);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
});
|
||
it("交错 register/dispose 多 provider 不互相腐蚀(状态转换复杂序列)", () => {
|
||
const reg = new FlashRegistry();
|
||
const dDd = reg.register(DD_PROVIDER);
|
||
const dFb = reg.register(FASTBOOT_PROVIDER);
|
||
reg.register(OPENOCD_PROVIDER);
|
||
dDd();
|
||
expect(reg.list().map((p) => p.id).sort()).toEqual(["fastboot", "openocd"]);
|
||
dFb();
|
||
expect(reg.list().map((p) => p.id)).toEqual(["openocd"]);
|
||
reg.register(DFU_PROVIDER);
|
||
expect(reg.list().map((p) => p.id).sort()).toEqual(["dfu", "openocd"]);
|
||
});
|
||
});
|
||
|
||
describe("FlashRegistry — 隔离/对抗(fuzz)", () => {
|
||
it("多注册表实例互不干扰(隔离不变式)", () => {
|
||
const reg1 = new FlashRegistry();
|
||
const reg2 = new FlashRegistry();
|
||
reg1.register(DD_PROVIDER);
|
||
expect(() => reg2.resolve("dd")).toThrow();
|
||
expect(reg1.resolve("dd").id).toBe("dd");
|
||
reg2.register(FASTBOOT_PROVIDER);
|
||
expect(reg1.list()).toHaveLength(1);
|
||
expect(reg2.list()).toHaveLength(1);
|
||
});
|
||
it("resolve 畸形 method 抛错含该 method(对抗)", () => {
|
||
const reg = new FlashRegistry();
|
||
expect(() => reg.resolve("nonsense" as FlashMethod)).toThrow(/no provider registered for method "nonsense"/);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// parseOffset —— 等价类 + 边界值(off-by-one/max/min)+ 对抗/fuzz
|
||
// ============================================================================
|
||
|
||
describe("parseOffset — 等价类/边界值", () => {
|
||
it("undefined → 0(默认偏移)", () => {
|
||
expect(parseOffset(undefined)).toBe(0);
|
||
});
|
||
it("空串 → 0", () => {
|
||
expect(parseOffset("")).toBe(0);
|
||
});
|
||
it("十进制 '0' → 0(min)", () => {
|
||
expect(parseOffset("0")).toBe(0);
|
||
});
|
||
it("十进制正整数", () => {
|
||
expect(parseOffset("8388608")).toBe(8388608);
|
||
});
|
||
it("十进制带前导零 → parseInt 去零(边界)", () => {
|
||
expect(parseOffset("0042")).toBe(42);
|
||
});
|
||
it("hex 0x0 → 0(off-by-one 关键边界)", () => {
|
||
expect(parseOffset("0x0")).toBe(0);
|
||
});
|
||
it("hex 0x0000 → 0(多零边界)", () => {
|
||
expect(parseOffset("0x0000")).toBe(0);
|
||
});
|
||
it("hex 0x10 → 16", () => {
|
||
expect(parseOffset("0x10")).toBe(16);
|
||
});
|
||
it("hex 混合大小写 0xAbCdEf", () => {
|
||
expect(parseOffset("0xAbCdEf")).toBe(0xabcdef);
|
||
});
|
||
it("hex 全大写字母 0xFF", () => {
|
||
expect(parseOffset("0xFF")).toBe(255);
|
||
});
|
||
it("十进制带空白 trim", () => {
|
||
expect(parseOffset(" 123 ")).toBe(123);
|
||
});
|
||
it("hex 带空白 trim", () => {
|
||
expect(parseOffset(" 0xff ")).toBe(0xff);
|
||
});
|
||
it("仅空白 → null(trim 后空串不匹配任何格式,边界)", () => {
|
||
// " " → trimmed = "" → 不匹配 0x hex / 不匹配十进制 → null
|
||
expect(parseOffset(" ")).toBeNull();
|
||
});
|
||
it("十进制 = MAX_SAFE_INTEGER(边界)", () => {
|
||
expect(parseOffset(String(Number.MAX_SAFE_INTEGER))).toBe(Number.MAX_SAFE_INTEGER);
|
||
});
|
||
it("十进制 > MAX_SAFE_INTEGER → 截断为 MAX_SAFE_INTEGER(上界)", () => {
|
||
expect(parseOffset("9007199254740992")).toBe(Number.MAX_SAFE_INTEGER);
|
||
expect(parseOffset("99999999999999999999999999")).toBe(Number.MAX_SAFE_INTEGER);
|
||
});
|
||
it("负数 → null(拒绝)", () => {
|
||
expect(parseOffset("-1")).toBeNull();
|
||
});
|
||
it("'0x' 无数字 → null", () => {
|
||
expect(parseOffset("0x")).toBeNull();
|
||
});
|
||
it("非数字串 → null", () => {
|
||
expect(parseOffset("abc")).toBeNull();
|
||
});
|
||
it("小数 → null(仅认整数)", () => {
|
||
expect(parseOffset("1.5")).toBeNull();
|
||
});
|
||
it("二进制 0b 前缀 → null", () => {
|
||
expect(parseOffset("0b101")).toBeNull();
|
||
});
|
||
it("大写 0X 前缀 → null(仅认小写 0x)", () => {
|
||
expect(parseOffset("0X10")).toBeNull();
|
||
});
|
||
it("十六进制 0x 后跟 g → null(g 非十六进制)", () => {
|
||
expect(parseOffset("0xg")).toBeNull();
|
||
});
|
||
it("hex 0xfff → 4095(边界:接近 4MiB)", () => {
|
||
expect(parseOffset("0xfff")).toBe(4095);
|
||
});
|
||
});
|
||
|
||
describe("parseOffset — 对抗/fuzz", () => {
|
||
it("null 抛 TypeError(类型契约外,不静默)", () => {
|
||
expect(() => parseOffset(null as unknown as string)).toThrow(TypeError);
|
||
});
|
||
it("巨大十进制仍截断为 MAX_SAFE_INTEGER(不溢出 Infinity)", () => {
|
||
expect(parseOffset("9".repeat(400))).toBe(Number.MAX_SAFE_INTEGER);
|
||
});
|
||
it("Number(0x) 大十六进制 → 截断或 null(不 Infinity)", () => {
|
||
const r = parseOffset("0x" + "f".repeat(400));
|
||
expect(r === null || r === Number.MAX_SAFE_INTEGER || typeof r === "number").toBe(true);
|
||
expect(Number.isFinite(r as number)).toBe(r !== null);
|
||
});
|
||
it("含空字节的串 → null(对抗)", () => {
|
||
expect(parseOffset("0x\x0010")).toBeNull();
|
||
});
|
||
it("含换行的串 → null(对抗)", () => {
|
||
expect(parseOffset("0x\n10")).toBeNull();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// parseLsblk —— 等价类 + 边界 + 对抗/fuzz
|
||
// ============================================================================
|
||
|
||
describe("parseLsblk — 等价类/边界值", () => {
|
||
it("标准表格输出含 header + 多行", () => {
|
||
const raw = [
|
||
"NAME SIZE TYPE MOUNTPOINT",
|
||
"sda 500G disk ",
|
||
"mmcblk0 7.3G disk",
|
||
"mmcblk0p1 7.3G part /mnt",
|
||
].join("\n");
|
||
const rows = parseLsblk(raw);
|
||
expect(rows).toHaveLength(3);
|
||
expect(rows[0]).toEqual({ name: "sda", size: 500, type: "disk", mountpoint: "" });
|
||
expect(rows[2]).toEqual({ name: "mmcblk0p1", size: 7, type: "part", mountpoint: "/mnt" });
|
||
});
|
||
it("树形盒绘字符前缀被清洗净化", () => {
|
||
const raw = [
|
||
"NAME SIZE TYPE MOUNTPOINT",
|
||
"├─sda1 100M part /boot",
|
||
"└─sda2 499G part /",
|
||
"mmcblk0 7.3G disk",
|
||
].join("\n");
|
||
const rows = parseLsblk(raw);
|
||
expect(rows.map((r) => r.name)).toEqual(["sda1", "sda2", "mmcblk0"]);
|
||
expect(rows[0].mountpoint).toBe("/boot");
|
||
expect(rows[1].mountpoint).toBe("/");
|
||
});
|
||
it("mountpoint 含空格 → slice(3).join(' ')(边界)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 1G part /mnt/my data";
|
||
const rows = parseLsblk(raw);
|
||
expect(rows[0].mountpoint).toBe("/mnt/my data");
|
||
});
|
||
it("size 非数字 → 0(边界)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 abc part /";
|
||
const rows = parseLsblk(raw);
|
||
expect(rows[0].size).toBe(0);
|
||
});
|
||
it("少于 3 列的行被跳过(边界/契约)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G";
|
||
expect(parseLsblk(raw)).toEqual([]);
|
||
});
|
||
it("空行被跳过", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\n\n\nsda 500G disk";
|
||
expect(parseLsblk(raw)).toHaveLength(1);
|
||
});
|
||
it("无 header 的输出 → 行仍被解析(fail-tolerant)", () => {
|
||
const rows = parseLsblk("sda 500G disk\nsdb 1T disk");
|
||
expect(rows).toHaveLength(2);
|
||
expect(rows.map((r) => r.name)).toEqual(["sda", "sdb"]);
|
||
});
|
||
it("空串输入 → [](边界)", () => {
|
||
expect(parseLsblk("")).toEqual([]);
|
||
});
|
||
it("仅 header 无数据行 → [](边界)", () => {
|
||
expect(parseLsblk("NAME SIZE TYPE MOUNTPOINT")).toEqual([]);
|
||
});
|
||
it("单行数据(边界单元素)", () => {
|
||
const rows = parseLsblk("sda 500G disk");
|
||
expect(rows).toHaveLength(1);
|
||
expect(rows[0].name).toBe("sda");
|
||
});
|
||
it("mountpoint 为空且无第 4 列 → 空串", () => {
|
||
const rows = parseLsblk("NAME SIZE TYPE MOUNTPOINT\nsda 500G disk");
|
||
expect(rows[0].mountpoint).toBe("");
|
||
});
|
||
it("tab 分隔列被正确解析(对抗)", () => {
|
||
const raw = "NAME\tSIZE\tTYPE\tMOUNTPOINT\nsda\t500G\tdisk\t/mnt";
|
||
const rows = parseLsblk(raw);
|
||
expect(rows).toHaveLength(1);
|
||
expect(rows[0].name).toBe("sda");
|
||
expect(rows[0].mountpoint).toBe("/mnt");
|
||
});
|
||
it("mountpoint 含多段路径空格(边界)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 1G part /a b c d e";
|
||
const rows = parseLsblk(raw);
|
||
expect(rows[0].mountpoint).toBe("/a b c d e");
|
||
});
|
||
it("仅空白行 → [](边界)", () => {
|
||
expect(parseLsblk(" \n \n ")).toEqual([]);
|
||
});
|
||
it("header 行重复 NAME 不产生行(对抗)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nNAME SIZE TYPE MOUNTPOINT\nsda 500G disk";
|
||
const rows = parseLsblk(raw);
|
||
// 第二个 NAME 行:cleaned = "NAME SIZE TYPE MOUNTPOINT" → 4 cols → 被解析为行
|
||
// 但 started=true 后不再识别 header → 当作数据行
|
||
expect(rows).toHaveLength(2);
|
||
expect(rows[0].name).toBe("NAME");
|
||
expect(rows[1].name).toBe("sda");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// deviceBasename / matchesDeviceName / isRootDiskTarget / targetExistsInRows
|
||
// —— 决策表 + 不变式
|
||
// ============================================================================
|
||
|
||
describe("deviceBasename — 等价类/边界", () => {
|
||
it("/dev/sda1 → sda1", () => {
|
||
expect(deviceBasename("/dev/sda1")).toBe("sda1");
|
||
});
|
||
it("/dev/mmcblk0p2 → mmcblk0p2", () => {
|
||
expect(deviceBasename("/dev/mmcblk0p2")).toBe("mmcblk0p2");
|
||
});
|
||
it("无 /dev/ 前缀 → 去前导斜杠", () => {
|
||
expect(deviceBasename("sda")).toBe("sda");
|
||
expect(deviceBasename("//sda")).toBe("sda");
|
||
});
|
||
it("路径含多级目录 → 取 /dev/ 后全部", () => {
|
||
expect(deviceBasename("/dev/disk/by-id/sda")).toBe("disk/by-id/sda");
|
||
});
|
||
it("空串 → 空串(边界)", () => {
|
||
expect(deviceBasename("")).toBe("");
|
||
});
|
||
it("仅斜杠 → 空串(边界)", () => {
|
||
expect(deviceBasename("/")).toBe("");
|
||
expect(deviceBasename("///")).toBe("");
|
||
});
|
||
});
|
||
|
||
describe("matchesDeviceName — 决策表(base × name)", () => {
|
||
it("name === base → true", () => {
|
||
expect(matchesDeviceName("sda", "sda")).toBe(true);
|
||
});
|
||
it("name = base + 分区号 sda1 → true", () => {
|
||
expect(matchesDeviceName("sda", "sda1")).toBe(true);
|
||
});
|
||
it("name = base + p分区号 mmcblk0p1 → true", () => {
|
||
expect(matchesDeviceName("mmcblk0", "mmcblk0p1")).toBe(true);
|
||
});
|
||
it("name = base + 多位分区号 nvme0n1p2 → true", () => {
|
||
expect(matchesDeviceName("nvme0n1", "nvme0n1p2")).toBe(true);
|
||
});
|
||
it("name 前缀相同但不同设备 sdab → false(关键回归)", () => {
|
||
expect(matchesDeviceName("sda", "sdab")).toBe(false);
|
||
});
|
||
it("name mmcblk0boot0 → false(前缀同但非分区号)", () => {
|
||
expect(matchesDeviceName("mmcblk0", "mmcblk0boot0")).toBe(false);
|
||
});
|
||
it("name mmcblk0p 无数字 → false", () => {
|
||
expect(matchesDeviceName("mmcblk0", "mmcblk0p")).toBe(false);
|
||
});
|
||
it("完全不同设备 → false", () => {
|
||
expect(matchesDeviceName("sda", "nvme0n1")).toBe(false);
|
||
});
|
||
it("空 base 空 name → true(边界)", () => {
|
||
expect(matchesDeviceName("", "")).toBe(true);
|
||
});
|
||
it("空 base + 非空 name → false(空 base + p?\\d+ 匹配数字串)", () => {
|
||
// 空 base → regex ^(?:p?\d+)?$ → 匹配空串或纯数字串
|
||
expect(matchesDeviceName("", "123")).toBe(true);
|
||
expect(matchesDeviceName("", "abc")).toBe(false);
|
||
});
|
||
it("base 含正则元字符(点号)→ 正确转义", () => {
|
||
expect(matchesDeviceName("sd.a", "sd.a")).toBe(true);
|
||
expect(matchesDeviceName("sd.a", "sdxxa")).toBe(false);
|
||
});
|
||
it("name = base + 多位数字 sda123 → true", () => {
|
||
expect(matchesDeviceName("sda", "sda123")).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe("isRootDiskTarget — 决策表(target × rows)", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "sda", size: 500e9, type: "disk", mountpoint: "" },
|
||
{ name: "sda2", size: 499e9, type: "part", mountpoint: "/" },
|
||
{ name: "sda1", size: 100e6, type: "part", mountpoint: "/boot" },
|
||
{ name: "mmcblk0", size: 7.3e9, type: "disk", mountpoint: "" },
|
||
{ name: "mmcblk0p1", size: 7.3e9, type: "part", mountpoint: "" },
|
||
];
|
||
it("target 整盘是根盘(分区挂 /)→ true", () => {
|
||
expect(isRootDiskTarget("/dev/sda", rows)).toBe(true);
|
||
});
|
||
it("target 分区自身挂 / → true", () => {
|
||
expect(isRootDiskTarget("/dev/sda2", rows)).toBe(true);
|
||
});
|
||
it("target 分区挂 /boot → true", () => {
|
||
expect(isRootDiskTarget("/dev/sda1", rows)).toBe(true);
|
||
});
|
||
it("target 非根盘 → false", () => {
|
||
expect(isRootDiskTarget("/dev/mmcblk0", rows)).toBe(false);
|
||
});
|
||
it("target 不在 rows → false", () => {
|
||
expect(isRootDiskTarget("/dev/nvme0n1", rows)).toBe(false);
|
||
});
|
||
it("前缀碰撞:target sda,rows 有 sdab 挂 / → false(关键回归)", () => {
|
||
const rows2: LsblkRow[] = [
|
||
{ name: "sda", size: 1, type: "disk", mountpoint: "" },
|
||
{ name: "sdab", size: 1, type: "disk", mountpoint: "/" },
|
||
];
|
||
expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false);
|
||
});
|
||
it("ROOT_MOUNTPOINTS 含核心挂载点集合", () => {
|
||
for (const mp of ["/", "/boot", "/boot/efi", "/home", "/var", "/usr", "/swap", "[SWAP]"]) {
|
||
expect(ROOT_MOUNTPOINTS.has(mp)).toBe(true);
|
||
}
|
||
expect(ROOT_MOUNTPOINTS.has("/tmp")).toBe(false);
|
||
});
|
||
it("ROOT_MOUNTPOINTS 不可变:add 抛 TypeError(fail-closed 不变式)", () => {
|
||
const s = ROOT_MOUNTPOINTS as unknown as { add?: (v: string) => void };
|
||
expect(typeof s.add).toBe("undefined"); // FrozenSet 不暴露 add
|
||
});
|
||
it("ROOT_MOUNTPOINTS size 契约", () => {
|
||
expect(ROOT_MOUNTPOINTS.size).toBe(8);
|
||
});
|
||
it("空 rows → false(边界)", () => {
|
||
expect(isRootDiskTarget("/dev/sda", [])).toBe(false);
|
||
});
|
||
it("mountpoint 为空串 → 不当根盘(边界)", () => {
|
||
const rows2: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "" }];
|
||
expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false);
|
||
});
|
||
it("mountpoint 非 ROOT_MOUNTPOINTS(如 /mnt)→ false", () => {
|
||
const rows2: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "/mnt" }];
|
||
expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("targetExistsInRows — 决策表", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "mmcblk0", size: 7e9, type: "disk", mountpoint: "" },
|
||
{ name: "mmcblk0p1", size: 7e9, type: "part", mountpoint: "" },
|
||
];
|
||
it("target 整盘存在 → true", () => {
|
||
expect(targetExistsInRows("/dev/mmcblk0", rows)).toBe(true);
|
||
});
|
||
it("target 分区存在 → true", () => {
|
||
expect(targetExistsInRows("/dev/mmcblk0p1", rows)).toBe(true);
|
||
});
|
||
it("target 不存在 → false", () => {
|
||
expect(targetExistsInRows("/dev/sda", rows)).toBe(false);
|
||
});
|
||
it("前缀碰撞:target mmcblk0,rows 有 mmcblk0boot0 → false", () => {
|
||
const rows2: LsblkRow[] = [{ name: "mmcblk0boot0", size: 1, type: "disk", mountpoint: "" }];
|
||
expect(targetExistsInRows("/dev/mmcblk0", rows2)).toBe(false);
|
||
});
|
||
it("空 rows → false(边界)", () => {
|
||
expect(targetExistsInRows("/dev/sda", [])).toBe(false);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// splitCommand —— 等价类 + 边界 + 对抗/fuzz
|
||
// ============================================================================
|
||
|
||
describe("splitCommand — 等价类/边界/对抗", () => {
|
||
it("简单命令", () => {
|
||
expect(splitCommand("dd if=a of=b")).toEqual(["dd", "if=a", "of=b"]);
|
||
});
|
||
it("双引号内整体保留(openocd -c \"program x verify reset exit\")", () => {
|
||
expect(splitCommand('openocd -f cfg -c "program img verify reset exit"')).toEqual([
|
||
"openocd", "-f", "cfg", "-c", "program img verify reset exit",
|
||
]);
|
||
});
|
||
it("多段引号", () => {
|
||
expect(splitCommand('a "x y" b "z w"')).toEqual(["a", "x y", "b", "z w"]);
|
||
});
|
||
it("空串 → [](边界)", () => {
|
||
expect(splitCommand("")).toEqual([]);
|
||
});
|
||
it("仅空格 → [](边界)", () => {
|
||
expect(splitCommand(" ")).toEqual([]);
|
||
});
|
||
it("尾随空格不产生空 token(边界)", () => {
|
||
expect(splitCommand("dd if=a ")).toEqual(["dd", "if=a"]);
|
||
});
|
||
it("不平衡引号不崩溃(对抗)", () => {
|
||
expect(splitCommand('a "b c')).toEqual(["a", "b c"]);
|
||
});
|
||
it("空引号 token 保留为空串(边界)", () => {
|
||
expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]);
|
||
});
|
||
it("仅引号 → 单个空串 token", () => {
|
||
expect(splitCommand('""')).toEqual([""]);
|
||
});
|
||
it("引号紧贴前文(对抗)", () => {
|
||
expect(splitCommand('a"b c"d')).toEqual(["ab cd"]);
|
||
});
|
||
it("多个连续空格不产生空 token(边界)", () => {
|
||
expect(splitCommand("a b")).toEqual(["a", "b"]);
|
||
});
|
||
it("tab 分隔不产生空 token(对抗)", () => {
|
||
expect(splitCommand("a\tb")).toEqual(["a\tb"]);
|
||
});
|
||
it("多个空引号 token 各自保留(边界)", () => {
|
||
expect(splitCommand('"" ""')).toEqual(["", ""]);
|
||
});
|
||
it("引号内含空格后引号外继续(对抗)", () => {
|
||
expect(splitCommand('a "b c" d')).toEqual(["a", "b c", "d"]);
|
||
});
|
||
it("仅前导空格 + 引号(边界)", () => {
|
||
expect(splitCommand(' "hello"')).toEqual(["hello"]);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// orchestrateRun —— 状态转换 + 决策表 + 不变式(fail-closed / 短路)
|
||
// ============================================================================
|
||
|
||
/** 构造最小 FlashPlanEx 供 orchestrateRun 直测。 */
|
||
function planEx(over: Partial<FlashPlanEx> = {}): FlashPlanEx {
|
||
return {
|
||
method: "dd",
|
||
commands: ["echo hi"],
|
||
target: "/dev/x",
|
||
image: "img",
|
||
...over,
|
||
};
|
||
}
|
||
const dryOk = async (p: FlashPlanEx): Promise<DryRunResult> => ({
|
||
ok: true, plan: p, targetExists: true, isRootDisk: false, probeCommands: [],
|
||
});
|
||
const dryFailFn = async (p: FlashPlanEx): Promise<DryRunResult> => ({
|
||
ok: false, reason: "dry-fail", plan: p, targetExists: false, isRootDisk: false, probeCommands: [],
|
||
});
|
||
const verifyOk = async (): Promise<VerifyResult> => ({ ok: true, verifyCommand: "vcmd" });
|
||
const verifyFailFn = async (): Promise<VerifyResult> => ({ ok: false, reason: "verify-fail", verifyCommand: "vcmd" });
|
||
|
||
describe("orchestrateRun — 状态转换/决策表", () => {
|
||
it("dryRun 失败 → written false / ok false / verify 不调(fail-closed)", async () => {
|
||
const exec = mockExec();
|
||
const verify = vi.fn(verifyOk);
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryFailFn, verify);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.written).toBe(false);
|
||
expect(r.writeExitCodes).toEqual([]);
|
||
expect(r.reason).toBe("dry-fail");
|
||
expect(verify).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("dryRun ok + dryRun 默认(undefined) → 只 dry-run 不写(fail-closed 默认)", async () => {
|
||
const exec = mockExec();
|
||
const r = await orchestrateRun(planEx({ dryRun: undefined }), exec, dryOk, verifyOk);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
expect(r.writeExitCodes).toEqual([]);
|
||
expect(exec.calls).toHaveLength(0); // 无写命令
|
||
});
|
||
|
||
it("dryRun ok + dryRun=true → 只 dry-run 不写", async () => {
|
||
const exec = mockExec();
|
||
const r = await orchestrateRun(planEx({ dryRun: true }), exec, dryOk, verifyOk);
|
||
expect(r.written).toBe(false);
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("dryRun ok + dryRun=false + 写全 0 + verify ok → written true / ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([0]);
|
||
expect(r.verify?.ok).toBe(true);
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("dryRun ok + dryRun=false + verify=false → 跳过 verify,ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const verify = vi.fn(verifyOk);
|
||
const r = await orchestrateRun(planEx({ dryRun: false, verify: false }), exec, dryOk, verify);
|
||
expect(r.written).toBe(true);
|
||
expect(r.verify).toBeUndefined();
|
||
expect(r.ok).toBe(true);
|
||
expect(verify).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("写命令失败 → 短路:后续命令不执行 + verify 不调(waterfall 短路不变式)", async () => {
|
||
const exec = mockExec({ exitCode: 3 });
|
||
const verify = vi.fn(verifyOk);
|
||
const p = planEx({
|
||
dryRun: false,
|
||
commands: ["first cmd", "second cmd"],
|
||
});
|
||
const r = await orchestrateRun(p, exec, dryOk, verify);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([3]);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("write command failed");
|
||
expect(exec.calls).toHaveLength(1); // 仅第一条
|
||
expect(verify).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("写全 0 + verify 失败 → ok false + reason verify-fail", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyFailFn);
|
||
expect(r.written).toBe(true);
|
||
expect(r.verify?.ok).toBe(false);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toBe("verify-fail");
|
||
});
|
||
|
||
it("多命令顺序执行 + 全 0 → writeExitCodes 长度 = 命令数", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const p = planEx({ dryRun: false, commands: ["a x", "b y", "c z"] });
|
||
const r = await orchestrateRun(p, exec, dryOk, verifyOk);
|
||
expect(r.writeExitCodes).toEqual([0, 0, 0]);
|
||
expect(exec.calls.map((c) => c.command)).toEqual(["a", "b", "c"]);
|
||
});
|
||
|
||
it("空 commands + dryRun=false → written true / writeExitCodes 空 / ok true(边界)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await orchestrateRun(planEx({ dryRun: false, commands: [] }), exec, dryOk, verifyOk);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([]);
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("写失败短路 reason 含 stderr(诊断不变式)", async () => {
|
||
const exec = mockExec({ exitCode: 5, stderr: "disk full" });
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk);
|
||
expect(r.reason).toContain("disk full");
|
||
});
|
||
|
||
it("写失败短路 reason 无 stderr 时含 exit N(边界)", async () => {
|
||
const exec = mockExec({ exitCode: 7, stderr: "" });
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk);
|
||
expect(r.reason).toContain("exit 7");
|
||
});
|
||
|
||
it("verify ok 时 reason undefined(不变式)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk);
|
||
expect(r.reason).toBeUndefined();
|
||
});
|
||
|
||
it("第二条写命令失败 → 第一条 exitCode 已记录 + 短路(决策表)", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "first") return ok();
|
||
return fail(9, "second fail");
|
||
});
|
||
const p = planEx({ dryRun: false, commands: ["first x", "second y"] });
|
||
const r = await orchestrateRun(p, exec, dryOk, verifyOk);
|
||
expect(r.writeExitCodes).toEqual([0, 9]);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("second y"); // plan.commands[1] = "second y"
|
||
expect(exec.calls).toHaveLength(2);
|
||
});
|
||
|
||
it("dryRun 失败后 dryRun reason 透传到顶层 reason(不变式)", async () => {
|
||
const exec = mockExec();
|
||
const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryFailFn, verifyOk);
|
||
expect(r.reason).toBe("dry-fail");
|
||
expect(r.dryRun.reason).toBe("dry-fail");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// probeDryRun / exitCodeVerify —— 决策表 + 不变式
|
||
// ============================================================================
|
||
|
||
describe("probeDryRun — 决策表(exit 0 / 非 0)", () => {
|
||
it("探活 exit 0 → ok true + probeCommands 记录", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await probeDryRun(planEx(), exec, { cmd: "fastboot", args: ["getvar", "all"] });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.targetExists).toBe(true);
|
||
expect(r.probeCommands).toEqual(["fastboot getvar all"]);
|
||
});
|
||
it("探活 非 0 → ok false + reason 含 method", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "no device" });
|
||
const r = await probeDryRun(planEx({ method: "fastboot" }), exec, { cmd: "fastboot", args: ["getvar", "all"] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("fastboot probe failed");
|
||
expect(r.reason).toContain("no device");
|
||
});
|
||
it("探活 非 0 + stderr 空 → reason 含 exit N(边界)", async () => {
|
||
const exec = mockExec({ exitCode: 2, stderr: "" });
|
||
const r = await probeDryRun(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] });
|
||
expect(r.reason).toContain("exit 2");
|
||
});
|
||
it("探活 exit 0 → isRootDisk false / targetExists true(不变式)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await probeDryRun(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] });
|
||
expect(r.isRootDisk).toBe(false);
|
||
expect(r.targetExists).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe("exitCodeVerify — 决策表(exit 0 / 非 0)", () => {
|
||
it("校验 exit 0 → ok true + verifyCommand", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await exitCodeVerify(planEx({ method: "openocd" }), exec, { cmd: "openocd", args: ["-c", "exit"] });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.verifyCommand).toBe("openocd -c exit");
|
||
});
|
||
it("校验 非 0 → ok false + reason", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "jtag fail" });
|
||
const r = await exitCodeVerify(planEx({ method: "openocd" }), exec, { cmd: "openocd", args: ["-c", "exit"] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("openocd verify failed");
|
||
});
|
||
it("校验 非 0 + stderr 空 → reason 含 exit N(边界)", async () => {
|
||
const exec = mockExec({ exitCode: 3, stderr: "" });
|
||
const r = await exitCodeVerify(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] });
|
||
expect(r.reason).toContain("exit 3");
|
||
});
|
||
it("校验 exit 0 → verifyCommand 含 cmd + args join(不变式)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const r = await exitCodeVerify(planEx(), exec, { cmd: "fastboot", args: ["getvar", "all"] });
|
||
expect(r.verifyCommand).toBe("fastboot getvar all");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// DD_PROVIDER plan —— 等价类 + 边界 + 决策表(fail-closed 抛错)
|
||
// ============================================================================
|
||
|
||
describe("DD_PROVIDER.plan — 等价类/边界值", () => {
|
||
it("基础 plan:dd if=image of=target bs=4M conv=fsync,无 seek", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
expect(p.commands).toEqual(["dd if=sd.img of=/dev/mmcblk0 bs=4M conv=fsync"]);
|
||
expect(p.offsetBytes).toBe(0);
|
||
expect(p.dryRun).toBeUndefined();
|
||
expect(p.verify).toBeUndefined();
|
||
});
|
||
it("offset > 0 → seek= 块数(字节 8388608 / 4MiB = 2)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "8388608" });
|
||
expect(p.offsetBytes).toBe(8388608);
|
||
expect(p.commands[0]).toContain("seek=2");
|
||
});
|
||
it("hex offset 0x10(16B,<4MiB)→ seek=0(floor(16/4MiB)=0,仍带 seek=)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0x10" });
|
||
expect(p.offsetBytes).toBe(16);
|
||
expect(p.commands[0]).toContain("seek=0");
|
||
});
|
||
it("offset 0 → 不带 seek", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0" });
|
||
expect(p.offsetBytes).toBe(0);
|
||
expect(p.commands[0]).not.toContain("seek=");
|
||
});
|
||
it("offset 恰好 4MiB → seek=1(边界 off-by-one)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE) });
|
||
expect(p.commands[0]).toContain("seek=1");
|
||
});
|
||
it("offset 恰好 4MiB-1 → seek=0(off-by-one 边界)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE - 1) });
|
||
expect(p.commands[0]).toContain("seek=0");
|
||
});
|
||
it("offset 恰好 8MiB → seek=2(边界)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE * 2) });
|
||
expect(p.commands[0]).toContain("seek=2");
|
||
});
|
||
it("dryRun/verify 透传", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", dryRun: false, verify: false });
|
||
expect(p.dryRun).toBe(false);
|
||
expect(p.verify).toBe(false);
|
||
});
|
||
it("plan 设 method=dd(等价类)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/x" });
|
||
expect(p.method).toBe("dd");
|
||
expect(p.target).toBe("/dev/x");
|
||
expect(p.image).toBe("i");
|
||
});
|
||
it("hex offset 0x400000 (=4MiB) → seek=1(hex 边界)", () => {
|
||
const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0x400000" });
|
||
expect(p.offsetBytes).toBe(DD_BLOCK_SIZE);
|
||
expect(p.commands[0]).toContain("seek=1");
|
||
});
|
||
});
|
||
|
||
describe("DD_PROVIDER.plan — fail-closed 抛错(决策表)", () => {
|
||
it("image 空 → 抛错", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "", target: "/dev/x" })).toThrow(/image path required/);
|
||
});
|
||
it("image 空白 → 抛错", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: " ", target: "/dev/x" })).toThrow(/image path required/);
|
||
});
|
||
it("target 空 → 抛错", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "" })).toThrow(/target required/);
|
||
});
|
||
it("target 空白 → 抛错", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: " " })).toThrow(/target required/);
|
||
});
|
||
it("offset 不可解析 → 抛错", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/x", offset: "abc" })).toThrow(/invalid offset/);
|
||
});
|
||
it("ctx.lsblk 中 target 不存在 → 抛错", () => {
|
||
const rows: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "" }];
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/mmcblk0" }, { lsblk: rows })).toThrow(/not found in lsblk/);
|
||
});
|
||
it("ctx.lsblk 中 target 是根盘 → 抛错", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "sda", size: 500e9, type: "disk", mountpoint: "" },
|
||
{ name: "sda2", size: 499e9, type: "part", mountpoint: "/" },
|
||
];
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" }, { lsblk: rows })).toThrow(/root disk|refusing/);
|
||
});
|
||
it("无 ctx.lsblk → 不做早期根盘校验(不抛)", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" })).not.toThrow();
|
||
});
|
||
it("ctx.lsblk 空数组 → 不做早期校验(不抛)", () => {
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" }, { lsblk: [] })).not.toThrow();
|
||
});
|
||
it("ctx.lsblk target 存在且非根盘 → 不抛(正常)", () => {
|
||
const rows: LsblkRow[] = [{ name: "mmcblk0", size: 7e9, type: "disk", mountpoint: "" }];
|
||
expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/mmcblk0" }, { lsblk: rows })).not.toThrow();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// DD_PROVIDER run/dryRun/verify —— 集成(scripted exec 路由)
|
||
// ============================================================================
|
||
|
||
/** 已知 payload + 其 sha256,用于 dryRun/verify happy 路径。 */
|
||
const DD_PAYLOAD = "hello-dd-payload-bytes";
|
||
const DD_PAYLOAD_SHA = createHash("sha256").update(DD_PAYLOAD).digest("hex");
|
||
const DD_IMAGE_SIZE = String(DD_PAYLOAD.length);
|
||
|
||
/** dd dryRun happy 路径的 scripted exec:lsblk/stat/sha256sum/dd-probe 全 0。 */
|
||
function ddHappyExec(targetBase = "mmcblk0"): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } {
|
||
return scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok(`NAME SIZE TYPE MOUNTPOINT\n${targetBase} 7G disk\n${targetBase}p1 7G part`);
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); // 只读探针
|
||
return ok();
|
||
});
|
||
}
|
||
|
||
describe("DD_PROVIDER.run — dryRun 默认(只 dry-run 不写)", () => {
|
||
it("全探针通过 → ok true / written false / expectedSha256 已填", async () => {
|
||
const exec = ddHappyExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
expect(r.dryRun.ok).toBe(true);
|
||
expect(plan.expectedSha256).toBe(DD_PAYLOAD_SHA);
|
||
expect(plan.blockCount).toBeGreaterThanOrEqual(1);
|
||
expect(plan.imageSizeBytes).toBe(DD_PAYLOAD.length);
|
||
});
|
||
|
||
it("dryRun 阶段 lsblk 失败 → ok false + written false", async () => {
|
||
const exec = scriptedExec(() => fail(1, "lsblk error"));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.written).toBe(false);
|
||
expect(r.dryRun.reason).toContain("lsblk failed");
|
||
});
|
||
|
||
it("dryRun 阶段 target 不在 lsblk → ok false", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nsda 500G disk");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("not found in lsblk");
|
||
});
|
||
|
||
it("dryRun 阶段 target 是根盘 → ok false + isRootDisk true", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk\nmmcblk0p1 7G part /");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.isRootDisk).toBe(true);
|
||
expect(r.dryRun.reason).toContain("refusing");
|
||
});
|
||
|
||
it("dryRun 阶段 stat 失败 → ok false", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return fail(1, "no such file");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("stat image failed");
|
||
});
|
||
|
||
it("dryRun 阶段镜像大小非法 → ok false", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok("not-a-number");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("invalid image size");
|
||
});
|
||
|
||
it("dryRun 阶段镜像大小 0 → ok false(边界)", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok("0");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("invalid image size");
|
||
});
|
||
|
||
it("dryRun 阶段 offset >= imageSize(未知设备大小回退) → 拒绝(契约边界)", async () => {
|
||
const exec = ddHappyExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: "999999" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
// targetDeviceSize = 7 (parseInt("7G")), offset 999999 >= 7 → "exceeds target device size"
|
||
expect(r.dryRun.reason).toMatch(/exceeds target device size|>= image size/);
|
||
});
|
||
|
||
it("dryRun 阶段 offset 非对齐 4MiB → 拒绝(fail-closed 非对齐)", async () => {
|
||
// offset=1 < targetDeviceSize(7) → 通过越界检查 → 命中非对齐检查
|
||
const exec = ddHappyExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: "1" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("not a multiple of block size");
|
||
});
|
||
|
||
it("dryRun 阶段 offset 恰好 4MiB 对齐 → 通过(边界)", async () => {
|
||
// 需要设备大小 > 4MiB,用字节数而非 7G(parseInt("7G")=7 太小)
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok(`NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7516192768 disk\nmmcblk0p1 7516192768 part`);
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok();
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE) });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
});
|
||
|
||
it("dryRun 阶段 sha256sum 失败 → ok false", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return fail(1, "sha err");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("sha256sum failed");
|
||
});
|
||
|
||
it("dryRun 阶段 sha256 输出非 64 hex → ok false", async () => {
|
||
const exec = scriptedExec((cmd) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok("garbage-not-a-hash");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("unparsable sha256sum");
|
||
});
|
||
|
||
it("dryRun 阶段只读 dd 探针失败 → ok false", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return fail(1, "read err");
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.dryRun.reason).toContain("image read probe failed");
|
||
});
|
||
|
||
it("dryRun ok 填充 imageSizeBytes + blockCount + expectedSha256(不变式)", async () => {
|
||
const exec = ddHappyExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
await DD_PROVIDER.run(plan, exec);
|
||
expect(plan.imageSizeBytes).toBe(DD_PAYLOAD.length);
|
||
expect(plan.blockCount).toBe(Math.max(1, Math.ceil(DD_PAYLOAD.length / DD_BLOCK_SIZE)));
|
||
expect(plan.expectedSha256).toBe(DD_PAYLOAD_SHA);
|
||
});
|
||
|
||
it("dryRun ok 填充 sha256sumOutput(不变式)", async () => {
|
||
const exec = ddHappyExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.dryRun.sha256sumOutput).toContain(DD_PAYLOAD_SHA);
|
||
});
|
||
});
|
||
|
||
describe("DD_PROVIDER.run — dryRun:false 写 + verify", () => {
|
||
it("写 + verify 全通过 → written true / ok true", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); // 探针
|
||
if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok(DD_PAYLOAD); // readback
|
||
if (cmd === "dd") return ok(); // 写
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([0]);
|
||
expect(r.verify?.ok).toBe(true);
|
||
expect(r.verify?.actual).toBe(DD_PAYLOAD_SHA);
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("dryRun:false + verify:false → 跳过 verify,ok true", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok();
|
||
if (cmd === "dd") return ok();
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false, verify: false });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.verify).toBeUndefined();
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("写命令失败 → ok false + 短路(无 readback)", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok();
|
||
if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok(DD_PAYLOAD);
|
||
if (cmd === "dd") return fail(1, "write protected"); // 写失败
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([1]);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("write command failed");
|
||
});
|
||
|
||
it("写全 0 + verify sha256 不匹配 → ok false + VERIFY FAILED", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk");
|
||
if (cmd === "stat") return ok(DD_IMAGE_SIZE);
|
||
if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`);
|
||
if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok();
|
||
if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok("different-content"); // readback mismatch
|
||
if (cmd === "dd") return ok(); // 写
|
||
return ok();
|
||
});
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false });
|
||
const r = await DD_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.verify?.ok).toBe(false);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("VERIFY FAILED");
|
||
});
|
||
});
|
||
|
||
describe("DD_PROVIDER.verify — 决策表(无 hash / 匹配 / 不匹配 / 读回失败)", () => {
|
||
it("无 expectedSha256 → ok false(fail-closed:未 dryRun 先拒)", async () => {
|
||
const exec = mockExec();
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
const r = await DD_PROVIDER.verify(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("no expectedSha256");
|
||
});
|
||
it("读回 sha256 匹配 → ok true + actual=expected", async () => {
|
||
const exec = scriptedExec(() => ok(DD_PAYLOAD));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
plan.blockCount = 1;
|
||
const r = await DD_PROVIDER.verify(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.actual).toBe(DD_PAYLOAD_SHA);
|
||
});
|
||
it("读回 sha256 不匹配 → ok false + VERIFY FAILED", async () => {
|
||
const exec = scriptedExec(() => ok("different-content"));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
plan.blockCount = 1;
|
||
const r = await DD_PROVIDER.verify(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("VERIFY FAILED");
|
||
});
|
||
it("读回 exec 失败 → ok false + readback dd failed", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "io err" });
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
plan.blockCount = 1;
|
||
const r = await DD_PROVIDER.verify(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.reason).toContain("readback dd failed");
|
||
});
|
||
it("verify 命令用 count=blockCount(不变式)", async () => {
|
||
const exec = scriptedExec(() => ok(DD_PAYLOAD));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
plan.blockCount = 3;
|
||
await DD_PROVIDER.verify(plan, exec);
|
||
expect(exec.calls[0].args).toContain("count=3");
|
||
});
|
||
it("verify 无 blockCount → 默认 count=1(边界)", async () => {
|
||
const exec = scriptedExec(() => ok(DD_PAYLOAD));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
await DD_PROVIDER.verify(plan, exec);
|
||
expect(exec.calls[0].args).toContain("count=1");
|
||
});
|
||
it("verify 命令格式:dd if=<target> bs=4M count=<n>", async () => {
|
||
const exec = scriptedExec(() => ok(DD_PAYLOAD));
|
||
const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" });
|
||
plan.expectedSha256 = DD_PAYLOAD_SHA;
|
||
plan.blockCount = 2;
|
||
await DD_PROVIDER.verify(plan, exec);
|
||
expect(exec.calls[0].command).toBe("dd");
|
||
expect(exec.calls[0].args).toContain("if=/dev/mmcblk0");
|
||
expect(exec.calls[0].args).toContain("bs=4M");
|
||
expect(exec.calls[0].args).toContain("count=2");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// FASTBOOT / DFU / OPENOCD providers —— plan 等价类 + run 编排
|
||
// ============================================================================
|
||
|
||
describe("FASTBOOT_PROVIDER.plan — 等价类", () => {
|
||
it("带 partition → fastboot flash <part> <image>", () => {
|
||
const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "boot.img", target: "serial", partition: "boot" });
|
||
expect(p.commands).toEqual(["fastboot flash boot boot.img"]);
|
||
});
|
||
it("无 partition → fastboot flash <image>", () => {
|
||
const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "boot.img", target: "serial" });
|
||
expect(p.commands).toEqual(["fastboot flash boot.img"]);
|
||
});
|
||
it("partition 空白 → 视为无 partition", () => {
|
||
const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", partition: " " });
|
||
expect(p.commands).toEqual(["fastboot flash b.img"]);
|
||
});
|
||
it("image 空 → 抛错", () => {
|
||
expect(() => FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "", target: "s" })).toThrow(/image path required/);
|
||
});
|
||
it("target 空 → 抛错", () => {
|
||
expect(() => FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "i", target: "" })).toThrow(/target required/);
|
||
});
|
||
it("dryRun/verify 透传", () => {
|
||
const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b", target: "s", dryRun: false, verify: false });
|
||
expect(p.dryRun).toBe(false);
|
||
expect(p.verify).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("FASTBOOT_PROVIDER.run — 编排(dryOnly / 写 / verify)", () => {
|
||
it("dryRun 默认 → dryRun getvar all 探活,不写", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s" });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
expect(exec.calls[0].command).toBe("fastboot");
|
||
expect(exec.calls[0].args).toEqual(["getvar", "all"]);
|
||
});
|
||
it("dryRun:false + 写 + verify getvar all → ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([0]);
|
||
expect(r.verify?.ok).toBe(true);
|
||
expect(exec.calls.filter((c) => c.args.join(" ") === "getvar all").length).toBe(2);
|
||
});
|
||
it("dryRun 探活失败 → ok false + written false", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "no device" });
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s" });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.written).toBe(false);
|
||
expect(r.dryRun.reason).toContain("fastboot probe failed");
|
||
});
|
||
it("dryRun:false + 写失败 → 短路不调 verify(不变式)", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "fastboot" && args.join(" ") === "getvar all") return ok(); // 探活通过
|
||
return fail(1, "write fail"); // 写失败
|
||
});
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.ok).toBe(false);
|
||
expect(exec.calls).toHaveLength(2); // 探活(1) + 写(1), verify 不调
|
||
});
|
||
it("dryRun:false + verify:false → 跳过 verify", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false, verify: false });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.verify).toBeUndefined();
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe("DFU_PROVIDER.plan — 等价类", () => {
|
||
it("带 alt → dfu-util -d <target> -a <alt> -D <image>", () => {
|
||
const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", partition: "0" });
|
||
expect(p.commands).toEqual(["dfu-util -d 0483:df11 -a 0 -D fw.bin"]);
|
||
});
|
||
it("无 alt → dfu-util -d <target> -D <image>", () => {
|
||
const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" });
|
||
expect(p.commands).toEqual(["dfu-util -d 0483:df11 -D fw.bin"]);
|
||
});
|
||
it("image/target 空 → 抛错", () => {
|
||
expect(() => DFU_PROVIDER.plan({ method: "dfu", image: "", target: "t" })).toThrow();
|
||
expect(() => DFU_PROVIDER.plan({ method: "dfu", image: "i", target: "" })).toThrow();
|
||
});
|
||
it("partition 空白 → 视为无 alt", () => {
|
||
const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", partition: " " });
|
||
expect(p.commands).toEqual(["dfu-util -d 0483:df11 -D fw.bin"]);
|
||
});
|
||
});
|
||
|
||
describe("DFU_PROVIDER.run — 编排", () => {
|
||
it("dryRun 默认 → dfu-util -l 探活,不写", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" });
|
||
const r = await DFU_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
expect(exec.calls[0]).toEqual({ command: "dfu-util", args: ["-l"], opts: undefined });
|
||
});
|
||
it("dryRun:false → 写 + verify -l → ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", dryRun: false });
|
||
const r = await DFU_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.verify?.ok).toBe(true);
|
||
});
|
||
it("dryRun 探活失败 → ok false + written false", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "no dfu" });
|
||
const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" });
|
||
const r = await DFU_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.written).toBe(false);
|
||
expect(r.dryRun.reason).toContain("dfu probe failed");
|
||
});
|
||
it("dryRun:false + 写失败 → 短路不调 verify", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "dfu-util" && args.join(" ") === "-l") return ok();
|
||
return fail(1, "write err");
|
||
});
|
||
const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", dryRun: false });
|
||
const r = await DFU_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(exec.calls).toHaveLength(2); // 探活 + 写, verify 不调
|
||
});
|
||
});
|
||
|
||
describe("OPENOCD_PROVIDER.plan — 等价类", () => {
|
||
it("命令格式 openocd -f <cfg> -c \"program <image> verify reset exit\"", () => {
|
||
const p = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg" });
|
||
expect(p.commands).toEqual([`openocd -f stlink.cfg -c "program fw.bin verify reset exit"`]);
|
||
});
|
||
it("image/target 空 → 抛错", () => {
|
||
expect(() => OPENOCD_PROVIDER.plan({ method: "openocd", image: "", target: "c" })).toThrow();
|
||
expect(() => OPENOCD_PROVIDER.plan({ method: "openocd", image: "i", target: "" })).toThrow();
|
||
});
|
||
it("dryRun/verify 透传", () => {
|
||
const p = OPENOCD_PROVIDER.plan({ method: "openocd", image: "f", target: "c.cfg", dryRun: false, verify: false });
|
||
expect(p.dryRun).toBe(false);
|
||
expect(p.verify).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("OPENOCD_PROVIDER.run — 编排", () => {
|
||
it("dryRun 默认 → openocd init/exit 探活,不写", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg" });
|
||
const r = await OPENOCD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(true);
|
||
expect(r.written).toBe(false);
|
||
expect(exec.calls[0].args).toEqual(["-f", "stlink.cfg", "-c", "init", "-c", "exit"]);
|
||
});
|
||
it("dryRun:false → 写 program cmd + verify verify_image → ok true", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg", dryRun: false });
|
||
const r = await OPENOCD_PROVIDER.run(plan, exec);
|
||
expect(r.written).toBe(true);
|
||
expect(r.writeExitCodes).toEqual([0]);
|
||
expect(r.verify?.ok).toBe(true);
|
||
const writeCall = exec.calls.find((c) => c.args.some((a) => a.includes("program")));
|
||
expect(writeCall?.args).toContain("program fw.bin verify reset exit");
|
||
const verifyCall = exec.calls.find((c) => c.args.some((a) => a.includes("verify_image")));
|
||
expect(verifyCall).toBeTruthy();
|
||
});
|
||
it("verify 命令格式:openocd -f cfg -c verify_image <img> -c exit", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg", dryRun: false });
|
||
await OPENOCD_PROVIDER.run(plan, exec);
|
||
const vcall = exec.calls.find((c) => c.args.some((a) => a.startsWith("verify_image")));
|
||
expect(vcall?.args).toEqual(["-f", "st.cfg", "-c", "verify_image fw.bin", "-c", "exit"]);
|
||
});
|
||
it("dryRun 探活失败 → ok false + written false", async () => {
|
||
const exec = mockExec({ exitCode: 1, stderr: "jtag err" });
|
||
const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg" });
|
||
const r = await OPENOCD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(r.written).toBe(false);
|
||
expect(r.dryRun.reason).toContain("openocd probe failed");
|
||
});
|
||
it("dryRun:false + 写失败 → 短路不调 verify", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "openocd" && args.includes("init")) return ok(); // 探活通过
|
||
return fail(1, "write err");
|
||
});
|
||
const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg", dryRun: false });
|
||
const r = await OPENOCD_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
// 探活(1) + 写(1) = 2, verify 不调
|
||
expect(exec.calls).toHaveLength(2);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// DEFAULT_*_PROVIDERS —— 不变式(freeze → 篡改抛 TypeError / 覆盖完整性)
|
||
// ============================================================================
|
||
|
||
describe("DEFAULT_BOARD_LINK_PROVIDERS — 不变式:freeze + 覆盖完整性", () => {
|
||
it("含三 provider,id/linkType 全覆盖", () => {
|
||
expect(DEFAULT_BOARD_LINK_PROVIDERS).toHaveLength(3);
|
||
const ids = DEFAULT_BOARD_LINK_PROVIDERS.map((p) => p.id);
|
||
expect(ids).toEqual(["rdk-x5-ssh", "rdk-s100-serial", "local"]);
|
||
const linkTypes = DEFAULT_BOARD_LINK_PROVIDERS.map((p) => p.linkType);
|
||
expect(linkTypes).toEqual(["ssh", "serial", "local"]);
|
||
});
|
||
it("数组冻结:push 抛 TypeError(freeze→篡改抛 TypeError 不变式)", () => {
|
||
expect(() => (DEFAULT_BOARD_LINK_PROVIDERS as unknown as { push: (x: unknown) => void }).push({})).toThrow(TypeError);
|
||
});
|
||
it("数组冻结:索引赋值抛 TypeError", () => {
|
||
expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS as unknown as Record<number, unknown>)[0] = {})).toThrow(TypeError);
|
||
});
|
||
it("deepFreeze:篡改 provider.id 抛 TypeError(深冻结不变式)", () => {
|
||
expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS[0] as unknown as { id: string }).id = "MUTATED")).toThrow(TypeError);
|
||
});
|
||
it("deepFreeze:篡改 provider.linkType 抛 TypeError", () => {
|
||
expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS[0] as unknown as { linkType: string }).linkType = "wifi")).toThrow(TypeError);
|
||
});
|
||
it("批量注册到 registry 后 resolve 全可用", () => {
|
||
const reg = new BoardLinkRegistry();
|
||
DEFAULT_BOARD_LINK_PROVIDERS.forEach((p) => reg.register(p));
|
||
expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh");
|
||
expect(reg.resolve(serialBoard()).id).toBe("rdk-s100-serial");
|
||
expect(reg.resolve(localBoard()).id).toBe("local");
|
||
});
|
||
});
|
||
|
||
describe("DEFAULT_FLASH_PROVIDERS — 不变式:freeze + 覆盖完整性", () => {
|
||
it("含四 provider,id 全覆盖 dd/fastboot/dfu/openocd", () => {
|
||
expect(DEFAULT_FLASH_PROVIDERS).toHaveLength(4);
|
||
expect(DEFAULT_FLASH_PROVIDERS.map((p) => p.id)).toEqual(["dd", "fastboot", "dfu", "openocd"]);
|
||
});
|
||
it("数组冻结:push 抛 TypeError", () => {
|
||
expect(() => (DEFAULT_FLASH_PROVIDERS as unknown as { push: (x: unknown) => void }).push({})).toThrow(TypeError);
|
||
});
|
||
it("数组冻结:索引赋值抛 TypeError", () => {
|
||
expect(() => ((DEFAULT_FLASH_PROVIDERS as unknown as Record<number, unknown>)[0] = {})).toThrow(TypeError);
|
||
});
|
||
it("deepFreeze:篡改 provider.id 抛 TypeError(深冻结不变式)", () => {
|
||
expect(() => ((DEFAULT_FLASH_PROVIDERS[0] as unknown as { id: string }).id = "MUTATED")).toThrow(TypeError);
|
||
});
|
||
it("批量注册到 registry 后 resolve 全可用", () => {
|
||
const reg = new FlashRegistry();
|
||
DEFAULT_FLASH_PROVIDERS.forEach((p) => reg.register(p));
|
||
for (const m of ["dd", "fastboot", "dfu", "openocd"] as FlashMethod[]) {
|
||
expect(reg.resolve(m).id).toBe(m);
|
||
}
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 元蜕变/不变式:跨变换保持的性质
|
||
// ============================================================================
|
||
|
||
describe("元蜕变/不变式:跨变换保持的性质", () => {
|
||
it("BoardLinkRegistry 与 FlashRegistry disposer 语义对称(单调)", () => {
|
||
const bl = new BoardLinkRegistry();
|
||
const fl = new FlashRegistry();
|
||
bl.register(RDK_X5_SSH_PROVIDER);
|
||
fl.register(DD_PROVIDER);
|
||
expect(bl.list()).toHaveLength(1);
|
||
expect(fl.list()).toHaveLength(1);
|
||
(bl.list() as unknown[]).push({} as never);
|
||
expect(fl.list()).toHaveLength(1);
|
||
expect(bl.list()).toHaveLength(1);
|
||
});
|
||
|
||
it("fail-closed 单调:未显式 dryRun:false → 永不 written=true(跨四 provider)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
for (const provider of [DD_PROVIDER, FASTBOOT_PROVIDER, DFU_PROVIDER, OPENOCD_PROVIDER]) {
|
||
const plan = provider.plan({ method: provider.id as FlashMethod, image: "i", target: "/dev/x" });
|
||
const r = await provider.run(plan, exec);
|
||
expect(r.written).toBe(false);
|
||
}
|
||
});
|
||
|
||
it("append 两次 = replay 等价:两次 plan 同输入产同命令(元蜕变)", () => {
|
||
const opts = { method: "dd" as FlashMethod, image: "img", target: "/dev/mmcblk0" };
|
||
const p1 = DD_PROVIDER.plan(opts);
|
||
const p2 = DD_PROVIDER.plan(opts);
|
||
expect(p1.commands).toEqual(p2.commands);
|
||
expect(p1.offsetBytes).toBe(p2.offsetBytes);
|
||
});
|
||
|
||
it("freeze→篡改抛 TypeError:DEFAULT_FLASH_PROVIDERS 内每个 provider 不可改", () => {
|
||
for (const p of DEFAULT_FLASH_PROVIDERS) {
|
||
expect(() => ((p as unknown as { id: string }).id = "x")).toThrow(TypeError);
|
||
}
|
||
});
|
||
|
||
it("freeze→篡改抛 TypeError:DEFAULT_BOARD_LINK_PROVIDERS 内每个 provider 不可改", () => {
|
||
for (const p of DEFAULT_BOARD_LINK_PROVIDERS) {
|
||
expect(() => ((p as unknown as { id: string }).id = "x")).toThrow(TypeError);
|
||
}
|
||
});
|
||
|
||
it("waterfall 不调 next=短路:写失败后 verify 永不调用(跨 provider)", async () => {
|
||
const exec = scriptedExec((cmd, args) => {
|
||
if (cmd === "fastboot" && args.join(" ") === "getvar all") return ok();
|
||
return fail(1, "write err");
|
||
});
|
||
const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b", target: "s", dryRun: false });
|
||
const r = await FASTBOOT_PROVIDER.run(plan, exec);
|
||
expect(r.ok).toBe(false);
|
||
expect(exec.calls).toHaveLength(2); // 探活(1) + 写(1), verify 不调
|
||
});
|
||
|
||
it("不变式:list() 返回的快照 mutate 不影响 resolve(隔离)", () => {
|
||
const reg = new FlashRegistry();
|
||
reg.register(DD_PROVIDER);
|
||
const snap = reg.list();
|
||
(snap as unknown[]).length = 0; // mutate snapshot
|
||
expect(reg.list()).toHaveLength(1);
|
||
expect(reg.resolve("dd").id).toBe("dd");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 变异测试 —— 7 个 seeded bug 内联副本,每个被某条真实测试杀死
|
||
// ============================================================================
|
||
//
|
||
// 每个 mutant 是真实逻辑的"单点变异"内联副本。我们对每个 mutant 做两层验证:
|
||
// ① 偏离验证:断言 mutant 输出 ≠ 真实输出(mutant 确实改变了行为)
|
||
// ② kill verification:把 mutant 喂给与真实代码完全相同的断言(expect(...).toBe(...)),
|
||
// 断言该断言抛错(即 mutant 在真实测试下 FAIL → bug 被杀)。
|
||
// 套件本身保持全绿(mutant 测试断言 mutant 确实偏离/确实 FAIL,而非断言 mutant 对)。
|
||
// 每个 mutant 标注:变异点 + 杀它的真实测试名。
|
||
|
||
// --- M1: parseOffset hex 守卫 >= 0 → > 0(丢掉 0x0,off-by-one)---
|
||
// 杀它的真实测试:parseOffset("0x0") → 0(见 "parseOffset — 等价类/边界值")
|
||
function parseOffsetMutantM1(offset: string | undefined): number | null {
|
||
if (offset === undefined || offset === "") return 0;
|
||
const trimmed = offset.trim();
|
||
if (/^0x[0-9a-fA-F]+$/.test(trimmed)) {
|
||
const n = Number(trimmed);
|
||
if (Number.isFinite(n) && n > 0) return n; // BUG: >= 0 → > 0
|
||
return null;
|
||
}
|
||
if (/^\d+$/.test(trimmed)) {
|
||
try {
|
||
const big = BigInt(trimmed);
|
||
if (big > BigInt(Number.MAX_SAFE_INTEGER)) return Number.MAX_SAFE_INTEGER;
|
||
return Number(big);
|
||
} catch { return null; }
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// --- M2: buildSshArgs 端口判断 !== 22 → === 22(-p 逻辑反)---
|
||
// 杀它的真实测试:buildSshArgs 非 22 端口带 -p / 22 端口不带 -p(见 "buildSshArgs — 决策表")
|
||
function buildSshArgsMutantM2(board: BoardSpec, command: string, args: string[]): string[] {
|
||
const { user, host, port } = parseSshAddress(board.address);
|
||
const sshArgs: string[] = [];
|
||
if (port === 22) sshArgs.push("-p", String(port)); // BUG: port !== 22 → port === 22
|
||
sshArgs.push(`${user}@${host}`);
|
||
sshArgs.push(command);
|
||
sshArgs.push(...args);
|
||
return sshArgs;
|
||
}
|
||
|
||
// --- M3: orchestrateRun dryRun 默认 !== false → === false(fail-closed 默认反转)---
|
||
// 杀它的真实测试:orchestrateRun dryRun undefined → written false(见 "orchestrateRun — 状态转换/决策表")
|
||
async function orchestrateRunMutantM3(
|
||
plan: FlashPlanEx,
|
||
exec: ExecFn,
|
||
dryRunFn: (p: FlashPlanEx, e: ExecFn) => Promise<DryRunResult>,
|
||
verifyFn: (p: FlashPlanEx, e: ExecFn) => Promise<VerifyResult>,
|
||
): Promise<{ written: boolean; ok: boolean }> {
|
||
const dr = await dryRunFn(plan, exec);
|
||
if (!dr.ok) return { written: false, ok: false };
|
||
const dryOnly = plan.dryRun === false; // BUG: !== false → === false
|
||
if (dryOnly) return { written: false, ok: true };
|
||
const writeExitCodes: number[] = [];
|
||
for (const cmdStr of plan.commands) {
|
||
const parts = splitCommand(cmdStr);
|
||
const res = await exec(parts[0], parts.slice(1));
|
||
writeExitCodes.push(res.exitCode);
|
||
if (res.exitCode !== 0) return { written: true, ok: false };
|
||
}
|
||
const vr = plan.verify === false ? undefined : await verifyFn(plan, exec);
|
||
return { written: true, ok: vr ? vr.ok : true };
|
||
}
|
||
|
||
// --- M4: parseLsblk cols.length < 3 → < 2(接受畸形 2 列行)---
|
||
// 杀它的真实测试:parseLsblk 2 列行被跳过(见 "parseLsblk — 等价类/边界值")
|
||
function parseLsblkMutantM4(raw: string): LsblkRow[] {
|
||
const lines = raw.split("\n");
|
||
const rows: LsblkRow[] = [];
|
||
let started = false;
|
||
const LSBLK_TREE_CHARS = /[─-╼│├└─\s]+/;
|
||
for (const line of lines) {
|
||
if (!line.trim()) continue;
|
||
if (!started) {
|
||
if (/^NAME/i.test(line.trim())) { started = true; continue; }
|
||
}
|
||
const cleaned = line.replace(LSBLK_TREE_CHARS, " ").trim();
|
||
if (!cleaned) continue;
|
||
const cols = cleaned.split(/\s+/);
|
||
if (cols.length < 2) continue; // BUG: < 3 → < 2
|
||
const name = cols[0] ?? "";
|
||
const size = Number.parseInt(cols[1] ?? "0", 10);
|
||
rows.push({ name, size: Number.isFinite(size) ? size : 0, type: cols[2] ?? "", mountpoint: cols.slice(3).join(" ") ?? "" });
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
// --- M5: isRootDiskTarget 用 startsWith 替代 matchesDeviceName(前缀误匹配)---
|
||
// 杀它的真实测试:isRootDiskTarget 前缀碰撞 sdab 不匹配 sda(见 "isRootDiskTarget — 决策表")
|
||
function isRootDiskTargetMutantM5(target: string, rows: LsblkRow[]): boolean {
|
||
const base = deviceBasename(target);
|
||
for (const row of rows) {
|
||
if (row.name.startsWith(base)) { // BUG: matchesDeviceName(base, row.name) → row.name.startsWith(base)
|
||
if (row.mountpoint && ROOT_MOUNTPOINTS.has(row.mountpoint)) {
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// --- M6: splitCommand `if (cur || hadQuote)` → `if (cur)`(丢空引号 token)---
|
||
// 杀它的真实测试:splitCommand('a -c ""') → ["a", "-c", ""](见 "splitCommand — 等价类/边界/对抗")
|
||
function splitCommandMutantM6(cmdStr: string): string[] {
|
||
const tokens: string[] = [];
|
||
let cur = "";
|
||
let inQuote = false;
|
||
let hadQuote = false;
|
||
for (let i = 0; i < cmdStr.length; i++) {
|
||
const ch = cmdStr[i];
|
||
if (ch === '"') {
|
||
inQuote = !inQuote;
|
||
hadQuote = true;
|
||
continue;
|
||
}
|
||
if (ch === " " && !inQuote) {
|
||
if (cur) tokens.push(cur); // BUG: cur || hadQuote → cur (drops empty quoted tokens)
|
||
cur = "";
|
||
hadQuote = false;
|
||
continue;
|
||
}
|
||
cur += ch;
|
||
}
|
||
if (cur) tokens.push(cur); // BUG: cur || hadQuote → cur
|
||
return tokens;
|
||
}
|
||
|
||
// --- M7: deviceBasename regex `/\/dev\/(.+)$/` → `/\/dev\/(.+).$/`(吞末字符)---
|
||
// 杀它的真实测试:deviceBasename("/dev/sda1") → "sda1"(见 "deviceBasename — 等价类/边界")
|
||
function deviceBasenameMutantM7(target: string): string {
|
||
const m = target.match(/\/dev\/(.+).$/); // BUG: /\/dev\/(.+)$/ → /\/dev\/(.+).$/ (drops last char)
|
||
return m ? m[1] : target.replace(/^\/+/, "");
|
||
}
|
||
|
||
/** orchestrateRun 的小 shim,仅暴露 written/ok 给 M3 对比(真实实现)。 */
|
||
async function orchestrateRunShim(
|
||
plan: FlashPlanEx,
|
||
exec: ExecFn,
|
||
dryRunFn: (p: FlashPlanEx, e: ExecFn) => Promise<DryRunResult>,
|
||
verifyFn: (p: FlashPlanEx, e: ExecFn) => Promise<VerifyResult>,
|
||
): Promise<{ written: boolean; ok: boolean }> {
|
||
const r = await orchestrateRun(plan, exec, dryRunFn, verifyFn);
|
||
return { written: r.written, ok: r.ok };
|
||
}
|
||
|
||
describe("变异测试 — seeded bug 被【真实测试】杀死(偏离验证)", () => {
|
||
// M1: parseOffset hex 守卫 >=0→>0,丢掉 0x0
|
||
it("M1 [parseOffset hex 守卫 >=0→>0]:mutant 把 0x0 返回 null,偏离真实 0", () => {
|
||
const real = parseOffset("0x0");
|
||
const mutant = parseOffsetMutantM1("0x0");
|
||
expect(real).toBe(0);
|
||
expect(mutant).toBeNull();
|
||
expect(mutant).not.toBe(real);
|
||
});
|
||
|
||
// M2: buildSshArgs port !==22→===22
|
||
it("M2 [buildSshArgs port !==22→===22]:mutant 在非 22 端口漏 -p,偏离真实", () => {
|
||
const board = sshBoard("x5", "root@192.168.1.100:2222");
|
||
const real = buildSshArgs(board, "ls", ["-la"]);
|
||
const mutant = buildSshArgsMutantM2(board, "ls", ["-la"]);
|
||
expect(real).toContain("-p");
|
||
expect(mutant).not.toContain("-p");
|
||
expect(mutant).not.toEqual(real);
|
||
});
|
||
it("M2 反向:mutant 在 22 端口误加 -p,偏离真实", () => {
|
||
const board = sshBoard("x5", "root@192.168.1.100:22");
|
||
const real = buildSshArgs(board, "ls", []);
|
||
const mutant = buildSshArgsMutantM2(board, "ls", []);
|
||
expect(real).not.toContain("-p");
|
||
expect(mutant).toContain("-p");
|
||
expect(mutant).not.toEqual(real);
|
||
});
|
||
|
||
// M3: orchestrateRun dryRun !==false→===false
|
||
it("M3 [orchestrateRun dryRun !==false→===false]:mutant 在 dryRun undefined 时 written=true,违反 fail-closed", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = planEx({ dryRun: undefined });
|
||
const realR = await orchestrateRunShim(plan, exec, dryOk, verifyOk);
|
||
const mutantR = await orchestrateRunMutantM3(plan, exec, dryOk, verifyOk);
|
||
expect(realR.written).toBe(false);
|
||
expect(mutantR.written).toBe(true);
|
||
expect(mutantR.written).not.toBe(realR.written);
|
||
});
|
||
|
||
// M4: parseLsblk cols<3→<2
|
||
it("M4 [parseLsblk cols<3→<2]:mutant 接受 2 列畸形行,偏离真实空数组", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G";
|
||
const real = parseLsblk(raw);
|
||
const mutant = parseLsblkMutantM4(raw);
|
||
expect(real).toEqual([]);
|
||
expect(mutant).toHaveLength(1);
|
||
expect(mutant).not.toEqual(real);
|
||
});
|
||
|
||
// M5: isRootDiskTarget startsWith 替代 matchesDeviceName
|
||
it("M5 [isRootDiskTarget startsWith→matchesDeviceName]:mutant 前缀误匹配 sdab→sda,偏离真实 false", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "sda", size: 1, type: "disk", mountpoint: "" },
|
||
{ name: "sdab", size: 1, type: "disk", mountpoint: "/" },
|
||
];
|
||
const real = isRootDiskTarget("/dev/sda", rows);
|
||
const mutant = isRootDiskTargetMutantM5("/dev/sda", rows);
|
||
expect(real).toBe(false);
|
||
expect(mutant).toBe(true);
|
||
expect(mutant).not.toBe(real);
|
||
});
|
||
|
||
// M6: splitCommand cur||hadQuote → cur
|
||
it("M6 [splitCommand cur||hadQuote→cur]:mutant 丢空引号 token,偏离真实", () => {
|
||
const real = splitCommand('a -c ""');
|
||
const mutant = splitCommandMutantM6('a -c ""');
|
||
expect(real).toEqual(["a", "-c", ""]);
|
||
expect(mutant).toEqual(["a", "-c"]); // 丢了空串 token
|
||
expect(mutant).not.toEqual(real);
|
||
});
|
||
|
||
// M7: deviceBasename regex 吞末字符
|
||
it("M7 [deviceBasename regex 吞末字符]:mutant 把 sda1 变 sda,偏离真实", () => {
|
||
const real = deviceBasename("/dev/sda1");
|
||
const mutant = deviceBasenameMutantM7("/dev/sda1");
|
||
expect(real).toBe("sda1");
|
||
expect(mutant).toBe("sda"); // 吞了末尾 '1'
|
||
expect(mutant).not.toBe(real);
|
||
});
|
||
});
|
||
|
||
describe("变异测试 — kill verification(每个 mutant 通过真实断言确认 FAIL)", () => {
|
||
// M1 kill: 真实测试 expect(parseOffset("0x0")).toBe(0) 在 mutant 上应 FAIL
|
||
it("M1 kill: expect(parseOffset('0x0')).toBe(0) fails on mutant (returns null)", () => {
|
||
expect(parseOffset("0x0")).toBe(0); // 真实通过
|
||
expect(() => expect(parseOffsetMutantM1("0x0")).toBe(0)).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M2 kill: 真实测试 expect(buildSshArgs(board,'ls',['-la'])).toContain('-p') 在 mutant 上应 FAIL
|
||
it("M2 kill: expect(buildSshArgs(non-22,'ls')).toContain('-p') fails on mutant", () => {
|
||
const board = sshBoard("x5", "root@192.168.1.100:2222");
|
||
expect(buildSshArgs(board, "ls", ["-la"])).toContain("-p"); // 真实通过
|
||
expect(() => expect(buildSshArgsMutantM2(board, "ls", ["-la"])).toContain("-p")).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M3 kill: 真实测试 expect(orchestrateRun(dryRun:undefined).written).toBe(false) 在 mutant 上应 FAIL
|
||
it("M3 kill: expect(orchestrateRun(dryRun:undefined).written).toBe(false) fails on mutant (writes)", async () => {
|
||
const exec = mockExec({ exitCode: 0 });
|
||
const plan = planEx({ dryRun: undefined });
|
||
const realR = await orchestrateRunShim(plan, exec, dryOk, verifyOk);
|
||
expect(realR.written).toBe(false); // 真实通过
|
||
const mutantR = await orchestrateRunMutantM3(plan, exec, dryOk, verifyOk);
|
||
expect(() => expect(mutantR.written).toBe(false)).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M4 kill: 真实测试 expect(parseLsblk('..sda 500G')).toEqual([]) 在 mutant 上应 FAIL
|
||
it("M4 kill: expect(parseLsblk('sda 500G')).toEqual([]) fails on mutant (accepts row)", () => {
|
||
const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G";
|
||
expect(parseLsblk(raw)).toEqual([]); // 真实通过
|
||
expect(() => expect(parseLsblkMutantM4(raw)).toEqual([])).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M5 kill: 真实测试 expect(isRootDiskTarget('/dev/sda', sdab-rows)).toBe(false) 在 mutant 上应 FAIL
|
||
it("M5 kill: expect(isRootDiskTarget('/dev/sda', sdab-rows)).toBe(false) fails on mutant (prefix match)", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "sda", size: 1, type: "disk", mountpoint: "" },
|
||
{ name: "sdab", size: 1, type: "disk", mountpoint: "/" },
|
||
];
|
||
expect(isRootDiskTarget("/dev/sda", rows)).toBe(false); // 真实通过
|
||
expect(() => expect(isRootDiskTargetMutantM5("/dev/sda", rows)).toBe(false)).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M6 kill: 真实测试 expect(splitCommand('a -c ""')).toEqual(["a","-c",""]) 在 mutant 上应 FAIL
|
||
it("M6 kill: expect(splitCommand('a -c \"\"')).toEqual([...,'']) fails on mutant (drops empty token)", () => {
|
||
expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]); // 真实通过
|
||
expect(() => expect(splitCommandMutantM6('a -c ""')).toEqual(["a", "-c", ""])).toThrow(); // mutant FAIL
|
||
});
|
||
|
||
// M7 kill: 真实测试 expect(deviceBasename('/dev/sda1')).toBe('sda1') 在 mutant 上应 FAIL
|
||
it("M7 kill: expect(deviceBasename('/dev/sda1')).toBe('sda1') fails on mutant (drops last char)", () => {
|
||
expect(deviceBasename("/dev/sda1")).toBe("sda1"); // 真实通过
|
||
expect(() => expect(deviceBasenameMutantM7("/dev/sda1")).toBe("sda1")).toThrow(); // mutant FAIL
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 真实代码全绿确认(不变式:所有上方测试断言真实行为,mutant 只断言偏离)
|
||
// ============================================================================
|
||
describe("真实代码全绿确认(meta-check)", () => {
|
||
it("parseOffset 0x0 真实返回 0(非 null)", () => {
|
||
expect(parseOffset("0x0")).toBe(0);
|
||
});
|
||
it("buildSshArgs 非 22 端口真实带 -p", () => {
|
||
expect(buildSshArgs(sshBoard("x5", "root@h:2222"), "ls", [])).toContain("-p");
|
||
});
|
||
it("orchestrateRun dryRun undefined 真实 written=false", async () => {
|
||
const r = await orchestrateRunShim(planEx({ dryRun: undefined }), mockExec({ exitCode: 0 }), dryOk, verifyOk);
|
||
expect(r.written).toBe(false);
|
||
});
|
||
it("parseLsblk 2 列行真实跳过", () => {
|
||
expect(parseLsblk("NAME SIZE TYPE MOUNTPOINT\nsda 500G")).toEqual([]);
|
||
});
|
||
it("isRootDiskTarget 前缀碰撞真实 false", () => {
|
||
const rows: LsblkRow[] = [
|
||
{ name: "sda", size: 1, type: "disk", mountpoint: "" },
|
||
{ name: "sdab", size: 1, type: "disk", mountpoint: "/" },
|
||
];
|
||
expect(isRootDiskTarget("/dev/sda", rows)).toBe(false);
|
||
});
|
||
it("splitCommand 空引号 token 真实保留", () => {
|
||
expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]);
|
||
});
|
||
it("deviceBasename 真实不吞末字符", () => {
|
||
expect(deviceBasename("/dev/sda1")).toBe("sda1");
|
||
});
|
||
});
|