test(guards): make path-pinned source reads fail when their subject moves

A test that reads a source file by path and asserts an absence
(`expect(source).not.toMatch(…)`) stays green after a split: the code it
watched moved next door and the old path no longer holds it. A missing file
throws; a file that kept its name but lost its contents does not.

- `readSource(path, anchors)` in helpers/source-files.ts reads one file and
  requires every anchor (a string or pattern the watched code carries) to
  match at least once; it throws on a missing file, a lost anchor, or a read
  without an anchor.
- `readSourceFolder(dir, { floor })` is the folder-scan form for a subject
  that was split into several files.
- The twelve reads that were asserted only negatively now go through
  `readSource` with an anchor: the batch route, the integration-sync
  registrar, the dashboard client, the mood insights client, the sleep
  overview and sleep page, the sidebar, the baseline form, the account
  section (two guards), api-handler's requireAuth and the Google Health sync.
- The two schema parsers the wipe and enum guards share now refuse a parse
  of the real schema that finds fewer than 50 models (and 10 enums), so a
  moved file or a drifted block regex cannot leave those guards comparing
  an allowlist against nothing. Synthetic schemas a test writes stay exempt.

Proof: renaming `setSaving` in the baseline form made the converted
confirm-failure guard throw "the file no longer contains setSaving"; the
helper's own test plants a missing file, a lost string anchor, a lost regex
anchor, an empty anchor list and an under-floor folder, each of which throws.
This commit is contained in:
Marc-André Bombeck committed 2026-10-22 04:29:35 +02:00
1 parent c86c7d1a79
commit f3d7ab31e2
16 files changed
+204 -44

No files matched your search

