Files
clean-architecture-frontend…/tests/unit/feature-residue.test.ts
T
DongHyeonka eb03dabdfd fix(removal): spec 본문 잔여를 적힌 그대로, -가 든 이름만 찾는다
문제: af3344b가 더한 Playwright spec 본문 검색은 대소문자를 무시하고
`_`를 이름 경계로 봤다(`(?<![A-Za-z0-9-])…(?![A-Za-z0-9-])`, `i`).
create:feature는 한 단어 ID(`messages`, `reports`)를 받고 폴더 이름도
ID와 같다. 그래서 `messages` 기능을 지우면 템플릿 자신의
tests/e2e/accessibility.spec.ts(`KO_MESSAGES`)와 scrollbar-gutter
visual spec이 잔여로 잡혀 드릴이 실패한다. `status`·`reports`는 템플릿
spec 여러 개가 평범한 단어로 쓴다. errors.md는 목록에 템플릿 파일이
나오면 템플릿 결함이라 적으므로 제품은 고칠 곳이 없다.

고른 방법: 메인 세션 기준대로 적힌 그대로(대소문자 구분) 찾고, 경계는
식별자 문자 `[A-Za-z0-9_-]`다. 폴더 이름이 ID와 다르면 같은 규칙을 쓴다.
그런데 이 둘만으로는 `status`·`reports`가 0건이 되지 않는다. 템플릿
spec에 `status: 200`, `getByRole("status")`, 테스트 제목의 "reports"가
있다(git grep). `getByRole("status")`는 따옴표 안 한 단어라 따옴표나
문맥 규칙으로도 실제 참조와 구별되지 않는다. 그래서 `-`가 든 이름만 spec
본문에서 찾는다. 한 단어 ID·폴더 이름은 spec 본문 검색에서 빠진다.
검사를 좁히는 변경이지만 이 발견이 바로 그 거짓 양성이다. 거짓 양성은
제거를 막고 고칠 길이 없는 반면, 빠지는 쪽(한 단어 ID만 본문에 적은
spec)은 1106/16-01 전처럼 다음 CI의 브라우저 게이트가 잡는다.
테스트: 템플릿의 spec 파일 전부를 사본에 옮겨 `product-feature`,
`messages`, `status`, `reports`로 돌리면 잔여 0건이다. 적힌 그대로의
ID와 다른 폴더 이름(`invoice-docs`)은 잔여이고, `Invoice-Feature`와
`invoice-feature_v2`는 아니다. 매뉴얼 01 11단계, errors.md, CHANGELOG
1106 절의 16-01 행·확인 2·알려진 제한을 고쳤다.
버린 대안: 따옴표나 `/features/` 문맥만 센다. `getByRole("status")`가
남고, `test.describe("invoice-feature")` 같은 실제 잔여도 문맥에 따라
빠진다. 한 단어 ID를 막는 생성기 규칙은 이 수정 범위 밖이다.

위험·한계: `-`가 든 흔한 이름(예: `read-only`)을 ID로 쓰면 템플릿 spec이
그 이름을 쓸 때 다시 거짓 양성이 난다. 템플릿 spec 0건 테스트는 네
ID만 본다. src 쪽 부분 문자열 검색(1105/16-04)은 그대로다. CHANGELOG
행의 커밋 칸에는 이 커밋 해시를 아직 적지 않았다(같은 커밋에 자기 해시를
적을 수 없다).

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/feature-residue.test.ts
node scripts/run-vitest.ts run tests/unit/changelog-review-ids.test.ts

Refs: 1106/16-01 (diff review DR-02)
2026-11-06 07:56:30 +09:00

148 lines
6.0 KiB
TypeScript

