Files
clean-architecture-frontend…/tests/unit/feature-residue.test.ts
DongHyeonka 03744e19cf
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / self-tests and removal drills (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
fix(scripts): 제거 드릴의 URL 잔여 검사가 남는 route와 page object를 가린다
문제: 새 눈 리뷰(정적 읽기)가 앞 두 커밋에서 넷을 찾았다.
- 같은 context의 첫 기능은 context 경로(`/invoice`)를, 뒤 기능은 그 아래
  경로(`/invoice/line`)를 받는다. 첫 기능을 지우면 context가 남는데도
  형제 기능 spec의 `"/invoice/line"`이 잔여물로 잡혔다.
- 선택 정적 세그먼트(`/invoice/edit?`)는 접두어가 `/invoice/edit?`가 되어
  아무 URL도 맞지 않았다.
- `` `/invoice${query}` ``와 Playwright `testDir` 안의 page object
  (`tests/e2e/support/*.ts`)는 찾지 않았다.
- `src` 검색이 대소문자를 가리게 되면서, 한 단어 ID(`invoices`)의 옛
  부분 문자열 검색이 잡던 route ID 잔여(`route.INVOICES_LIST.title`)를
  놓쳤다.

고친 것: 드릴이 지우기 전에 지울 route 경로, 남는 route 경로(플랫폼 포함),
지울 route ID(넘겨받은 플랫폼 ID 제외)를 함께 넘긴다. URL 문자열은 맞는
접두어 중 가장 긴 것이 지운 route일 때만 센다(남는 route와 접두어가 같으면
세지 않는다). 접두어는 선택 세그먼트 앞에서 끊고, `${`도 이어짐으로 본다.
`playwright*.config.ts`의 `testDir` 안 파일 중 vitest 시험이 아닌 것도
본다. route ID는 `src` 본문에서 이름 단위로 찾는다.

버린 대안: react-router `matchRoutes`로 모든 문자열을 route 표에 맞추기.
드릴 lib가 앱 라우터에 묶이고, 고정 접두어 비교로 같은 판정을 낸다.

위험·한계: 지운 route와 남는 route의 고정 접두어가 같으면(`/invoice/:id`를
지우고 `/invoice`가 남음) `/invoice/7`을 세지 않는다. 조각으로 만든 URL은
여전히 못 찾는다.

검증(desktop): feature-residue·feature-removal-argument 19개 통과,
check:types·eslint rc=0(로그 /tmp/claude-gates/w2fe2-res4/). 변이 다섯
(남는 route 비교, 선택 세그먼트, `${`, testDir 파일, route ID 검색을 하나씩
끔)마다 해당 시험 하나가 실패했다(로그 /tmp/claude-gates/w2fe2-resmut/).

Refs: 0925 FOLLOW-UP 09-07, 1105/16-04
2026-11-13 05:40:54 +09:00

292 lines
13 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 { featureNamePattern, 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",
]);
});
// 0925 FOLLOW-UP 09-07. No step of the drill runs a Playwright spec, so a
// spec that opens the removed feature by its URL alone passed the drill and
// failed FE-GATE-008 afterwards.
it("counts a Playwright spec that opens one of the feature's route paths", async () => {
const root = await fixture({
"tests/e2e/route-only.spec.ts": 'test("opens", ({ page }) => page.goto("/invoice"));\n',
"tests/e2e/detail.spec.ts": "await page.goto(`/invoice/${id}?tab=lines`);\n",
"tests/visual/hash.visual.spec.ts": "await page.goto('/invoice#total');\n",
"tests/e2e/longer-path.spec.ts": 'await page.goto("/invoices-archive");\n',
"tests/e2e/other-base.spec.ts": 'await page.goto("/admin/invoice");\n',
// The same text in a vitest test is data (1105/16-04).
"tests/unit/route.test.ts": 'const target = "/invoice";\n',
});
expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice", "/invoice/:invoiceId"] })).toEqual([
"tests/e2e/detail.spec.ts",
"tests/e2e/route-only.spec.ts",
"tests/visual/hash.visual.spec.ts",
]);
});
// Diff review of 09-07. The first feature of a context takes the context's
// path (`/invoice`) and a later one a path under it (`/invoice/line`), and
// the context stays while another feature is in it.
it("leaves a URL to a route still there with a longer prefix, such as a sibling feature's", async () => {
const root = await fixture({
"tests/e2e/lines.spec.ts": 'await page.goto("/invoice/line");\nawait page.goto("/invoice/line/7");\n',
"tests/e2e/detail.spec.ts": 'await page.goto("/invoice/7");\n',
"tests/e2e/shared-prefix.spec.ts": 'await page.goto("/report/2026");\n',
});
expect(
await productFeatureResidue(root, ID, ID, {
paths: ["/invoice", "/report/:year"],
remainingPaths: ["/", "/invoice/line", "/report"],
}),
).toEqual(["tests/e2e/detail.spec.ts"]);
});
it("stops a route prefix at an optional segment and finds a URL built with a template", async () => {
const root = await fixture({
"tests/e2e/edit.spec.ts": 'await page.goto("/invoice/edit");\n',
"tests/e2e/query.spec.ts": "await page.goto(`/invoice${query}`);\n",
});
expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice/edit?"] })).toEqual([
"tests/e2e/edit.spec.ts",
"tests/e2e/query.spec.ts",
]);
});
it("searches a page object in a Playwright testDir, not a mock or a vitest test", async () => {
const root = await fixture({
"playwright.config.ts": 'export default defineConfig({ testDir: "./tests/e2e" });\n',
"tests/e2e/support/invoice-page.ts": 'export const open = (page) => page.goto("/invoice");\n',
"tests/e2e/support/route.test.ts": 'const target = "/invoice";\n',
"tests/mocks/handlers/routes.ts": 'export const PAGE = "/invoice";\n',
});
expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice"] })).toEqual([
"tests/e2e/support/invoice-page.ts",
]);
});
it("finds the feature's route IDs in source by their whole name", async () => {
const root = await fixture({
"src/contracts/titles.ts": "export const TITLE = messages.route.INVOICE_LIST.title;\n",
"src/contracts/longer.ts": 'export const KEY = "INVOICE_LIST_V2";\n',
});
expect(await productFeatureResidue(root, ID, ID, { ids: ["INVOICE_LIST"] })).toEqual([
"src/contracts/titles.ts",
]);
});
it("does not search a route path that is the root before its first parameter", async () => {
const root = await fixture({
"tests/e2e/home.spec.ts": 'await page.goto("/");\nawait page.goto("/?lang=ko");\n',
});
expect(await productFeatureResidue(root, ID, ID, { paths: ["/", "/:invoiceId", "*"] })).toEqual([]);
});
it("does not count the template's own browser tests for the route paths of a generated feature", async () => {
const files: Record<string, string> = {};
for (const entry of await readdir(".")) {
if (/^playwright.*\.config\.ts$/u.test(entry)) files[entry] = await readFile(entry, "utf8");
}
expect(Object.keys(files)).toContain("playwright.config.ts");
for (const entry of await readdir("tests", { recursive: true, withFileTypes: true })) {
if (!entry.isFile()) continue;
const file = path.join(entry.parentPath, entry.name).split(path.sep).join("/");
if (!/\.[cm]?[jt]sx?$/u.test(file)) continue;
if (/^tests\/(?:e2e|visual|storybook|browser-capabilities)\//u.test(file) || /\.spec\./u.test(file)) {
files[file] = await readFile(file, "utf8");
}
}
const root = await fixture(files);
// create:feature product-feature declares PRODUCT_LIST at /product.
expect(
await productFeatureResidue(root, "product-feature", "product-feature", { paths: ["/product"] }),
).toEqual([]);
});
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: a one-word ID that the template's source uses
// as a word (`status`) is still found in `src` text (feature-residue.ts).
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",
]);
});
// 1112 round9 (1105/16-04 remainder). `src` was searched by case-insensitive
// substring over path and text, so a legitimate ID such as
// `product-feature` counted ten template files (`product-features.ts`,
// `product-features-port.ts` and their importers) as residue.
it("does not count the template's own source and tests for an ID that longer names contain", async () => {
expect(await productFeatureResidue(process.cwd(), "product-feature", "product-feature")).toEqual([]);
});
// 1112 round9 (1105/16-04 remainder). The drill searched the built `dist`
// by case-insensitive substring too, so removing `product-feature` failed
// on the template's own platform-overview chunk (`data-product-feature`).
it("finds the feature in a built chunk by its whole name only", () => {
const pattern = featureNamePattern("product-feature", "product-feature");
expect(pattern.test('createElement("p",{"data-product-feature":e.featureId})')).toBe(false);
expect(pattern.test('const r="product-features";')).toBe(false);
expect(pattern.test('const t="Product-Feature";')).toBe(false);
expect(pattern.test('chunkId:"route-product",owner:"product-feature"')).toBe(true);
expect(featureNamePattern(ID, "invoices").test('import("./invoices/page.js")')).toBe(true);
});
it("counts a source path or text that names the ID as a whole name, and ignores the generated index", async () => {
const root = await fixture({
"src/contracts/leftover.ts": 'export const OWNER = "product-feature";\n',
"src/features/product-feature/stale.ts": "export const STALE = 1;\n",
"src/contracts/product-feature-port.ts": "export const PORT = 1;\n",
"src/contracts/product-features.ts": 'export const KEY = "data-product-feature";\n',
"src/contracts/title-case.ts": 'export const TITLE = "Product-Feature";\n',
"src/.generated/product-feature-index.ts": 'export const IDS = ["product-feature"];\n',
});
// A longer file name that starts with the ID is not the feature's file;
// the template's own tests/component/product-feature-switch.test.tsx is one.
expect(await productFeatureResidue(root, "product-feature", "product-feature")).toEqual([
"src/contracts/leftover.ts",
"src/features/product-feature/stale.ts",
]);
});
});