Files
clean-architecture-frontend…/tests/unit/manual-code-blocks.test.ts
T
DongHyeonka 01cac930e0 docs(manual): 샘플 대신 생성 기능 경로와 시험하는 코드 조각을 예제로 둔다
매뉴얼 예제 칸 14곳(S4 3.3절)과 산문 30여 곳이 참조 기능을
가리킨다. problem details(Envelope가 아닌 백엔드) 응답 매핑의 예는
참조 기능에만 있다.

생성기 출력이 그 모양을 만들면 그 경로로 바꿨다. 없으면 매뉴얼 안
코드 조각으로 썼다: problem details의 분류와 매핑(02 결정표 4절,
소유자 결정 D1), 도메인 모델, 검색값 스키마와 hook, 실패 행동 hook,
403 페이지 시험. 조각마다 manual-code-block 표식에 둘 경로를 적는다.
tests/unit/manual-code-blocks.test.ts가 저장소 사본에 create:feature
invoice-feature --with-create를 만들고 조각을 그 경로에 그대로 넣어
tsc(app, test), eslint, check:architecture, 그 기능 폴더의 vitest를
돈다. 조각의 동작은 tests/fixtures/manual-code-blocks/가 본다.

위험: 403 조각은 본문 없는 403으로 답한다. 공유 시나리오
forbidden-403(JSON 본문)은 jsdom + MSW에서 실행기의 본문 cancel이
끝나지 않아 화면이 로딩에 머물렀다. 실행기는 고치지 않았다. 사본에
이미 invoice-feature가 있는 프로젝트에서는 이 시험이 생성 단계에서
실패한다.

검증(desktop): test:unit 213 files 3096 passed(이 커밋까지),
verify:documentation PASS_SCOPED, lint 통과.
2026-11-08 13:51:55 +09:00

141 lines
6.0 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { cp, 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 { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts";
/**
* 2026-11-07. The template ships no sample feature: what the generated
* feature does not show, docs/manual shows as code blocks a product copies
* into its feature folder. Each such block has `<!-- manual-code-block: <path> -->`
* above it, the path in the feature `create:feature invoice-feature
* --with-create` writes. Here a copy of the repository gets that feature, each
* block goes to its path unchanged, and the app and test typecheck programs,
* lint and the feature's tests run on it. A block that is a test runs as it
* is; what the other blocks do is checked by tests/fixtures/manual-code-blocks.
*/
const MANUAL = "docs/manual";
const FEATURE_ID = "invoice-feature";
const CHECKS = "tests/fixtures/manual-code-blocks";
const MARKED_BLOCK = /<!-- manual-code-block: (\S+) -->\n```tsx?\n([\s\S]*?)\n```/gu;
async function manualDocuments(directory: string): Promise<string[]> {
const documents: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) documents.push(...(await manualDocuments(target)));
else if (entry.name.endsWith(".md")) documents.push(target);
}
return documents.sort();
}
/** Each marked block by the path it goes to. */
async function markedBlocks(): Promise<ReadonlyMap<string, string>> {
const blocks = new Map<string, string>();
for (const document of await manualDocuments(MANUAL)) {
for (const [, target = "", body = ""] of (await readFile(document, "utf8")).matchAll(MARKED_BLOCK)) {
if (blocks.has(target)) throw new Error(`${target} is marked twice in ${MANUAL}`);
blocks.set(target, `${body}\n`);
}
}
return blocks;
}
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
async function copyRepository(): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "manual-code-blocks-"));
roots.push(root);
for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) {
// A removal drill runs this test in a copy that has already lost some.
if (!existsSync(path.resolve(entry))) continue;
await cp(path.resolve(entry), path.join(root, entry), {
recursive: true,
filter: (source) => !source.includes(`${path.sep}.generated`),
});
}
await linkFixtureNodeModules(root);
return root;
}
function run(root: string, command: string, args: readonly string[]) {
const result = spawnSync(command, args, { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
return { status: result.status, output: `${result.stdout}${result.stderr}` };
}
describe("docs/manual code blocks, pasted into a generated feature", () => {
it("marks each block with a path in the feature it is written for", async () => {
const targets = [...(await markedBlocks()).keys()].sort();
expect(targets).toEqual([
"src/features/invoice-feature/adapters/invoice-problem-mapping.ts",
"src/features/invoice-feature/contracts/invoice-list-search.ts",
"src/features/invoice-feature/contracts/invoice-problem-details.ts",
"src/features/invoice-feature/domain/invoice.ts",
"src/features/invoice-feature/presentation/use-invoice-failure-action.ts",
"src/features/invoice-feature/presentation/use-invoice-list-filters.ts",
"tests/features/invoice-feature/invoice-forbidden.test.tsx",
]);
});
it("typechecks, lints and does what the manual says", async () => {
const blocks = await markedBlocks();
const root = await copyRepository();
const node = process.execPath;
// The generator runs first, as `corepack pnpm create:feature` does.
const indexed = run(root, node, ["scripts/generate-product-feature-index.ts"]);
expect(indexed.status, indexed.output).toBe(0);
const created = run(root, node, ["scripts/create-feature.ts", FEATURE_ID, "--with-create"]);
expect(created.status, created.output).toBe(0);
for (const [target, block] of blocks) {
const file = path.join(root, target);
// A block adds a file; it never stands in for one the command wrote.
expect(existsSync(file), `${target} exists before the block is pasted`).toBe(false);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, block);
}
const checks = (await readdir(CHECKS)).filter((name) => name.endsWith(".check.tsx"));
expect(checks.length).toBeGreaterThan(0);
for (const check of checks) {
await writeFile(
path.join(root, "tests/features", FEATURE_ID, check.replace(/\.check\.tsx$/u, ".test.tsx")),
(await readFile(path.join(CHECKS, check), "utf8")).replaceAll("{{feature}}", FEATURE_ID),
);
}
for (const program of ["tsconfig.app.json", "tsconfig.test.json"]) {
const typecheck = run(root, path.resolve("node_modules/.bin/tsc"), ["--project", program]);
expect(typecheck.output, program).toBe("");
expect(typecheck.status, program).toBe(0);
}
const lint = run(root, path.resolve("node_modules/.bin/eslint"), [
`src/features/${FEATURE_ID}`,
`tests/features/${FEATURE_ID}`,
"--max-warnings=0",
]);
expect(lint.output).toBe("");
expect(lint.status).toBe(0);
const architecture = run(root, node, ["scripts/check-architecture.ts"]);
expect(architecture.status, architecture.output).toBe(0);
const tests = run(root, node, [
"scripts/run-vitest.ts",
"run",
`tests/features/${FEATURE_ID}`,
"--reporter=dot",
]);
expect(tests.status, tests.output).toBe(0);
}, 300_000);
});