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>
1994 lines
74 KiB
TypeScript
1994 lines
74 KiB
TypeScript
/**
|
||
* @module doc-sync.test
|
||
*
|
||
* T10 —— CI 质量门三件套(doc-sync / e2e-snapshot / DEFAULT_DOC_ANCHORS)
|
||
* 完整测试套件(多方法论、测试前置、严到植入 bug 活不过)。
|
||
*
|
||
* 被测对象(命名导出,按契约直接 import,mock 注入依赖):
|
||
* scripts/doc-sync.ts → checkDocSync / DEFAULT_DOC_ANCHORS /
|
||
* defaultReadFile / defaultGrepSymbol
|
||
* (类型契约 DocAnchor / DocSyncMismatch /
|
||
* DocSyncResult / ReadFile / GrepSymbol)
|
||
* scripts/e2e-snapshot.ts → compareSnapshot
|
||
* (类型契约 SnapshotDiff)
|
||
* .github/workflows/ci.yml → 契约:quality-gate job 调 checkDocSync 走
|
||
* per-file 100% 覆盖门 + tsc + doc-sync;
|
||
* type-drift job 周期跑(本套件只测它调的纯函数,
|
||
* 不测 IO 装配细节)。
|
||
*
|
||
* 依赖注入:readFile / grepSymbol 全 mock;无 pi 运行时 / 无硬件 / 无网络。
|
||
* defaultReadFile / defaultGrepSymbol 用本仓稳定文件做轻量真 fs 集成
|
||
* (钉住 CI 装配契约:缺文件抛错、命中返回 1-indexed 行号)。
|
||
*
|
||
* 测试方法论(每个 describe 块标注方法论名):
|
||
* - 等价类划分(有效 / 无效 / 边界类)
|
||
* - 边界值分析(off-by-one / 空 / 单元素 / min / max / 越界)
|
||
* - 决策表(双侧组合输入 → 期望,覆盖全分支)
|
||
* - 状态转换(fail-closed 优先序链 + 短路 + 不可达态 + 重入)
|
||
* - 变异测试:8 个 seeded bug 内联副本(faithful copy + 恰好一处变异),
|
||
* 每个 it 断言:真代码满足 spec 谓词、buggy 副本违反 spec 谓词、
|
||
* 且 `expect(() => expect(buggyResult).toBe(期望)).toThrow()`
|
||
* 字面演示「拿 buggy 当 SUT 跑同一 spec 断言必抛 AssertionError」
|
||
* = 该 spec 单独跑 buggy 变体时 FAIL = bug 被杀。
|
||
* - 对抗 / fuzz(null / undefined / 巨大 / NaN / Infinity / 循环引用 /
|
||
* 负行号 / 空符号 / 并发重入 / 非整数行号)
|
||
* - 元蜕变 / 不变式(自反 / 对称 / 传递 / 单调 / 确定性 / 升序 /
|
||
* freeze→篡改抛 TypeError / waterfall 短路 / fail-closed unusable=拒 /
|
||
* append 两次=replay 等价)
|
||
*
|
||
* 门:
|
||
* 1. npx vitest run tests/doc-sync.test.ts # 真实代码 all green
|
||
* 2. 每个 seeded bug 变体:spec 谓词在 buggy 副本上为 false(bug 被杀)——
|
||
* 本套件用 `expect(() => expect(buggy...).toBe(...)).toThrow()` 字面验证。
|
||
*
|
||
* 真实 bug(非植入):当前源码未发现真实缺陷(serializeLeaf 的 -0 / symbol /
|
||
* bigint 特判均已落地且经正向 it 钉住;见 StructuredOutput findings 为空)。
|
||
*
|
||
* 见架构设计文档_v3.md §5.9(CI 质量门:doc-sync 文档门 + 真实 API snapshot)。
|
||
*/
|
||
|
||
import { describe, it, expect } from "vitest";
|
||
import {
|
||
checkDocSync,
|
||
DEFAULT_DOC_ANCHORS,
|
||
defaultReadFile,
|
||
defaultGrepSymbol,
|
||
} from "../scripts/doc-sync.js";
|
||
import type {
|
||
DocAnchor,
|
||
DocSyncResult,
|
||
ReadFile,
|
||
GrepSymbol,
|
||
} from "../scripts/doc-sync.js";
|
||
import { compareSnapshot } from "../scripts/e2e-snapshot.js";
|
||
import type { SnapshotDiff } from "../scripts/e2e-snapshot.js";
|
||
|
||
// ============================================================================
|
||
// 工具:构造可注入的 readFile / grepSymbol / anchor
|
||
// ============================================================================
|
||
|
||
/**
|
||
* 按行表构造 readFile:lineTable[path] = 文本。
|
||
* 缺省返回 ""(模拟空文件 / 不可读占位,不抛——抛错用 throwingReader)。
|
||
*/
|
||
function readerFrom(lineTable: Record<string, string>): ReadFile {
|
||
return (p) => lineTable[p] ?? "";
|
||
}
|
||
|
||
/**
|
||
* 按「file:symbol → 行号」表构造 grepSymbol;缺省 -1(未命中)。
|
||
* 显式表驱动,杜绝 defaultGrepSymbol 的子串巧合,让 grep 行为完全确定。
|
||
*/
|
||
function greperFrom(table: Record<string, number>): GrepSymbol {
|
||
return (file, symbol) => table[`${file}:${symbol}`] ?? -1;
|
||
}
|
||
|
||
/** 一抛即抛的 readFile,用于 fail-closed 注入。 */
|
||
function throwingReader(msg = "ENOENT"): ReadFile {
|
||
return () => {
|
||
throw new Error(msg);
|
||
};
|
||
}
|
||
|
||
/** 构造一条锚点(默认全字段合法,调用方可覆盖任意字段)。 */
|
||
function anchor(over: Partial<DocAnchor> = {}): DocAnchor {
|
||
return {
|
||
docFile: "doc.md",
|
||
docLine: 2,
|
||
codeFile: "src/core/tool-pipeline.ts",
|
||
codeSymbol: "ToolPipeline",
|
||
...over,
|
||
};
|
||
}
|
||
|
||
// ============================================================================
|
||
// 变异测试:seeded bug 内联副本(faithful copy,仅一处变异)
|
||
// ============================================================================
|
||
//
|
||
// 每个变体是「真实逻辑的逐行忠实副本」+ 恰好一处变异。下方「变异测试」
|
||
// describe 对每个变体断言:
|
||
// (a) 真代码满足 spec 谓词;
|
||
// (b) buggy 副本违反 spec 谓词;
|
||
// (c) 字面演示:`expect(() => expect(buggyResult).toBe(期望)).toThrow()` ——
|
||
// 即「拿 buggy 当 SUT 跑同一 spec 断言必抛 AssertionError」,等价于
|
||
// 「该 spec 单独跑 buggy 变体时 FAIL」= bug 被杀。
|
||
|
||
/**
|
||
* MUTATION M1 —— checkDocSync:`codeLine <= 0` 改 `codeLine < 0`。
|
||
* 后果:grepSymbol 返回 0(非法行号)被当「命中」放行,破坏 fail-closed。
|
||
* 杀它的测试:grep 返回 0 须 mismatch(fail-closed)。
|
||
*/
|
||
function checkDocSync_bug_ltLeq(opts: {
|
||
readFile: ReadFile;
|
||
anchors: readonly DocAnchor[];
|
||
grepSymbol: GrepSymbol;
|
||
}): DocSyncResult {
|
||
const { readFile, anchors, grepSymbol } = opts;
|
||
const mismatches: DocSyncResult["mismatches"][number][] = [];
|
||
for (const a of anchors) {
|
||
let docText: string;
|
||
try {
|
||
docText = readFile(a.docFile);
|
||
} catch {
|
||
mismatches.push({ anchor: a, reason: `doc file not readable: ${a.docFile}` });
|
||
continue;
|
||
}
|
||
const docLines = docText.split("\n");
|
||
const docLine = docLines[a.docLine - 1];
|
||
if (docLine === undefined) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`,
|
||
});
|
||
continue;
|
||
}
|
||
if (!docLine.includes(a.codeFile)) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`,
|
||
});
|
||
continue;
|
||
}
|
||
let codeLine: number;
|
||
try {
|
||
codeLine = grepSymbol(a.codeFile, a.codeSymbol);
|
||
} catch {
|
||
mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` });
|
||
continue;
|
||
}
|
||
// MUTATION: `<= 0` → `< 0`
|
||
if (codeLine < 0) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`,
|
||
});
|
||
}
|
||
}
|
||
return { ok: mismatches.length === 0, mismatches };
|
||
}
|
||
|
||
/**
|
||
* MUTATION M2 —— checkDocSync:行索引 off-by-one,
|
||
* `docLines[docLine - 1]` 改 `docLines[docLine]`。
|
||
* 后果:docLine=1 读到第 2 行而非第 1 行,错位一行;锚点对齐校验形同虚设。
|
||
* 杀它的测试:docLine=1 须读首行(含 codeFile)→ ok=true。
|
||
*/
|
||
function checkDocSync_bug_offByOne(opts: {
|
||
readFile: ReadFile;
|
||
anchors: readonly DocAnchor[];
|
||
grepSymbol: GrepSymbol;
|
||
}): DocSyncResult {
|
||
const { readFile, anchors, grepSymbol } = opts;
|
||
const mismatches: DocSyncResult["mismatches"][number][] = [];
|
||
for (const a of anchors) {
|
||
let docText: string;
|
||
try {
|
||
docText = readFile(a.docFile);
|
||
} catch {
|
||
mismatches.push({ anchor: a, reason: `doc file not readable: ${a.docFile}` });
|
||
continue;
|
||
}
|
||
const docLines = docText.split("\n");
|
||
// MUTATION: `a.docLine - 1` → `a.docLine`
|
||
const docLine = docLines[a.docLine];
|
||
if (docLine === undefined) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`,
|
||
});
|
||
continue;
|
||
}
|
||
if (!docLine.includes(a.codeFile)) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`,
|
||
});
|
||
continue;
|
||
}
|
||
let codeLine: number;
|
||
try {
|
||
codeLine = grepSymbol(a.codeFile, a.codeSymbol);
|
||
} catch {
|
||
mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` });
|
||
continue;
|
||
}
|
||
if (codeLine <= 0) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`,
|
||
});
|
||
}
|
||
}
|
||
return { ok: mismatches.length === 0, mismatches };
|
||
}
|
||
|
||
/**
|
||
* MUTATION M3 —— checkDocSync:docFile 读抛错时静默吞掉(catch 内不 push
|
||
* mismatch,仅 continue)。
|
||
* 后果:不可读文档不再 fail-closed,锚点静默通过,文档门失守。
|
||
* 杀它的测试:docFile 不可读 须 mismatch(ok=false)。
|
||
*/
|
||
function checkDocSync_bug_swallowRead(opts: {
|
||
readFile: ReadFile;
|
||
anchors: readonly DocAnchor[];
|
||
grepSymbol: GrepSymbol;
|
||
}): DocSyncResult {
|
||
const { readFile, anchors, grepSymbol } = opts;
|
||
const mismatches: DocSyncResult["mismatches"][number][] = [];
|
||
for (const a of anchors) {
|
||
let docText: string;
|
||
try {
|
||
docText = readFile(a.docFile);
|
||
} catch {
|
||
// MUTATION: 漏 push mismatch(静默吞错,放行)
|
||
continue;
|
||
}
|
||
const docLines = docText.split("\n");
|
||
const docLine = docLines[a.docLine - 1];
|
||
if (docLine === undefined) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`,
|
||
});
|
||
continue;
|
||
}
|
||
if (!docLine.includes(a.codeFile)) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`,
|
||
});
|
||
continue;
|
||
}
|
||
let codeLine: number;
|
||
try {
|
||
codeLine = grepSymbol(a.codeFile, a.codeSymbol);
|
||
} catch {
|
||
mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` });
|
||
continue;
|
||
}
|
||
if (codeLine <= 0) {
|
||
mismatches.push({
|
||
anchor: a,
|
||
reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`,
|
||
});
|
||
}
|
||
}
|
||
return { ok: mismatches.length === 0, mismatches };
|
||
}
|
||
|
||
/**
|
||
* 内部副本:serializeLeaf 系列(faithful copy,供下方变异变体复用)。
|
||
* 与 scripts/e2e-snapshot.ts 的 serializeLeaf 逐行一致(含 -0/symbol/bigint 特判)。
|
||
*/
|
||
function serializeLeafFaithful(value: unknown): string {
|
||
if (value === undefined) return "undefined";
|
||
if (typeof value === "function") return "function";
|
||
if (typeof value === "symbol") return "symbol";
|
||
if (typeof value === "bigint") return `bigint:${value}`;
|
||
if (typeof value === "number") {
|
||
if (Object.is(value, -0)) return "-0";
|
||
if (Number.isNaN(value)) return "NaN";
|
||
if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
|
||
}
|
||
const serialized = JSON.stringify(value);
|
||
return serialized === undefined ? "undefined" : serialized;
|
||
}
|
||
|
||
function isPlainObjectFaithful(value: object): boolean {
|
||
const proto = Object.getPrototypeOf(value);
|
||
return proto === null || proto === Object.prototype;
|
||
}
|
||
|
||
function joinPathFaithful(prefix: string, segment: string): string {
|
||
return prefix === "" ? segment : `${prefix}.${segment}`;
|
||
}
|
||
|
||
function flattenFaithful(value: unknown, prefix: string, out: Map<string, string>): void {
|
||
if (value === null || typeof value !== "object") {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (value.length === 0) {
|
||
out.set(prefix, "[]");
|
||
return;
|
||
}
|
||
for (let i = 0; i < value.length; i++) {
|
||
flattenFaithful(value[i], joinPathFaithful(prefix, String(i)), out);
|
||
}
|
||
return;
|
||
}
|
||
if (!isPlainObjectFaithful(value)) {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
const entries = Object.entries(value as Record<string, unknown>);
|
||
if (entries.length === 0) {
|
||
out.set(prefix, "{}");
|
||
return;
|
||
}
|
||
for (const [key, child] of entries) {
|
||
flattenFaithful(child, joinPathFaithful(prefix, key), out);
|
||
}
|
||
}
|
||
|
||
/** 共用 diff 装配(拍平两侧 + 集合运算 + 升序),供变体复用。 */
|
||
function assembleDiff(
|
||
actualFlat: Map<string, string>,
|
||
baselineFlat: Map<string, string>,
|
||
): SnapshotDiff {
|
||
const added: string[] = [];
|
||
const removed: string[] = [];
|
||
const changed: string[] = [];
|
||
for (const [path, value] of actualFlat) {
|
||
const baselineValue = baselineFlat.get(path);
|
||
if (baselineValue === undefined) {
|
||
added.push(path);
|
||
} else if (baselineValue !== value) {
|
||
changed.push(path);
|
||
}
|
||
}
|
||
for (const [path] of baselineFlat) {
|
||
if (!actualFlat.has(path)) {
|
||
removed.push(path);
|
||
}
|
||
}
|
||
added.sort();
|
||
removed.sort();
|
||
changed.sort();
|
||
return {
|
||
match: added.length === 0 && removed.length === 0 && changed.length === 0,
|
||
added,
|
||
removed,
|
||
changed,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* MUTATION M4 —— compareSnapshot:changed 检测 `!==` 改 `===`。
|
||
* 后果:值相同时误报 changed、值不同时漏报 → 回归漂移检测双向失真。
|
||
* 杀它的测试:b 值不同须报 changed(含 "b")。
|
||
*/
|
||
function compareSnapshot_bug_invertChanged(actual: unknown, baseline: unknown): SnapshotDiff {
|
||
const actualFlat = new Map<string, string>();
|
||
const baselineFlat = new Map<string, string>();
|
||
flattenFaithful(actual, "", actualFlat);
|
||
flattenFaithful(baseline, "", baselineFlat);
|
||
const added: string[] = [];
|
||
const removed: string[] = [];
|
||
const changed: string[] = [];
|
||
for (const [path, value] of actualFlat) {
|
||
const baselineValue = baselineFlat.get(path);
|
||
if (baselineValue === undefined) {
|
||
added.push(path);
|
||
} else if (baselineValue === value) {
|
||
// MUTATION: `!==` → `===`
|
||
changed.push(path);
|
||
}
|
||
}
|
||
for (const [path] of baselineFlat) {
|
||
if (!actualFlat.has(path)) {
|
||
removed.push(path);
|
||
}
|
||
}
|
||
added.sort();
|
||
removed.sort();
|
||
changed.sort();
|
||
return {
|
||
match: added.length === 0 && removed.length === 0 && changed.length === 0,
|
||
added,
|
||
removed,
|
||
changed,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* MUTATION M5 —— compareSnapshot:空数组叶子 `"[]"` 改 `"{}"`(与空对象碰撞)。
|
||
* 后果:空数组与空对象被当等价,结构即值的不变式被破坏。
|
||
* 杀它的测试:[] vs {} 须 match=false("[]" ≠ "{}")。
|
||
*/
|
||
function compareSnapshot_bug_emptyArrayAsObject(actual: unknown, baseline: unknown): SnapshotDiff {
|
||
function flatten(value: unknown, prefix: string, out: Map<string, string>): void {
|
||
if (value === null || typeof value !== "object") {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (value.length === 0) {
|
||
// MUTATION: "[]" → "{}"
|
||
out.set(prefix, "{}");
|
||
return;
|
||
}
|
||
for (let i = 0; i < value.length; i++) {
|
||
flatten(value[i], joinPathFaithful(prefix, String(i)), out);
|
||
}
|
||
return;
|
||
}
|
||
if (!isPlainObjectFaithful(value)) {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
const entries = Object.entries(value as Record<string, unknown>);
|
||
if (entries.length === 0) {
|
||
out.set(prefix, "{}");
|
||
return;
|
||
}
|
||
for (const [key, child] of entries) {
|
||
flatten(child, joinPathFaithful(prefix, key), out);
|
||
}
|
||
}
|
||
const actualFlat = new Map<string, string>();
|
||
const baselineFlat = new Map<string, string>();
|
||
flatten(actual, "", actualFlat);
|
||
flatten(baseline, "", baselineFlat);
|
||
return assembleDiff(actualFlat, baselineFlat);
|
||
}
|
||
|
||
/**
|
||
* MUTATION M6 —— compareSnapshot:flatten 叶子守卫
|
||
* `value === null || typeof value !== "object"` 漏掉 null 判定
|
||
* (删 `value === null ||`,仅留 `typeof value !== "object"`)。
|
||
* 后果:null(typeof "object")落入后续分支 → Array.isArray(null)=false →
|
||
* isPlainObject(null) 调 Object.getPrototypeOf(null) 抛 TypeError。
|
||
* 自反 null 比较直接崩。
|
||
* 杀它的测试:null vs null 须 match=true(不抛)。
|
||
*/
|
||
function compareSnapshot_bug_dropNullGuard(actual: unknown, baseline: unknown): SnapshotDiff {
|
||
function flatten(value: unknown, prefix: string, out: Map<string, string>): void {
|
||
// MUTATION: 删 `value === null ||`,仅留 `typeof value !== "object"`
|
||
if (typeof value !== "object") {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (value.length === 0) {
|
||
out.set(prefix, "[]");
|
||
return;
|
||
}
|
||
for (let i = 0; i < value.length; i++) {
|
||
flatten(value[i], joinPathFaithful(prefix, String(i)), out);
|
||
}
|
||
return;
|
||
}
|
||
if (!isPlainObjectFaithful(value as object)) {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
const entries = Object.entries(value as Record<string, unknown>);
|
||
if (entries.length === 0) {
|
||
out.set(prefix, "{}");
|
||
return;
|
||
}
|
||
for (const [key, child] of entries) {
|
||
flatten(child, joinPathFaithful(prefix, key), out);
|
||
}
|
||
}
|
||
const actualFlat = new Map<string, string>();
|
||
const baselineFlat = new Map<string, string>();
|
||
flatten(actual, "", actualFlat);
|
||
flatten(baseline, "", baselineFlat);
|
||
return assembleDiff(actualFlat, baselineFlat);
|
||
}
|
||
|
||
/**
|
||
* MUTATION M7 —— compareSnapshot:空对象叶子 `"{}"` 改 `"[]"`(与空数组碰撞)。
|
||
* 后果:空对象与空数组被当等价;与 M5 对称,从对象侧破坏结构即值不变式。
|
||
* 杀它的测试:{} vs [] 须 match=false("{}" ≠ "[]")。
|
||
*/
|
||
function compareSnapshot_bug_emptyObjectAsArray(actual: unknown, baseline: unknown): SnapshotDiff {
|
||
function flatten(value: unknown, prefix: string, out: Map<string, string>): void {
|
||
if (value === null || typeof value !== "object") {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (value.length === 0) {
|
||
out.set(prefix, "[]");
|
||
return;
|
||
}
|
||
for (let i = 0; i < value.length; i++) {
|
||
flatten(value[i], joinPathFaithful(prefix, String(i)), out);
|
||
}
|
||
return;
|
||
}
|
||
if (!isPlainObjectFaithful(value)) {
|
||
out.set(prefix, serializeLeafFaithful(value));
|
||
return;
|
||
}
|
||
const entries = Object.entries(value as Record<string, unknown>);
|
||
if (entries.length === 0) {
|
||
// MUTATION: "{}" → "[]"
|
||
out.set(prefix, "[]");
|
||
return;
|
||
}
|
||
for (const [key, child] of entries) {
|
||
flatten(child, joinPathFaithful(prefix, key), out);
|
||
}
|
||
}
|
||
const actualFlat = new Map<string, string>();
|
||
const baselineFlat = new Map<string, string>();
|
||
flatten(actual, "", actualFlat);
|
||
flatten(baseline, "", baselineFlat);
|
||
return assembleDiff(actualFlat, baselineFlat);
|
||
}
|
||
|
||
/**
|
||
* MUTATION M8 —— compareSnapshot:serializeLeaf 漏 -0 特判
|
||
* (删 `if (Object.is(value, -0)) return "-0";` 一行)。
|
||
* 后果:-0 落入 JSON.stringify 得 "0",与正零 0 碰撞;Object.is(-0,0)===false
|
||
* 而 match=true → 违反「不同语义值 → 不同串」不变式。
|
||
* 杀它的测试:-0 vs 0 须 match=false。
|
||
*/
|
||
function serializeLeaf_bug_noNegZero(value: unknown): string {
|
||
if (value === undefined) return "undefined";
|
||
if (typeof value === "function") return "function";
|
||
if (typeof value === "symbol") return "symbol";
|
||
if (typeof value === "bigint") return `bigint:${value}`;
|
||
if (typeof value === "number") {
|
||
// MUTATION: 删 -0 特判行
|
||
if (Number.isNaN(value)) return "NaN";
|
||
if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
|
||
}
|
||
const serialized = JSON.stringify(value);
|
||
return serialized === undefined ? "undefined" : serialized;
|
||
}
|
||
|
||
function compareSnapshot_bug_noNegZero(actual: unknown, baseline: unknown): SnapshotDiff {
|
||
function flatten(value: unknown, prefix: string, out: Map<string, string>): void {
|
||
if (value === null || typeof value !== "object") {
|
||
out.set(prefix, serializeLeaf_bug_noNegZero(value));
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (value.length === 0) {
|
||
out.set(prefix, "[]");
|
||
return;
|
||
}
|
||
for (let i = 0; i < value.length; i++) {
|
||
flatten(value[i], joinPathFaithful(prefix, String(i)), out);
|
||
}
|
||
return;
|
||
}
|
||
if (!isPlainObjectFaithful(value)) {
|
||
out.set(prefix, serializeLeaf_bug_noNegZero(value));
|
||
return;
|
||
}
|
||
const entries = Object.entries(value as Record<string, unknown>);
|
||
if (entries.length === 0) {
|
||
out.set(prefix, "{}");
|
||
return;
|
||
}
|
||
for (const [key, child] of entries) {
|
||
flatten(child, joinPathFaithful(prefix, key), out);
|
||
}
|
||
}
|
||
const actualFlat = new Map<string, string>();
|
||
const baselineFlat = new Map<string, string>();
|
||
flatten(actual, "", actualFlat);
|
||
flatten(baseline, "", baselineFlat);
|
||
return assembleDiff(actualFlat, baselineFlat);
|
||
}
|
||
|
||
/** MUTATION M9 —— DEFAULT_DOC_ANCHORS:漏 Object.freeze(深冻结不变式)。 */
|
||
const BUGGY_ANCHORS_NO_FREEZE: DocAnchor[] = [...DEFAULT_DOC_ANCHORS];
|
||
|
||
// ============================================================================
|
||
// 等价类划分 · checkDocSync(有效/无效/边界类)
|
||
// ============================================================================
|
||
|
||
describe("等价类划分 · checkDocSync(有效/无效/边界类)", () => {
|
||
// 有效类:双侧皆过
|
||
it("有效类-双侧对齐 → ok=true / mismatches 空", () => {
|
||
const readFile = readerFrom({
|
||
"doc.md": "第一行无关\n`src/core/tool-pipeline.ts`:实现 `ToolPipeline`\n第三行",
|
||
});
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 });
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mismatches).toHaveLength(0);
|
||
});
|
||
|
||
// 无效类-A:文档侧飘(行不引用 codeFile)
|
||
it("无效类-文档侧飘(行不引用 codeFile)→ mismatch + reason 含 does not reference", () => {
|
||
const readFile = readerFrom({ "doc.md": "第一行\n第二行没提路径\n第三行" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 });
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches).toHaveLength(1);
|
||
expect(r.mismatches[0].reason).toContain("does not reference");
|
||
});
|
||
|
||
// 无效类-B:代码侧飘(符号未命中,-1)
|
||
it("无效类-代码侧飘(grep -1)→ mismatch + reason 含 not found", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\n`src/core/tool-pipeline.ts`:`ToolPipeline`\n" });
|
||
const grepSymbol = greperFrom({});
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("not found");
|
||
});
|
||
|
||
// 无效类-C:文档不可读(readFile 抛错)
|
||
it("无效类-文档不可读(readFile 抛错)→ mismatch + reason 含 not readable + 文件名", () => {
|
||
const r = checkDocSync({
|
||
readFile: throwingReader(),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor()],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("not readable");
|
||
expect(r.mismatches[0].reason).toContain("doc.md");
|
||
});
|
||
|
||
// 无效类-D:代码侧抛错(grepSymbol 抛错)
|
||
it("无效类-代码侧抛错(grepSymbol 抛错)→ mismatch + reason 含 code file not readable", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\n`src/core/tool-pipeline.ts`:`ToolPipeline`\n" });
|
||
const grepSymbol: GrepSymbol = () => {
|
||
throw new Error("ENOENT");
|
||
};
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("code file not readable");
|
||
});
|
||
|
||
// 无效类-E:行越界(docLine 超出文件行数)
|
||
it("无效类-行越界 → mismatch + reason 含 out of range + 实际行数", () => {
|
||
const readFile = readerFrom({ "doc.md": "仅一行" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 99 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("out of range");
|
||
expect(r.mismatches[0].reason).toContain("1 lines");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 边界值分析 · checkDocSync(off-by-one / 空 / 单元素 / min / max)
|
||
// ============================================================================
|
||
|
||
describe("边界值分析 · checkDocSync(off-by-one / 空 / 单元素 / min / max)", () => {
|
||
it("docLine=1(首行,min 有效)→ 行引用 codeFile 即过", () => {
|
||
const readFile = readerFrom({ "doc.md": "`src/core/tool-pipeline.ts` 在首行\n第二行" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 1 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("docLine=N(末行,max 有效)→ 过", () => {
|
||
const readFile = readerFrom({ "doc.md": "第一行\n第二行\n`src/core/tool-pipeline.ts`" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 3 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("docLine=N+1(末行后一行,off-by-one 越界)→ mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "第一行\n第二行\n第三行" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 4 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("out of range");
|
||
});
|
||
|
||
it("docLine=0(零值,非法 1-indexed)→ mismatch(越界)", () => {
|
||
const readFile = readerFrom({ "doc.md": "唯一一行含 src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 0 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("docLine 负值(-1)→ mismatch(越界)", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: -1 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("grepSymbol 返回 1(min 有效行号)→ 过", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("grepSymbol 返回 0(非法哨兵)→ mismatch(fail-closed)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("not found");
|
||
});
|
||
|
||
it("grepSymbol 返回负值(-7)→ mismatch(fail-closed)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": -7 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("not found");
|
||
});
|
||
|
||
it("grepSymbol 返回大正数(Number.MAX_SAFE_INTEGER)→ 过(>0 即命中)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({
|
||
"src/core/tool-pipeline.ts:ToolPipeline": Number.MAX_SAFE_INTEGER,
|
||
}),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("单行文档 + 锚点指向该行 → 过", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts 的 ToolPipeline" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 10 }),
|
||
anchors: [anchor({ docLine: 1 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("空文档(readFile 返回 '')→ split 后 1 行空串 → 行不含 codeFile → mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 1 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("does not reference");
|
||
});
|
||
|
||
it("docLine=N(末行)恰好含 codeFile,末尾无换行 → 过(split 不产生幽灵尾行越界)", () => {
|
||
// "a\nb\ncode" split('\n') = ['a','b','code'],3 行;docLine=3 命中
|
||
const readFile = readerFrom({ "doc.md": "a\nb\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 3 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("文档末尾有换行 → split 产生尾空行,docLine 指向尾空行 → mismatch", () => {
|
||
// "a\nsrc/...\n" split = ['a','src/...',''],3 行
|
||
const readFile = readerFrom({ "doc.md": "a\nsrc/core/tool-pipeline.ts\n" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 3 })], // 尾空行,不含 codeFile
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("does not reference");
|
||
});
|
||
|
||
it("单元素锚点清单(1 条全过)→ ok=true", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mismatches).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 决策表 · checkDocSync(双侧组合 → 期望,覆盖全分支)
|
||
// ============================================================================
|
||
|
||
describe("决策表 · checkDocSync 双侧分支全覆盖", () => {
|
||
// 决策表:6 条可达规则(continue 早退致后续列不影响结果)
|
||
// 列:docReadable | lineInRange | lineRefsCode | grepThrows | grepHit(>0)
|
||
// 规则1: N | - | - | - | - → mismatch "doc not readable"
|
||
// 规则2: Y | N | - | - | - → mismatch "out of range"
|
||
// 规则3: Y | Y | N | - | - → mismatch "does not reference"
|
||
// 规则4: Y | Y | Y | Y | - → mismatch "code file not readable"
|
||
// 规则5: Y | Y | Y | N | N(≤0) → mismatch "not found"
|
||
// 规则6: Y | Y | Y | N | Y(>0) → ok
|
||
const cases: {
|
||
name: string;
|
||
readFile: ReadFile;
|
||
grepSymbol: GrepSymbol;
|
||
a: DocAnchor;
|
||
expectOk: boolean;
|
||
reasonContains: string;
|
||
}[] = [
|
||
{
|
||
name: "R1 文档不可读",
|
||
readFile: throwingReader(),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
a: anchor(),
|
||
expectOk: false,
|
||
reasonContains: "not readable",
|
||
},
|
||
{
|
||
name: "R2 行越界",
|
||
readFile: readerFrom({ "doc.md": "仅一行" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
a: anchor({ docLine: 5 }),
|
||
expectOk: false,
|
||
reasonContains: "out of range",
|
||
},
|
||
{
|
||
name: "R3 行不引用 codeFile",
|
||
readFile: readerFrom({ "doc.md": "第一\n第二行没提\n第三" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
a: anchor({ docLine: 2 }),
|
||
expectOk: false,
|
||
reasonContains: "does not reference",
|
||
},
|
||
{
|
||
name: "R4 代码侧抛错",
|
||
readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }),
|
||
grepSymbol: () => {
|
||
throw new Error("ENOENT");
|
||
},
|
||
a: anchor({ docLine: 2 }),
|
||
expectOk: false,
|
||
reasonContains: "code file not readable",
|
||
},
|
||
{
|
||
name: "R5 符号未命中(-1)",
|
||
readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }),
|
||
grepSymbol: greperFrom({}),
|
||
a: anchor({ docLine: 2 }),
|
||
expectOk: false,
|
||
reasonContains: "not found",
|
||
},
|
||
{
|
||
name: "R6 全过",
|
||
readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 }),
|
||
a: anchor({ docLine: 2 }),
|
||
expectOk: true,
|
||
reasonContains: "",
|
||
},
|
||
];
|
||
|
||
for (const c of cases) {
|
||
it(c.name, () => {
|
||
const r = checkDocSync({
|
||
readFile: c.readFile,
|
||
grepSymbol: c.grepSymbol,
|
||
anchors: [c.a],
|
||
});
|
||
expect(r.ok).toBe(c.expectOk);
|
||
if (!c.expectOk) {
|
||
expect(r.mismatches).toHaveLength(1);
|
||
expect(r.mismatches[0].reason).toContain(c.reasonContains);
|
||
} else {
|
||
expect(r.mismatches).toHaveLength(0);
|
||
}
|
||
});
|
||
}
|
||
|
||
// 决策表补充:grepSymbol 返回 0(非法哨兵)走 R5 分支(≤0)
|
||
it("R5' 符号返回 0(非法哨兵)→ not found(fail-closed)", () => {
|
||
const readFile = readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches[0].reason).toContain("not found");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 状态转换 · checkDocSync(fail-closed 优先序链 + 短路 + 不可达态 + 重入)
|
||
// ============================================================================
|
||
|
||
describe("状态转换 · checkDocSync fail-closed 链 + 短路 + 重入", () => {
|
||
// 每个锚点在状态机中迁移:
|
||
// S0(doc-read) → S1(line-bounds) → S2(doc-ref) → S3(code-grep) → S4(code-found) → ACCEPT
|
||
// 任一迁移失败 → MISMATCH(fail-closed,不可回到 ACCEPT)
|
||
// 不可达态:一旦 mismatch,不会回流到 ACCEPT(continue 跳过后续阶段)。
|
||
it("一旦文档侧 mismatch,不触达代码侧(grepSymbol 不被调用)", () => {
|
||
let grepCalled = 0;
|
||
const readFile = readerFrom({ "doc.md": "第一\n第二行没提\n第三" });
|
||
const grepSymbol: GrepSymbol = () => {
|
||
grepCalled++;
|
||
return 1;
|
||
};
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] });
|
||
expect(r.ok).toBe(false);
|
||
expect(grepCalled).toBe(0); // 文档侧先 mismatch,代码侧不可达
|
||
});
|
||
|
||
it("文档不可读时 grepSymbol 不被调用(fail-closed 优先序)", () => {
|
||
let grepCalled = 0;
|
||
const grepSymbol: GrepSymbol = () => {
|
||
grepCalled++;
|
||
return 1;
|
||
};
|
||
const r = checkDocSync({
|
||
readFile: throwingReader(),
|
||
grepSymbol,
|
||
anchors: [anchor()],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(grepCalled).toBe(0);
|
||
});
|
||
|
||
it("行越界时 grepSymbol 不被调用(S1→MISMATCH 短路)", () => {
|
||
let grepCalled = 0;
|
||
const readFile = readerFrom({ "doc.md": "唯一一行 src/core/tool-pipeline.ts" });
|
||
const grepSymbol: GrepSymbol = () => {
|
||
grepCalled++;
|
||
return 1;
|
||
};
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol,
|
||
anchors: [anchor({ docLine: 50 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
expect(grepCalled).toBe(0);
|
||
});
|
||
|
||
// 重入:同一 opts 多次调用结果等价(纯函数,无内部状态残留)
|
||
it("重入不变式:同一 opts 调两次结果 deep equal", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 5 });
|
||
const opts = {
|
||
readFile,
|
||
grepSymbol,
|
||
anchors: [anchor({ docLine: 2 }), anchor({ docLine: 1 })],
|
||
};
|
||
const r1 = checkDocSync(opts);
|
||
const r2 = checkDocSync(opts);
|
||
expect(r1).toEqual(r2);
|
||
});
|
||
|
||
// 多锚点重入:每锚点独立走状态机,mismatch 不影响下一锚点
|
||
it("多锚点重入:第二锚点 ok 不受第一锚点 mismatch 影响", () => {
|
||
const readFile = readerFrom({ "doc.md": "bad line\nsrc/core/tool-pipeline.ts" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 9 });
|
||
const bad = anchor({ docLine: 1 }); // 行1 不含 codeFile
|
||
const good = anchor({ docLine: 2 }); // 行2 含 codeFile
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [bad, good] });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches).toHaveLength(1);
|
||
expect(r.mismatches[0].anchor).toBe(bad);
|
||
});
|
||
|
||
// 不可达态校验:ok=true 时 mismatches 必空;ok=false 时 mismatches 必非空
|
||
it("不可达态:ok=true ⟺ mismatches 空(跨多场景单调)", () => {
|
||
const okR = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
const badR = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nbad" }),
|
||
grepSymbol: greperFrom({}),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(okR.ok).toBe(true);
|
||
expect(okR.mismatches).toHaveLength(0);
|
||
expect(badR.ok).toBe(false);
|
||
expect(badR.mismatches.length).toBeGreaterThan(0);
|
||
});
|
||
|
||
// 状态可逆:修复 mismatch 输入后 ok 可从 false 迁回 true
|
||
it("状态可逆:bad opts 修为 good opts 后 ok false→true", () => {
|
||
const bad = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nbad" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(bad.ok).toBe(false);
|
||
const good = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(good.ok).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 变异测试 · seeded bug 被某测试杀死
|
||
// ============================================================================
|
||
//
|
||
// 每个 it 验证一个 seeded bug 被杀:
|
||
// (a) 真代码满足 spec:`expect(spec(real)).toBe(true)`
|
||
// (b) buggy 副本违反 spec:`expect(spec(bug)).toBe(false)`
|
||
// (c) 字面演示「拿 buggy 当 SUT 跑 spec 断言必抛 AssertionError」:
|
||
// `expect(() => expect(buggyResult).toBe(期望值)).toThrow()`
|
||
// —— 等价于「该 spec 单独跑 buggy 变体时 FAIL」= bug 被杀。
|
||
|
||
describe("变异测试 · seeded bug 被某测试杀死", () => {
|
||
it("M1: `<= 0` 改 `< 0` —— grepSymbol 返回 0 须被拒绝(fail-closed)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const opts = {
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
};
|
||
const specRejectsZero = (r: DocSyncResult) => r.ok === false;
|
||
const real = checkDocSync(opts);
|
||
const bug = checkDocSync_bug_ltLeq(opts);
|
||
expect(specRejectsZero(real)).toBe(true); // 真代码满足 spec
|
||
expect(specRejectsZero(bug)).toBe(false); // buggy 违反 spec → bug 被杀
|
||
// 显式分歧:真代码 mismatch,buggy 放行
|
||
expect(real.ok).toBe(false);
|
||
expect(bug.ok).toBe(true);
|
||
// 字面:拿 buggy 当 SUT 跑「ok 须为 false」断言必抛
|
||
expect(() => expect(bug.ok).toBe(false)).toThrow();
|
||
expect(() => expect(bug.mismatches).toHaveLength(1)).toThrow();
|
||
});
|
||
|
||
it("M2: 行索引 off-by-one(漏 -1)—— docLine=1 须读首行", () => {
|
||
// 文档:第1行含 codeFile,第2行不含。docLine=1 应读第1行 → 过。
|
||
const readFile = readerFrom({
|
||
"doc.md": "src/core/tool-pipeline.ts 在首行\n第二行无关",
|
||
});
|
||
const opts = {
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 1 })],
|
||
};
|
||
const specReadsFirstLine = (r: DocSyncResult) => r.ok === true;
|
||
const real = checkDocSync(opts);
|
||
const bug = checkDocSync_bug_offByOne(opts);
|
||
expect(specReadsFirstLine(real)).toBe(true); // 真代码满足
|
||
expect(specReadsFirstLine(bug)).toBe(false); // buggy 读第2行 → mismatch → 违反
|
||
expect(real.ok).toBe(true);
|
||
expect(bug.ok).toBe(false);
|
||
// 字面:拿 buggy 当 SUT 跑「ok 须为 true」断言必抛
|
||
expect(() => expect(bug.ok).toBe(true)).toThrow();
|
||
});
|
||
|
||
it("M3: 漏 fail-closed(docFile 抛错静默吞)—— 不可读文档须 mismatch", () => {
|
||
const opts = {
|
||
readFile: throwingReader(),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor()],
|
||
};
|
||
const specFailsClosed = (r: DocSyncResult) => r.ok === false;
|
||
const real = checkDocSync(opts);
|
||
const bug = checkDocSync_bug_swallowRead(opts);
|
||
expect(specFailsClosed(real)).toBe(true);
|
||
expect(specFailsClosed(bug)).toBe(false); // buggy 静默放行 → 违反
|
||
expect(real.ok).toBe(false);
|
||
expect(bug.ok).toBe(true);
|
||
// 字面:拿 buggy 当 SUT 跑「ok 须为 false」断言必抛
|
||
expect(() => expect(bug.ok).toBe(false)).toThrow();
|
||
});
|
||
|
||
it("M4: changed 检测 `!==` 改 `===` —— 值不同须报 changed", () => {
|
||
const actual = { a: 1, b: 2 };
|
||
const baseline = { a: 1, b: 99 };
|
||
const specDetectsChange = (d: SnapshotDiff) => d.changed.includes("b");
|
||
const real = compareSnapshot(actual, baseline);
|
||
const bug = compareSnapshot_bug_invertChanged(actual, baseline);
|
||
expect(specDetectsChange(real)).toBe(true); // 真代码满足
|
||
expect(specDetectsChange(bug)).toBe(false); // buggy 漏报 changed → 违反
|
||
// 旁证:buggy 还会把相等的 a 误报 changed
|
||
expect(bug.changed).toContain("a");
|
||
expect(real.changed).not.toContain("a");
|
||
// 字面:拿 buggy 当 SUT 跑「changed 须含 b」断言必抛
|
||
expect(() => expect(bug.changed).toContain("b")).toThrow();
|
||
});
|
||
|
||
it("M5: 空数组叶子 `[]` 改 `{}` —— [] vs {} 须 match=false(结构即值)", () => {
|
||
const specStruct = (d: SnapshotDiff) => d.match === false;
|
||
const real = compareSnapshot([], {});
|
||
const bug = compareSnapshot_bug_emptyArrayAsObject([], {});
|
||
expect(specStruct(real)).toBe(true); // 真代码:"[]" ≠ "{}" → match=false
|
||
expect(specStruct(bug)).toBe(false); // buggy:两边均 "{}" → match=true → 违反
|
||
expect(real.match).toBe(false);
|
||
expect(bug.match).toBe(true);
|
||
// 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛
|
||
expect(() => expect(bug.match).toBe(false)).toThrow();
|
||
});
|
||
|
||
it("M6: flatten 漏 null 守卫 —— null vs null 须 match=true(不抛)", () => {
|
||
const specNullSafe = (d: SnapshotDiff) => d.match === true;
|
||
const real = compareSnapshot(null, null);
|
||
expect(specNullSafe(real)).toBe(true); // 真代码:null 当叶子,自反 match
|
||
// buggy:Object.getPrototypeOf(null) 抛 TypeError
|
||
expect(() => compareSnapshot_bug_dropNullGuard(null, null)).toThrow(TypeError);
|
||
// 字面:拿 buggy 当 SUT 跑「match 须为 true」断言必抛(因调用本身抛错)
|
||
expect(() =>
|
||
expect(compareSnapshot_bug_dropNullGuard(null, null).match).toBe(true),
|
||
).toThrow();
|
||
});
|
||
|
||
it("M7: 空对象叶子 `{}` 改 `[]` —— {} vs [] 须 match=false(结构即值,对象侧)", () => {
|
||
const specStruct = (d: SnapshotDiff) => d.match === false;
|
||
const real = compareSnapshot({}, []);
|
||
const bug = compareSnapshot_bug_emptyObjectAsArray({}, []);
|
||
expect(specStruct(real)).toBe(true); // 真代码:"{}" ≠ "[]" → match=false
|
||
expect(specStruct(bug)).toBe(false); // buggy:两边均 "[]" → match=true → 违反
|
||
expect(real.match).toBe(false);
|
||
expect(bug.match).toBe(true);
|
||
// 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛
|
||
expect(() => expect(bug.match).toBe(false)).toThrow();
|
||
});
|
||
|
||
it("M8: serializeLeaf 漏 -0 特判 —— -0 vs 0 须 match=false(Object.is 语义)", () => {
|
||
const specNegZeroDistinct = (d: SnapshotDiff) => d.match === false;
|
||
const real = compareSnapshot(-0, 0);
|
||
const bug = compareSnapshot_bug_noNegZero(-0, 0);
|
||
expect(Object.is(-0, 0)).toBe(false); // 语义确不同
|
||
expect(specNegZeroDistinct(real)).toBe(true); // 真代码特判 -0 → "-0"≠"0" → match=false
|
||
expect(specNegZeroDistinct(bug)).toBe(false); // buggy:均 "0" → match=true → 违反
|
||
expect(real.match).toBe(false);
|
||
expect(bug.match).toBe(true);
|
||
// 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛
|
||
expect(() => expect(bug.match).toBe(false)).toThrow();
|
||
});
|
||
|
||
it("M9: 漏 Object.freeze —— DEFAULT_DOC_ANCHORS 须深冻结", () => {
|
||
// spec:默认锚点清单 Object.isFrozen === true
|
||
const specFrozen = (arr: readonly DocAnchor[]) => Object.isFrozen(arr);
|
||
expect(specFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); // 真代码满足
|
||
expect(specFrozen(BUGGY_ANCHORS_NO_FREEZE)).toBe(false); // 漏 freeze → 违反
|
||
// 字面:拿 buggy 当 SUT 跑「isFrozen 须为 true」断言必抛
|
||
expect(() => expect(Object.isFrozen(BUGGY_ANCHORS_NO_FREEZE)).toBe(true)).toThrow();
|
||
});
|
||
|
||
it("变异兜底:真代码全部满足 spec 谓词(无 buggy 介入时全过)", () => {
|
||
// 汇总:真代码在每个变异场景都满足 spec,证明真实代码无这些 bug
|
||
expect(
|
||
checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
}).ok,
|
||
).toBe(false);
|
||
expect(
|
||
checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "src/core/tool-pipeline.ts\n第二行" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 1 })],
|
||
}).ok,
|
||
).toBe(true);
|
||
expect(
|
||
checkDocSync({
|
||
readFile: throwingReader(),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor()],
|
||
}).ok,
|
||
).toBe(false);
|
||
expect(compareSnapshot({ a: 1, b: 2 }, { a: 1, b: 99 }).changed).toContain("b");
|
||
expect(compareSnapshot([], {}).match).toBe(false);
|
||
expect(compareSnapshot({}, []).match).toBe(false);
|
||
expect(compareSnapshot(null, null).match).toBe(true);
|
||
expect(compareSnapshot(-0, 0).match).toBe(false);
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 对抗 / fuzz · checkDocSync + compareSnapshot
|
||
// ============================================================================
|
||
|
||
describe("对抗/fuzz · 畸形与滥用输入", () => {
|
||
// ---- checkDocSync fuzz ----
|
||
it("fuzz-空锚点清单 → ok=true(vacuous truth),mismatches 空", () => {
|
||
const r = checkDocSync({
|
||
readFile: throwingReader(), // 无锚点 → readFile 不被调用
|
||
grepSymbol: () => -1,
|
||
anchors: [],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mismatches).toHaveLength(0);
|
||
});
|
||
|
||
it("fuzz-docLine=NaN → 行索引越界 → mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: Number.NaN })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("fuzz-docLine=Infinity → 越界 → mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: Number.POSITIVE_INFINITY })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("fuzz-docLine=-Infinity → 越界 → mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: Number.NEGATIVE_INFINITY })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("fuzz-docLine=0.5(非整数 1-indexed)→ docLines[−0.5] 越界 → mismatch", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 0.5 })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("fuzz-codeSymbol 空串 + grep 返回 1(mock 放行)→ ok", () => {
|
||
// 空符号对抗:mock 控制结果,校验 checkDocSync 不因空串崩溃
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:": 1 }),
|
||
anchors: [anchor({ docLine: 2, codeSymbol: "" })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("fuzz-codeSymbol 空串 + grep 返回 -1 → mismatch(fail-closed)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({}),
|
||
anchors: [anchor({ docLine: 2, codeSymbol: "" })],
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
|
||
it("fuzz-并发重入:同一 opts 并发 100 次结果一致(纯函数无共享态)", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 7 });
|
||
const opts = { readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] };
|
||
const first = checkDocSync(opts);
|
||
for (let i = 0; i < 100; i++) {
|
||
expect(checkDocSync(opts)).toEqual(first);
|
||
}
|
||
});
|
||
|
||
it("fuzz-巨大锚点清单(1000 条全过)→ ok=true,mismatches 空", () => {
|
||
const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 });
|
||
const anchors = Array.from({ length: 1000 }, () => anchor({ docLine: 1 }));
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mismatches).toHaveLength(0);
|
||
});
|
||
|
||
it("fuzz-巨大锚点清单(1000 条全 mismatch)→ 1000 条 mismatches 保持输入序", () => {
|
||
const readFile = readerFrom({ "doc.md": "不含路径" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 });
|
||
const anchors = Array.from({ length: 1000 }, (_, i) =>
|
||
anchor({ docLine: 1, codeSymbol: `S${i}` }),
|
||
);
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mismatches).toHaveLength(1000);
|
||
// 输入序保持
|
||
expect(r.mismatches[999].anchor.codeSymbol).toBe("S999");
|
||
});
|
||
|
||
it("fuzz-codeFile 含正则元字符(. *)→ 子串匹配不误当正则", () => {
|
||
// docLine 的 includes 是字面子串,codeFile 的 "." 应字面匹配
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const r = checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 5 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
it("fuzz-readFile 返回非字符串(number)→ split 抛 TypeError 逃逸(特征化 try/catch 边界)", () => {
|
||
// ReadFile 类型契约要求返回 string;违约返回 number 时 docText.split
|
||
// 不存在 → 抛 TypeError。checkDocSync 的 try/catch 只包裹 readFile 调用
|
||
// 本身,未覆盖后续 .split(),故该 TypeError 逃逸(不被兜成 mismatch)。
|
||
// 这要求运行时违反 ReadFile 类型契约(tsc 编译期已防),非 in-spec 缺陷,
|
||
// 此处特征化 try/catch 守卫的精确边界。
|
||
const readFile = (() => 42) as unknown as ReadFile;
|
||
expect(() =>
|
||
checkDocSync({
|
||
readFile,
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor()],
|
||
}),
|
||
).toThrow(TypeError);
|
||
});
|
||
|
||
// ---- compareSnapshot fuzz ----
|
||
it("fuzz-undefined vs undefined → match=true(serializeLeaf 特判 'undefined')", () => {
|
||
expect(compareSnapshot(undefined, undefined).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-null vs undefined → mismatch('null' ≠ 'undefined')", () => {
|
||
const d = compareSnapshot(undefined, null);
|
||
expect(d.match).toBe(false);
|
||
// 根 path "" 两边都有但值不同 → changed
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
// serializeLeaf 已特判 NaN/Infinity/函数/symbol/bigint/-0——以下断言钉住正确行为。
|
||
it("NaN vs null 不碰撞 → match=false(serializeLeaf 特判 'NaN')", () => {
|
||
expect(compareSnapshot(NaN, null).match).toBe(false);
|
||
});
|
||
|
||
it("Infinity vs null 不碰撞 → match=false", () => {
|
||
expect(compareSnapshot(Infinity, null).match).toBe(false);
|
||
});
|
||
|
||
it("相同函数自反 match=true(serializeLeaf 特判 'function')", () => {
|
||
const f = () => 1;
|
||
expect(compareSnapshot(f, f).match).toBe(true);
|
||
});
|
||
|
||
it("两不同函数 → match=true(均序列化为 'function',opaque 身份类型)", () => {
|
||
// 与 function 同范式:不序列化内部,所有函数同串 → 自反且互等
|
||
// (这是文档明示的设计选择,非缺陷:opaque 身份类型)
|
||
const f = () => 1;
|
||
const g = () => 2;
|
||
expect(compareSnapshot(f, g).match).toBe(true);
|
||
});
|
||
|
||
it("Symbol vs undefined 不碰撞 → match=false(特判 'symbol')", () => {
|
||
expect(compareSnapshot(Symbol("s"), undefined).match).toBe(false);
|
||
});
|
||
|
||
it("Symbol 自反 match=true(opaque,均 'symbol')", () => {
|
||
expect(compareSnapshot(Symbol("a"), Symbol("b")).match).toBe(true);
|
||
});
|
||
|
||
it("BigInt 自反 match=true(特判 `bigint:${v}`,不抛)", () => {
|
||
expect(compareSnapshot(BigInt(1), BigInt(1)).match).toBe(true);
|
||
});
|
||
|
||
it("BigInt 值不同 → changed(bigint:1 ≠ bigint:2)", () => {
|
||
const d = compareSnapshot(BigInt(1), BigInt(2));
|
||
expect(d.match).toBe(false);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("BigInt vs number 不碰撞 → changed('bigint:1' ≠ '1')", () => {
|
||
const d = compareSnapshot(BigInt(1), 1);
|
||
expect(d.match).toBe(false);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("-0 vs 0 → match=false(特判 '-0',Object.is 语义)", () => {
|
||
expect(Object.is(-0, 0)).toBe(false);
|
||
expect(compareSnapshot(-0, 0).match).toBe(false);
|
||
});
|
||
|
||
it("-0 自反 match=true('-0' = '-0')", () => {
|
||
expect(compareSnapshot(-0, -0).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-NaN vs NaN → match=true(两侧均 'NaN',一致)", () => {
|
||
expect(compareSnapshot(NaN, NaN).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-NaN vs 0 → changed('NaN' ≠ '0')", () => {
|
||
const d = compareSnapshot(NaN, 0);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("fuzz-Infinity vs -Infinity → changed('Infinity' ≠ '-Infinity')", () => {
|
||
const d = compareSnapshot(Infinity, -Infinity);
|
||
expect(d.match).toBe(false);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("fuzz-循环引用 → 抛 RangeError(不静默挂死,特征化)", () => {
|
||
const circ: any = {};
|
||
circ.self = circ;
|
||
expect(() => compareSnapshot(circ, circ)).toThrow(RangeError);
|
||
});
|
||
|
||
it("fuzz-循环引用 vs 不同循环引用 → 抛 RangeError(不误报 match)", () => {
|
||
const a: any = {};
|
||
a.self = a;
|
||
const b: any = {};
|
||
b.self = b;
|
||
expect(() => compareSnapshot(a, b)).toThrow(RangeError);
|
||
});
|
||
|
||
it("fuzz-深嵌套(depth 1000)→ 不抛、自反 match=true", () => {
|
||
let deep: any = { v: 0 };
|
||
for (let i = 0; i < 1000; i++) deep = { nested: deep };
|
||
expect(() => compareSnapshot(deep, deep)).not.toThrow();
|
||
expect(compareSnapshot(deep, deep).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-巨大数组(10000 元素)→ 自反 match + 确定性", () => {
|
||
const big = Array.from({ length: 10000 }, (_, i) => i);
|
||
const d = compareSnapshot(big, big);
|
||
expect(d.match).toBe(true);
|
||
expect(compareSnapshot(big, big)).toEqual(d); // 确定性
|
||
});
|
||
|
||
it("fuzz-巨大数组单元素漂移 → 精确定位 changed path", () => {
|
||
const a = Array.from({ length: 10000 }, (_, i) => i);
|
||
const b = [...a];
|
||
b[5000] = 99999;
|
||
const d = compareSnapshot(a, b);
|
||
expect(d.changed).toEqual(["5000"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("fuzz-Date 自反 match=true(非纯对象当叶子,走 toJSON)", () => {
|
||
const dt = new Date("2026-01-01T00:00:00Z");
|
||
expect(compareSnapshot(dt, dt).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-Date 同 epoch 自反 match=true(两实例同值)", () => {
|
||
const a = new Date(123);
|
||
const b = new Date(123);
|
||
expect(compareSnapshot(a, b).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-Date 不同 epoch → changed", () => {
|
||
const a = new Date(123);
|
||
const b = new Date(999);
|
||
const d = compareSnapshot(a, b);
|
||
expect(d.match).toBe(false);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("fuzz-Map/Set 当叶子(非纯对象)→ 自反 match=true", () => {
|
||
const m = new Map([["k", 1]]);
|
||
expect(compareSnapshot(m, m).match).toBe(true);
|
||
const s = new Set([1, 2, 3]);
|
||
expect(compareSnapshot(s, s).match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-Map vs Set(空)→ match=true(均 JSON.stringify 为 '{}',opaque 身份)", () => {
|
||
// 空 Map/Set 无可枚举自有属性 → JSON.stringify 均得 "{}" → 同串 → match=true。
|
||
// 这是文档明示设计(非纯对象当叶子走 JSON 标准序列化),非缺陷。
|
||
const d = compareSnapshot(new Map(), new Set());
|
||
expect(d.match).toBe(true);
|
||
});
|
||
|
||
it("fuzz-巨大字符串值 → 自反 match + 确定性", () => {
|
||
const big = "x".repeat(100000);
|
||
expect(compareSnapshot(big, big).match).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 元蜕变 / 不变式 · checkDocSync + compareSnapshot
|
||
// ============================================================================
|
||
|
||
describe("元蜕变/不变式 · 跨变换保持的性质", () => {
|
||
// ---- checkDocSync 不变式 ----
|
||
it("不变式-ok 单调:mismatches 空 ⟺ ok=true(跨多场景)", () => {
|
||
const okCase = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
const badCase = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nbad" }),
|
||
grepSymbol: greperFrom({}),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(okCase.ok).toBe(true);
|
||
expect(okCase.mismatches).toHaveLength(0);
|
||
expect(badCase.ok).toBe(false);
|
||
expect(badCase.mismatches.length).toBeGreaterThan(0);
|
||
// 单调:ok === (mismatches.length === 0)
|
||
expect(okCase.ok).toBe(okCase.mismatches.length === 0);
|
||
expect(badCase.ok).toBe(badCase.mismatches.length === 0);
|
||
});
|
||
|
||
it("元蜕变-append 等价:append 两次同锚点 = replay(同 opts 调两次)deep equal", () => {
|
||
const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 3 });
|
||
const opts = {
|
||
readFile,
|
||
grepSymbol,
|
||
anchors: [anchor({ docLine: 2 }), anchor({ docLine: 2 })],
|
||
};
|
||
// 两次同锚点 = 输入序两条 ok
|
||
const r = checkDocSync(opts);
|
||
expect(r.ok).toBe(true);
|
||
// replay 等价
|
||
expect(checkDocSync(opts)).toEqual(r);
|
||
});
|
||
|
||
it("不变式-mismatches 保持锚点输入序(多 mismatch 排序校验)", () => {
|
||
const readFile = readerFrom({ "doc.md": "a 不含\nb 不含\nc 不含" });
|
||
const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 });
|
||
const a1 = anchor({ docLine: 1, codeSymbol: "A1" });
|
||
const a2 = anchor({ docLine: 2, codeSymbol: "A2" });
|
||
const a3 = anchor({ docLine: 3, codeSymbol: "A3" });
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [a1, a2, a3] });
|
||
expect(r.mismatches.map((m) => m.anchor)).toEqual([a1, a2, a3]);
|
||
});
|
||
|
||
it("不变式-DEFAULT_DOC_ANCHORS 数组级冻结(防 push 篡改)", () => {
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true);
|
||
// 数组级冻结:push 抛 TypeError(strict 模式)
|
||
expect(() => {
|
||
(DEFAULT_DOC_ANCHORS as any).push({
|
||
docFile: "x",
|
||
docLine: 1,
|
||
codeFile: "y",
|
||
codeSymbol: "z",
|
||
});
|
||
}).toThrow(TypeError);
|
||
});
|
||
|
||
// DEFAULT_DOC_ANCHORS 深冻结(外层 + 逐元素),元素属性不可篡改。
|
||
it("元素深冻结:isFrozen(element)=true,属性不可写", () => {
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[0])).toBe(true);
|
||
// 元素对象已冻结 → 其属性不可写、不可删——深冻结不变式兑现
|
||
const a = DEFAULT_DOC_ANCHORS[0];
|
||
const desc = Object.getOwnPropertyDescriptor(a, "docFile");
|
||
expect(desc?.writable).toBe(false); // 不可写 = 不可篡改
|
||
});
|
||
|
||
it("不变式-元素属性篡改抛 TypeError(深冻结 fail-closed)", () => {
|
||
expect(() => {
|
||
(DEFAULT_DOC_ANCHORS[0] as any).docFile = "tampered";
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
delete (DEFAULT_DOC_ANCHORS[0] as any).docLine;
|
||
}).toThrow(TypeError);
|
||
});
|
||
|
||
// ---- compareSnapshot 不变式 ----
|
||
it("不变式-自反性:compareSnapshot(x,x).match === true(多类型)", () => {
|
||
const samples = [
|
||
undefined,
|
||
null,
|
||
0,
|
||
-0,
|
||
"",
|
||
"str",
|
||
true,
|
||
false,
|
||
{},
|
||
[],
|
||
{ a: 1, b: { c: [1, 2, 3] } },
|
||
[1, "x", { y: null }],
|
||
];
|
||
for (const s of samples) {
|
||
expect(compareSnapshot(s, s).match).toBe(true);
|
||
}
|
||
});
|
||
|
||
it("不变式-对称性:交换 actual/baseline,added↔removed、changed 不变、match 不变", () => {
|
||
const actual = { a: 1, b: 2, c: 3 };
|
||
const baseline = { a: 1, b: 99, d: 4 };
|
||
const d1 = compareSnapshot(actual, baseline);
|
||
const d2 = compareSnapshot(baseline, actual);
|
||
expect(d2.added).toEqual(d1.removed);
|
||
expect(d2.removed).toEqual(d1.added);
|
||
expect(d2.changed).toEqual(d1.changed);
|
||
expect(d2.match).toBe(d1.match);
|
||
});
|
||
|
||
it("元蜕变-传递性:a≡b 且 b≡c ⇒ a≡c(等价类闭包)", () => {
|
||
const a = { x: 1, y: [1, 2], z: { w: "k" } };
|
||
const b = structuredClone(a);
|
||
const c = { x: 1, y: [1, 2], z: { w: "k" } };
|
||
expect(compareSnapshot(a, b).match).toBe(true);
|
||
expect(compareSnapshot(b, c).match).toBe(true);
|
||
expect(compareSnapshot(a, c).match).toBe(true);
|
||
});
|
||
|
||
it("不变式-确定性:同输入两次 deep equal(含 added/removed/changed 升序)", () => {
|
||
const a = { tools: [{ name: "flash", ok: true }, { name: "verify" }] };
|
||
const b = { tools: [{ name: "flash", ok: false }, { name: "verify" }] };
|
||
const d1 = compareSnapshot(a, b);
|
||
const d2 = compareSnapshot(a, b);
|
||
expect(d2).toEqual(d1);
|
||
expect(d1.changed).toEqual(["tools.0.ok"]);
|
||
});
|
||
|
||
it("不变式-升序:added/removed/changed 均升序排列", () => {
|
||
// 故意乱序构造 path(对象 key 插入序非字母序)
|
||
const actual = { z: 1, a: 2, m: 3, extra1: 9, extra2: 9 };
|
||
const baseline = { z: 1, a: 99, m: 3, gone1: 0, gone2: 0 };
|
||
const d = compareSnapshot(actual, baseline);
|
||
const isSorted = (arr: readonly string[]) =>
|
||
arr.every((v, i) => i === 0 || arr[i - 1] <= v);
|
||
expect(isSorted(d.added)).toBe(true);
|
||
expect(isSorted(d.removed)).toBe(true);
|
||
expect(isSorted(d.changed)).toBe(true);
|
||
// 升序内容校验
|
||
expect(d.added).toEqual(["extra1", "extra2"].sort());
|
||
expect(d.removed).toEqual(["gone1", "gone2"].sort());
|
||
expect(d.changed).toEqual(["a"].sort());
|
||
});
|
||
|
||
it("不变式-空容器结构变化即漂移({} vs [] vs {x:1})", () => {
|
||
const dEmptyVsX = compareSnapshot({}, { x: 1 });
|
||
expect(dEmptyVsX.added).toEqual([""]); // actual 的 "{}" path
|
||
expect(dEmptyVsX.removed).toEqual(["x"]);
|
||
expect(compareSnapshot([], {}).match).toBe(false); // "[]" vs "{}"
|
||
expect(compareSnapshot({}, {}).match).toBe(true);
|
||
expect(compareSnapshot([], []).match).toBe(true);
|
||
expect(compareSnapshot({}, []).match).toBe(false); // "{}" vs "[]"
|
||
});
|
||
|
||
it("元蜕变-waterfall 不调 next=短路:checkDocSync 文档侧 mismatch 即止(grep 不触达)", () => {
|
||
// fail-closed 短路:文档侧红即不评估代码侧,等价「waterfall 不调 next」
|
||
let grepTouched = false;
|
||
const readFile = readerFrom({ "doc.md": "第一\n第二行没提\n第三" });
|
||
const grepSymbol: GrepSymbol = () => {
|
||
grepTouched = true;
|
||
return 1;
|
||
};
|
||
const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] });
|
||
expect(r.ok).toBe(false);
|
||
expect(grepTouched).toBe(false); // 短路:未调 next
|
||
});
|
||
|
||
it("不变式-fail-closed unusable=拒:任一侧不可用即 mismatch(不静默 ok)", () => {
|
||
// 文档不可用
|
||
const docUnusable = checkDocSync({
|
||
readFile: throwingReader(),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }),
|
||
anchors: [anchor()],
|
||
});
|
||
expect(docUnusable.ok).toBe(false);
|
||
// 代码不可用(抛错)
|
||
const codeUnusable = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }),
|
||
grepSymbol: () => {
|
||
throw new Error("ENOENT");
|
||
},
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(codeUnusable.ok).toBe(false);
|
||
// grep 返回非法哨兵 0
|
||
const grepZero = checkDocSync({
|
||
readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }),
|
||
grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }),
|
||
anchors: [anchor({ docLine: 2 })],
|
||
});
|
||
expect(grepZero.ok).toBe(false);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// DEFAULT_DOC_ANCHORS + 默认 IO 适配器契约
|
||
// ============================================================================
|
||
|
||
describe("DEFAULT_DOC_ANCHORS + 默认 IO 适配器契约", () => {
|
||
it("DEFAULT_DOC_ANCHORS:数组冻结 + 非空 + ≥3 条 + 字段齐全", () => {
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true);
|
||
expect(DEFAULT_DOC_ANCHORS.length).toBeGreaterThanOrEqual(3);
|
||
for (const a of DEFAULT_DOC_ANCHORS) {
|
||
expect(typeof a.docFile).toBe("string");
|
||
expect(typeof a.docLine).toBe("number");
|
||
expect(a.docLine).toBeGreaterThan(0);
|
||
expect(typeof a.codeFile).toBe("string");
|
||
expect(a.codeFile.startsWith("src/")).toBe(true);
|
||
expect(typeof a.codeSymbol).toBe("string");
|
||
expect(a.codeSymbol.length).toBeGreaterThan(0);
|
||
}
|
||
});
|
||
|
||
// 元素深冻结——deepFreezeAnchors 兑现「外层 + 逐元素 Object.freeze」承诺。
|
||
it("元素深冻结:Object.isFrozen(element)===true", () => {
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); // 数组级冻结
|
||
// 元素级:深冻结触达,元素不可变(与文档声称的「深冻结」一致)
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[0])).toBe(true);
|
||
expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[DEFAULT_DOC_ANCHORS.length - 1])).toBe(true);
|
||
});
|
||
|
||
it("默认锚点 docFile 一致(同一架构文档)", () => {
|
||
const docFiles = new Set(DEFAULT_DOC_ANCHORS.map((a) => a.docFile));
|
||
expect(docFiles.size).toBe(1);
|
||
});
|
||
|
||
// defaultGrepSymbol 轻量真 fs 集成(本仓稳定文件,无 pi/硬件/网络)
|
||
it("defaultGrepSymbol:在本仓 scripts/doc-sync.ts 中命中 'checkDocSync'(>0 行号)", () => {
|
||
const line = defaultGrepSymbol("scripts/doc-sync.ts", "checkDocSync");
|
||
expect(line).toBeGreaterThan(0);
|
||
});
|
||
|
||
it("defaultGrepSymbol:未命中符号返回 -1", () => {
|
||
const line = defaultGrepSymbol("scripts/doc-sync.ts", "ZZZ_NOT_A_SYMBOL_999");
|
||
expect(line).toBe(-1);
|
||
});
|
||
|
||
it("defaultReadFile:读本仓稳定文件返回含已知标记的字符串", () => {
|
||
const text = defaultReadFile("scripts/doc-sync.ts");
|
||
expect(typeof text).toBe("string");
|
||
expect(text).toContain("checkDocSync");
|
||
});
|
||
|
||
it("defaultReadFile:读不存在文件抛错(fail-closed 适配器契约)", () => {
|
||
expect(() => defaultReadFile("does/not/exist.md")).toThrow();
|
||
});
|
||
|
||
// defaultGrepSymbol 行号语义:返回首个命中行(1-indexed)
|
||
it("defaultGrepSymbol:返回首个命中行(1-indexed)—— '@module' 首现于第 2 行", () => {
|
||
// scripts/doc-sync.ts 第 1 行是 '/**',第 2 行是 ' * @module doc-sync'
|
||
const line = defaultGrepSymbol("scripts/doc-sync.ts", "@module");
|
||
expect(line).toBe(2);
|
||
});
|
||
|
||
it("defaultGrepSymbol:空符号命中首行(''.includes('')===true → 返回 1)", () => {
|
||
const line = defaultGrepSymbol("scripts/doc-sync.ts", "");
|
||
expect(line).toBe(1);
|
||
});
|
||
|
||
// 端到端:用默认适配器跑默认锚点(CI 实跑路径)
|
||
it("端到端-CI 装配:checkDocSync(defaultReadFile, defaultGrepSymbol, DEFAULT_DOC_ANCHORS) 全过", () => {
|
||
const r = checkDocSync({
|
||
readFile: defaultReadFile,
|
||
grepSymbol: defaultGrepSymbol,
|
||
anchors: DEFAULT_DOC_ANCHORS,
|
||
});
|
||
// 本测试套件假定开发 Agent 已校对 DEFAULT_DOC_ANCHORS 与真实仓库对齐
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mismatches).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// e2e-snapshot · compareSnapshot 等价类 / 边界 / 决策表 / 状态
|
||
// ============================================================================
|
||
|
||
describe("等价类划分 · compareSnapshot(有效/无效/边界类)", () => {
|
||
it("有效类-两侧结构一致 → match=true", () => {
|
||
const baseline = { a: 1, b: { c: 2 }, d: [1, 2] };
|
||
const actual = { a: 1, b: { c: 2 }, d: [1, 2] };
|
||
const diff = compareSnapshot(actual, baseline);
|
||
expect(diff.match).toBe(true);
|
||
expect(diff.added).toEqual([]);
|
||
expect(diff.removed).toEqual([]);
|
||
expect(diff.changed).toEqual([]);
|
||
});
|
||
|
||
it("无效类-added(actual 独有 path)", () => {
|
||
const d = compareSnapshot({ a: 1, b: 2 }, { a: 1 });
|
||
expect(d.added).toEqual(["b"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("无效类-removed(baseline 独有 path)", () => {
|
||
const d = compareSnapshot({ a: 1 }, { a: 1, b: 2 });
|
||
expect(d.removed).toEqual(["b"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("无效类-changed(同 path 值不同)", () => {
|
||
const d = compareSnapshot({ a: 1, b: 2 }, { a: 1, b: 99 });
|
||
expect(d.changed).toEqual(["b"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("复合-added/removed/changed 各命中一条", () => {
|
||
const baseline = { a: 1, b: 2, c: 3 };
|
||
const actual = { a: 1, b: 99, d: 4 }; // b 变、c 删、d 增
|
||
const diff: SnapshotDiff = compareSnapshot(actual, baseline);
|
||
expect(diff.match).toBe(false);
|
||
expect(diff.added).toEqual(["d"]);
|
||
expect(diff.removed).toEqual(["c"]);
|
||
expect(diff.changed).toEqual(["b"]);
|
||
});
|
||
});
|
||
|
||
describe("边界值分析 · compareSnapshot", () => {
|
||
it("根原始值:0 vs 0 → match;0 vs 1 → changed", () => {
|
||
expect(compareSnapshot(0, 0).match).toBe(true);
|
||
const d = compareSnapshot(0, 1);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
|
||
it("根空串 vs 空串 → match;空串 vs 'x' → changed", () => {
|
||
expect(compareSnapshot("", "").match).toBe(true);
|
||
expect(compareSnapshot("", "x").changed).toEqual([""]);
|
||
});
|
||
|
||
it("布尔 true vs true → match;true vs false → changed", () => {
|
||
expect(compareSnapshot(true, true).match).toBe(true);
|
||
expect(compareSnapshot(true, false).changed).toEqual([""]);
|
||
});
|
||
|
||
it("单元素数组 vs 单元素数组(同值)→ match", () => {
|
||
expect(compareSnapshot([1], [1]).match).toBe(true);
|
||
});
|
||
|
||
it("单元素数组值不同 → changed 命中 '0'", () => {
|
||
const d = compareSnapshot([1], [2]);
|
||
expect(d.changed).toEqual(["0"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("单 key 对象 vs 空 {} → added=['k'] + removed=[''](空对象 {} 叶被移除)", () => {
|
||
const d = compareSnapshot({ k: 1 }, {});
|
||
expect(d.added).toEqual(["k"]);
|
||
expect(d.removed).toEqual([""]);
|
||
});
|
||
|
||
it("空数组 vs 单元素数组 → added=['0'] + removed=[''](空数组的 '[]' 叶被移除)", () => {
|
||
const d = compareSnapshot([1], []);
|
||
expect(d.added).toEqual(["0"]);
|
||
expect(d.removed).toEqual([""]); // baseline 空数组的 "[]" 叶 path ""
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("数组长度变化:[1] vs [1,2] → removed=['1']", () => {
|
||
const d = compareSnapshot([1], [1, 2]);
|
||
expect(d.removed).toEqual(["1"]);
|
||
});
|
||
|
||
it("数组长度变化:[1,2] vs [1] → added=['1']", () => {
|
||
const d = compareSnapshot([1, 2], [1]);
|
||
expect(d.added).toEqual(["1"]);
|
||
});
|
||
|
||
it("嵌套 path 形态:tools.0.ok 漂移", () => {
|
||
const a = { tools: [{ name: "flash", ok: true }, { name: "verify" }] };
|
||
const b = { tools: [{ name: "flash", ok: false }, { name: "verify" }] };
|
||
const d = compareSnapshot(a, b);
|
||
expect(d.changed).toEqual(["tools.0.ok"]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("空对象 {} vs {x:1} → added=[''] + removed=['x'](结构即值)", () => {
|
||
const d = compareSnapshot({}, { x: 1 });
|
||
expect(d.added).toEqual([""]);
|
||
expect(d.removed).toEqual(["x"]);
|
||
});
|
||
|
||
it("根 null vs null → match=true(叶子自反)", () => {
|
||
expect(compareSnapshot(null, null).match).toBe(true);
|
||
});
|
||
|
||
it("根 null vs 0 → changed('null' ≠ '0')", () => {
|
||
const d = compareSnapshot(null, 0);
|
||
expect(d.changed).toEqual([""]);
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("根 undefined vs null → changed('undefined' ≠ 'null')", () => {
|
||
const d = compareSnapshot(undefined, null);
|
||
expect(d.changed).toEqual([""]);
|
||
});
|
||
});
|
||
|
||
describe("决策表 · compareSnapshot path 集合运算", () => {
|
||
// 决策表:对每个 path,按 actual/baseline 是否含 + 值是否等 → 4 类
|
||
// 1) 两边含且值同 → 无 diff
|
||
// 2) 两边含且值异 → changed
|
||
// 3) 仅 actual 含 → added
|
||
// 4) 仅 baseline 含 → removed
|
||
it("四类同时出现的混合快照", () => {
|
||
const actual = { same: 1, changed: 2, added: 3 };
|
||
const baseline = { same: 1, changed: 99, removed: 4 };
|
||
const d = compareSnapshot(actual, baseline);
|
||
expect(d.changed).toEqual(["changed"]);
|
||
expect(d.added).toEqual(["added"]);
|
||
expect(d.removed).toEqual(["removed"]);
|
||
// same 不出现在任何 diff 列表
|
||
expect(d.added).not.toContain("same");
|
||
expect(d.changed).not.toContain("same");
|
||
expect(d.removed).not.toContain("same");
|
||
expect(d.match).toBe(false);
|
||
});
|
||
|
||
it("全相同 → 三列表皆空 + match=true", () => {
|
||
const d = compareSnapshot(
|
||
{ a: 1, b: [1, 2], c: { d: true } },
|
||
{ a: 1, b: [1, 2], c: { d: true } },
|
||
);
|
||
expect(d.added).toEqual([]);
|
||
expect(d.removed).toEqual([]);
|
||
expect(d.changed).toEqual([]);
|
||
expect(d.match).toBe(true);
|
||
});
|
||
|
||
it("仅 added(baseline 为空对象)", () => {
|
||
const d = compareSnapshot({ x: 1 }, {});
|
||
expect(d.added).toEqual(["x"]);
|
||
expect(d.removed).toEqual([""]);
|
||
expect(d.changed).toEqual([]);
|
||
});
|
||
|
||
it("仅 removed(actual 为空对象)", () => {
|
||
const d = compareSnapshot({}, { x: 1 });
|
||
expect(d.added).toEqual([""]);
|
||
expect(d.removed).toEqual(["x"]);
|
||
expect(d.changed).toEqual([]);
|
||
});
|
||
|
||
it("仅 changed(同 key 集,值全异)", () => {
|
||
const d = compareSnapshot({ a: 1, b: 2 }, { a: 9, b: 8 });
|
||
expect(d.changed).toEqual(["a", "b"]);
|
||
expect(d.added).toEqual([]);
|
||
expect(d.removed).toEqual([]);
|
||
});
|
||
});
|
||
|
||
describe("状态转换 · compareSnapshot(match 状态守恒)", () => {
|
||
// 状态:match ∈ {true, false};迁移:任一 added/removed/changed 非空 → false
|
||
// 不可达态:added/removed/changed 全空 且 match=false(不变式禁此态)
|
||
it("不变式-禁不可达态:三表全空 ⟹ match=true", () => {
|
||
const d = compareSnapshot({ a: 1 }, { a: 1 });
|
||
expect(d.added.length === 0 && d.removed.length === 0 && d.changed.length === 0).toBe(true);
|
||
expect(d.match).toBe(true); // 不可达 false
|
||
});
|
||
|
||
it("不变式-禁不可达态:match=true ⟹ 三表全空", () => {
|
||
const d = compareSnapshot({ a: { b: [1, 2] } }, { a: { b: [1, 2] } });
|
||
expect(d.match).toBe(true);
|
||
expect(d.added).toEqual([]);
|
||
expect(d.removed).toEqual([]);
|
||
expect(d.changed).toEqual([]);
|
||
});
|
||
|
||
it("迁移-单点漂移即 match→false", () => {
|
||
const base = { a: 1, b: 2, c: 3 };
|
||
const same = compareSnapshot(base, base);
|
||
expect(same.match).toBe(true);
|
||
const drifted = compareSnapshot({ ...base, b: 99 }, base);
|
||
expect(drifted.match).toBe(false);
|
||
});
|
||
|
||
it("迁移-漂移修复后 match→true(状态可逆)", () => {
|
||
const base = { a: 1, b: 2 };
|
||
const drifted = compareSnapshot({ a: 1, b: 99 }, base);
|
||
expect(drifted.match).toBe(false);
|
||
const fixed = compareSnapshot(base, base);
|
||
expect(fixed.match).toBe(true);
|
||
});
|
||
});
|