import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { productFeatureResidue } from "../../scripts/lib/feature-residue.ts";
/**
* 1105/16-04. The manual's example ID is `invoice-feature` (01 1단계), and
* its step 11 removes that feature with
* `test:sample-removal -- --feature=invoice-feature`. The drill searched every
* file under `src` and `tests` for the ID as a substring, so the template's
* own tests/unit/create-feature.test.ts, which writes that example ID 51
* times as data, failed the removal (`fixture-id-residue`), and the advice
* was to edit that template file.
*/
const ID = "invoice-feature";
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
async function fixture(files: Readonly<Record<string, string>>): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "feature-residue-"));
roots.push(root);
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
return root;
}
// Built at run time so this file does not itself read as an import of the
// feature when the repository is searched below.
const importOf = (target: string) => ["import { x } from", JSON.stringify(target)].join(" ");
describe("product feature residue (1105/16-04)", () => {
it("does not count the template's own tests that name the manual's example ID", async () => {
expect(await productFeatureResidue(process.cwd(), ID, ID)).toEqual([]);
});
it("counts what still points at the removed feature", async () => {
const root = await fixture({
"src/contracts/leftover.ts": `export const OWNER = "${ID}";\n`,
"src/platform/clean.ts": "export const NOTHING = 1;\n",
[`tests/e2e/${ID}.spec.ts`]: "test('opens', () => {});\n",
"tests/unit/imports-feature.test.ts": `${importOf(`../../src/features/${ID}/feature-module.ts`)};\n`,
"tests/unit/imports-feature-tests.test.ts": `${importOf(`../features/${ID}/helpers.ts`)};\n`,
"tests/unit/example-data.test.ts": `const request = { id: "${ID}" };\nconst path = "src/features/${ID}/feature-module.ts";\n`,
});
expect(await productFeatureResidue(root, ID, ID)).toEqual([
"src/contracts/leftover.ts",
`tests/e2e/${ID}.spec.ts`,
"tests/unit/imports-feature-tests.test.ts",
"tests/unit/imports-feature.test.ts",
]);
});
// 1106/16-01. test:all is vitest only and the drill runs no Playwright
// spec, so a spec that names the removed feature in its text and nowhere
// else was caught by no step.
it("counts a Playwright spec that names the feature only in its text", async () => {
const spec = [
`test.describe("${ID}", () => {`,
' test("opens", async ({ page }) => {',
' await page.goto("/invoice");',
" });",
"});",
"",
].join("\n");
const root = await fixture({
"tests/e2e/checkout.spec.ts": spec,
"tests/visual/billing.visual.spec.ts": `const FEATURE = '${ID}';\n`,
// The same text in a vitest test is data (1105/16-04).
"tests/unit/checkout.test.ts": spec,
"tests/e2e/route-only.spec.ts": 'test("opens", ({ page }) => page.goto("/invoice"));\n',
});
expect(await productFeatureResidue(root, ID, ID)).toEqual([
"tests/e2e/checkout.spec.ts",
"tests/visual/billing.visual.spec.ts",
]);
});
it("does not count a spec whose longer names only contain the ID", async () => {
const root = await fixture({
"tests/e2e/builds.spec.ts": [
'run("scripts/generate-product-feature-index.ts");',
'const attribute = "data-product-feature";',
'const registry = "product-features";',
"",
].join("\n"),
});
expect(
await productFeatureResidue(root, "product-feature", "product-feature"),
).toEqual([]);
});
// 1106/16-01 (diff review DR-02). The spec search ignored case and took
// `_` as a boundary, so removing a feature named `messages` counted the
// template's accessibility spec (`KO_MESSAGES`), and `status` or `reports`
// counted a dozen template specs that use the word.
it("does not count the template's own specs for common feature IDs", async () => {
const specs: Record<string, string> = {};
for (const entry of await readdir("tests", { recursive: true })) {
const file = path.join("tests", entry).split(path.sep).join("/");
if (/\.spec\.[cm]?[jt]sx?$/u.test(file)) specs[file] = await readFile(file, "utf8");
}
expect(Object.keys(specs)).toContain("tests/e2e/accessibility.spec.ts");
// A copy of the specs alone: `src` is searched by substring (1105/16-04).
const root = await fixture(specs);
for (const id of ["product-feature", "messages", "status", "reports"]) {
expect(await productFeatureResidue(root, id, id), id).toEqual([]);
}
});
it("finds the name in a spec as written, and the folder name by the same rule", async () => {
const root = await fixture({
"tests/e2e/checkout.spec.ts": `test.describe("${ID}", () => {});\n`,
"tests/e2e/documents.spec.ts": 'const FOLDER = "invoice-docs";\n',
"tests/e2e/title-case.spec.ts": 'test.describe("Invoice-Feature", () => {});\n',
"tests/e2e/longer-key.spec.ts": `const KEY = "${ID}_v2";\n`,
});
expect(await productFeatureResidue(root, ID, "invoice-docs")).toEqual([
"tests/e2e/checkout.spec.ts",
"tests/e2e/documents.spec.ts",
]);
});
it("matches the folder name as well as the ID", async () => {
const root = await fixture({
"src/contracts/leftover.ts": 'export const DIRECTORY = "invoices";\n',
"tests/unit/x.test.ts": `${importOf("../../src/features/invoices/index.ts")};\n`,
});
expect(await productFeatureResidue(root, ID, "invoices")).toEqual([
"src/contracts/leftover.ts",
"tests/unit/x.test.ts",
]);
});
});