@@ -48,6 +48,7 @@ import {
convertHkValue,
isConvertibleHkUnit,
} from "@/lib/measurements/hk-units";
import { readSource } from "@/__tests__/helpers/source-files";
const ENTRIES = Object.values(APPLE_HEALTH_TYPE_MAP);
@@ -193,10 +194,10 @@ describe("Apple Health mapping — the record's own unit (issue #944)", () => {
"utf8",
);
expect(archive).toContain(optIn);
const batch = readFileSync(
join(process.cwd(), "src/app/api/measurements/batch/route.ts"),
"utf8",
);
const batch = readSource("src/app/api/measurements/batch/route.ts", [
"export const POST",
"hkIdentifier",
]);
expect(
batch,
"the batch route opted into record-unit conversion",
@@ -171,5 +171,16 @@ export function readDeclaredSchema(
};
});
// Every consumer compares this against an allowlist or a "none of these"
// rule, which an empty parse satisfies. For the real schema, this little is
// a broken read (a moved file, a block regex that stopped matching), not a
// schema. A synthetic schema a test writes itself is exempt.
if (schemaPath === SCHEMA_PATH && (models.length < 50 || enums.length < 10)) {
throw new Error(
`readDeclaredSchema(${schemaPath}): parsed ${models.length} model(s) and ` +
`${enums.length} enum(s), below the floor of 50 and 10. Fix the parser ` +
`before trusting a guard built on it.`,
);
}
return { enums, models };
}
+80 -1
View File
@@ -50,7 +50,7 @@
* worktrees, each a full second copy of the tree that would double every
* match. Every caller roots at `src/`, `e2e/` or a subtree of one.
*/
import { readdirSync, readFileSync } from "node:fs";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join, sep } from "node:path";
export function walkSourceFiles(
@@ -229,3 +229,82 @@ export function scanSourceMatches(
options.matchFloor,
) as SourceMatch[];
}
/** Something a file must still contain for a read of it to mean anything. */
export type SourceAnchor = string | RegExp;
function anchorCount(text: string, anchor: SourceAnchor): number {
if (typeof anchor === "string") return text.split(anchor).length - 1;
const flags = anchor.flags.includes("g") ? anchor.flags : `${anchor.flags}g`;
return [...text.matchAll(new RegExp(anchor.source, flags))].length;
}
/**
* Read one source file by path, and prove it is still the file the guard is
* about.
*
* A guard that reads a fixed path and asserts that something is ABSENT
* (`expect(source).not.toMatch(…)`) is green on a file that has been split:
* the code it watched moved next door, the old path holds whatever is left,
* and the absence is true for the wrong reason. A missing file at least
* throws; a file that kept its name but lost its contents does not.
*
* So the caller names at least one anchor: a string or pattern the watched
* code itself carries (the function the guard is about, the call it pins).
* Every anchor must match at least once, or this throws and names the file,
* which is the moment to point the guard at the new home (or at a folder
* with `readSourceFolder`). `rel` is relative to the repository root.
*/
export function readSource(
rel: string,
anchors: SourceAnchor | readonly SourceAnchor[],
): string {
const list = (Array.isArray(anchors) ? anchors : [anchors]) as SourceAnchor[];
if (list.length === 0) {
throw new Error(
`readSource(${rel}): name at least one anchor the watched code carries.`,
);
}
const path = join(process.cwd(), rel);
if (!existsSync(path)) {
throw new Error(
`readSource(${rel}): the file does not exist. If it was split or moved, ` +
`point the guard at the new location or scan the folder with ` +
`readSourceFolder and a floor.`,
);
}
const text = readFileSync(path, "utf8");
const lost = list.filter((anchor) => anchorCount(text, anchor) === 0);
if (lost.length > 0) {
throw new Error(
`readSource(${rel}): the file no longer contains ${lost
.map(String)
.join(", ")}. The code this guard watches has moved; a negative ` +
`assertion on this file would now pass for the wrong reason.`,
);
}
return text;
}
/**
* Read every source file under a folder (relative to the repository root),
* with a floor on how many it found: the folder-scan form of `readSource`
* for a guard whose subject was split into several files. Returns
* `[path relative to the folder, text]` pairs, sorted.
*/
export function readSourceFolder(
relDir: string,
options: {
floor: number;
include?: (rel: string) => boolean;
extensions?: readonly string[];
},
): Array<[string, string]> {
const root = join(process.cwd(), relDir);
const files = walkSourceFiles(root, {
floor: options.floor,
extensions: options.extensions,
}).filter(options.include ?? (() => true));
requireFloor(`readSourceFolder(${relDir})`, files, options.floor);
return files.map((rel) => [rel, readFileSync(join(root, rel), "utf8")]);
}
@@ -38,6 +38,12 @@ export function parseWipeSchema(
const blocks = [...schema.matchAll(/^model\s+(\w+)\s*\{([\s\S]*?)^\}/gm)].map(
(m) => ({ name: m[1], body: m[2] }),
);
if (schemaPath === WIPE_SCHEMA_PATH && blocks.length < 50) {
throw new Error(
`parseWipeSchema(${schemaPath}): parsed ${blocks.length} model(s), below ` +
`the floor of 50. A wipe guard over an empty parse passes on nothing.`,
);
}
const modelNames = new Set(blocks.map((b) => b.name));
const out = new Map<string, ModelShape>();
+4 -3
View File
@@ -22,6 +22,7 @@ import { describe, expect, it } from "vitest";
import { INTEGRATION_CADENCE } from "@/lib/integrations/sync-verdict";
import { INTEGRATION_DISPLAY_NAMES } from "@/components/settings/integrations/integration-fallback-row";
import { readSource } from "@/__tests__/helpers/source-files";
const ROOT = path.resolve(__dirname, "../..");
@@ -65,9 +66,9 @@ describe("moodLog integration stays removed", () => {
});
it("registers no moodlog queue, cron or handler binding", () => {
const registrar = readFileSync(
path.join(ROOT, "src/lib/jobs/reminder/register-integration-sync.ts"),
"utf8",
const registrar = readSource(
"src/lib/jobs/reminder/register-integration-sync.ts",
"export async function registerIntegrationSyncQueues",
);
expect(registrar).not.toContain("moodlog");
expect(registrar).not.toContain("MoodLog");
+55
View File
@@ -0,0 +1,55 @@
/**
* `readSource` and `readSourceFolder`: the reads a path-pinned guard goes
* through, so a split file fails the guard instead of leaving it green.
*/
import { describe, expect, it } from "vitest";
import { readSource, readSourceFolder } from "./helpers/source-files";
const HERE = "src/__tests__/helpers/source-files.ts";
describe("readSource", () => {
it("returns the text when every anchor is present", () => {
const text = readSource(HERE, [
"export function readSource(",
/export function walkSourceFiles\(/,
]);
expect(text.length).toBeGreaterThan(1000);
});
it("throws on a file that does not exist", () => {
expect(() => readSource("src/lib/does-not-exist.ts", "anything")).toThrow(
/does not exist/,
);
});
it("throws when an anchor no longer matches", () => {
expect(() =>
readSource(HERE, ["export function readSource(", "noSuchAnchorHere"]),
).toThrow(/no longer contains noSuchAnchorHere/);
expect(() => readSource(HERE, /export function neverDeclared\(/)).toThrow(
/no longer contains/,
);
});
it("refuses a read without an anchor", () => {
expect(() => readSource(HERE, [])).toThrow(/at least one anchor/);
});
});
describe("readSourceFolder", () => {
it("returns the files with their text, above the floor", () => {
const files = readSourceFolder("src/__tests__/helpers", { floor: 5 });
expect(files.length).toBeGreaterThanOrEqual(5);
expect(files.map(([rel]) => rel)).toContain("source-files.ts");
});
it("throws when the folder holds fewer files than the floor", () => {
expect(() =>
readSourceFolder("src/__tests__/helpers", {
floor: 1,
include: (rel) => rel === "nothing-matches.ts",
}),
).toThrow(/below the stated floor/);
});
});