Files
clean-architecture-frontend…/tests/unit/backend-contract-drift.test.ts
DongHyeonka f600e6b132 fix(contracts): 짝 백엔드 pin과 drift 검사가 생성기 템플릿 사실도 대조한다
문제: create:feature --with-create가 백엔드 생성기 템플릿의 사실 넷을
프론트 문자열로 옮겼다. 경로 복수형(scripts/new-feature.sh), 이름 상한 100
(__Feature__.java.tmpl NAME_MAX_LENGTH), 오류 code <FEATURE>_INVALID·
_NOT_FOUND(__Feature__ErrorCode·ControllerTest 템플릿), 201과 검사 순서
(Controller·Create__Feature__UseCase 템플릿)다. 그러나 pin
(config/contracts/backend-contract-pin.json)과 check:backend-contract-drift는
docs/web/http-contract.md(1105/07-01 뒤로는 그 문서의 표 사본과 답 표)만
본다. 백엔드가 템플릿을 바꾸면 생성 기능이 다른 경로·상한·code를 써도 아무
신호가 없다.

고른 방법: pin의 backend.scaffoldSources에 백엔드 템플릿 파일 여섯과 각
파일에서 옮긴 사실, 옮긴 프론트 위치(파일과 이름)를 적는다. drift 검사는
1105/07-01의 사본·답 표 대조와 종료 코드(0 일치, 1 어긋남, 2 비교 못 함)를
그대로 두고, pin 뒤 HEAD에서 이 파일들도 diff한다. 바뀐 파일마다 다시 볼
프론트 위치를 failures에 더해 exit 1한다. pin 단위 테스트는 각 항목의 프론트
이름이 실제로 그 파일에 있는지 본다. drift 단위 테스트는 07-01의 가짜 백엔드
fixture에 생성기 템플릿 파일 하나를 더하고, 그 파일이 바뀐 경우(exit 1, 프론트
위치 출력)와 pin이 이름 붙이지 않은 파일만 바뀐 경우(exit 0, "1 scaffold
sources unchanged")를 더한다. 07-01의 경우들은 그대로다. 계약 문서 4.1절과
생성기 머리 주석에 같은 내용을 적었다.
버린 대안: 백엔드가 생성기 사실을 JSON으로 내고 프론트가 읽기 — 두 repo를
바꿔야 한다(백엔드는 이번에 읽기만 한다).

위험·한계: drift 검사는 여전히 게이트 밖이고 형제 checkout이 있을 때만
돈다. 파일 단위 diff라 템플릿의 무관한 줄이 바뀌어도 알린다(사람이 다시
본다). pin의 commit(45d2a478)은 그대로다. 네 사실이 그 커밋과 같다는 대조는
리뷰(1105/16 영역)가 했고 이번에는 이름 상한만 다시 읽었다. 07-01과 같은
파일을 고쳐서 fix/r1105-contracts-core-sq 위에 다시 쌓았다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/backend-contract-drift.test.ts
tests/unit/backend-contract-pin.test.ts
corepack pnpm check:backend-contract-drift (desktop 형제 checkout 기준, 참고)

Refs: 1105/16-02
2026-11-06 01:23:48 +09:00

333 lines
11 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
/**
* 1105/07-01. `check:backend-contract-drift` on a fake paired backend: a git
* repository with a small `docs/web/http-contract.md`, and a frontend root
* with the pin, the answer table and the table excerpt. The script compared
* only the document between the pin and HEAD, so an answer table or an
* excerpt that disagreed with the pinned document passed, and no checkout
* passed as "skipped".
*/
type Answer = Readonly<{ section: string; code: string; status: number }>;
type Sections = Readonly<Record<string, readonly (readonly string[])[]>>;
const T2A = [
"| 경우 | status | `error.code` | 클라이언트 행동 |",
"| --- | --- | --- | --- |",
"| 재생: 같은 키, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | 받아들인다 |",
"| 처리 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | 같은 키로 다시 보낸다 |",
];
const T2B = [
"| 경우 | status | `error.code` | 클라이언트 행동 |",
"| --- | --- | --- | --- |",
"| 결과 불명 | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 같은 키로 나중에 |",
];
const T4 = [
"| 코드 | status | 언제 |",
"| --- | --- | --- |",
"| `REQUEST_TIMEOUT` | 503 | 시간 안에 끝나지 않았다 |",
"| `RATE_LIMIT_UNAVAILABLE` | 503 | rate-limit 저장소 응답 없음 |",
];
const SECTIONS: Sections = { "2": [T2A, T2B], "4": [T4] };
const ANSWERS: readonly Answer[] = [
{ section: "2", code: "IDEMPOTENT_IN_FLIGHT", status: 409 },
{ section: "2", code: "IDEMPOTENCY_COMPLETION_UNKNOWN", status: 503 },
{ section: "4", code: "REQUEST_TIMEOUT", status: 503 },
];
const NOT_COPIED = [
{ section: "4", code: "RATE_LIMIT_UNAVAILABLE", reason: "fixture" },
];
function contractDocument(sections: Sections): string {
return [
"# HTTP wire 계약",
"",
"## 1. Envelope",
"",
"| 응답 | 키 |",
"| --- | --- |",
"| 성공 | `data` |",
"",
"## 2. 멱등성 응답",
"",
...(sections["2"]?.[0] ?? []),
"",
"### 저장소가 응답하지 않을 때",
"",
...(sections["2"]?.[1] ?? []),
"",
"## 4. web 전용 오류 코드",
"",
...(sections["4"]?.[0] ?? []),
"",
"## 5. 바꿀 때",
"",
"- 표를 고치면 짝 프론트에 알린다.",
"",
].join("\n");
}
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
);
});
function git(cwd: string, ...args: string[]): string {
const result = spawnSync("git", args, {
cwd,
encoding: "utf8",
env: {
...process.env,
GIT_AUTHOR_NAME: "drift-fixture",
GIT_AUTHOR_EMAIL: "drift-fixture@localhost",
GIT_COMMITTER_NAME: "drift-fixture",
GIT_COMMITTER_EMAIL: "drift-fixture@localhost",
},
});
if (result.error || result.status !== 0) {
throw new Error(`fixture git ${args[0]} failed: ${result.stderr || result.error?.message}`);
}
return result.stdout.trim();
}
const DOCUMENT = "docs/web/http-contract.md";
/**
* 1105/16-02. One of the backend scaffold files `create:feature
* --with-create` copies a fact from (the aggregate's name limit).
*/
const AGGREGATE =
"scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl";
const SCAFFOLD_SOURCES = [
{
path: AGGREGATE,
fact: "NAME_MAX_LENGTH 100",
copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" },
},
];
async function commitFiles(
backend: string,
files: Readonly<Record<string, string>>,
message: string,
): Promise<string> {
for (const [file, text] of Object.entries(files)) {
await mkdir(path.dirname(path.join(backend, file)), { recursive: true });
await writeFile(path.join(backend, file), text);
}
git(backend, "add", "--all");
git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message);
return git(backend, "rev-parse", "HEAD");
}
async function drift(
options: Readonly<{
answers?: readonly Answer[];
excerpt?: Sections;
notCopied?: typeof NOT_COPIED;
/** The document of a backend commit after the pin. */
head?: string;
/** 1105/16-02. The scaffold aggregate template in that later commit. */
scaffoldHead?: string;
/** 1105/16-02. A file the pin does not name, in that later commit. */
otherHead?: string;
/** Where the script looks for the backend instead of the fake one. */
backend?: string;
flags?: readonly string[];
}> = {},
) {
const root = await mkdtemp(path.join(tmpdir(), "drift-frontend-"));
const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-"));
directories.push(root, backend);
git(backend, "init", "--quiet", "--initial-branch=fixture");
const commit = await commitFiles(
backend,
{
[DOCUMENT]: contractDocument(SECTIONS),
[AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n",
"README.md": "backend\n",
},
"pinned",
);
const later = {
...(options.head === undefined ? {} : { [DOCUMENT]: options.head }),
...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }),
...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }),
};
if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin");
const source = {
repository: "clean-architecture-backend-template",
commit,
document: DOCUMENT,
};
const write = async (file: string, value: unknown) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
};
await write("config/contracts/backend-contract-pin.json", {
schemaVersion: 1,
backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES },
frontend: {
contractDocument: "docs/architecture/backend-api-and-server-state-contract.md",
contractSections: ["4.1", "6", "6.1"],
readers: ["src/adapters/http/backend-envelope.ts"],
},
tables: {
idempotencyAnswers: "config/contracts/backend-idempotency-answers.json",
backendExcerpt: "config/contracts/backend-http-contract-excerpt.json",
},
notCopied: options.notCopied ?? NOT_COPIED,
owner: "fixture",
comparedOn: "2026-11-05",
});
await write("config/contracts/backend-idempotency-answers.json", {
schemaVersion: 1,
source,
answers: (options.answers ?? ANSWERS).map((answer) => ({
...answer,
refusedBeforeWrite: false,
sameKeyResend: true,
})),
});
await write("config/contracts/backend-http-contract-excerpt.json", {
schemaVersion: 1,
source,
sections: options.excerpt ?? SECTIONS,
});
const result = spawnSync(
process.execPath,
[
path.resolve("scripts/check-backend-contract-drift.ts"),
"--backend",
options.backend ?? backend,
...(options.flags ?? []),
],
{ cwd: root, encoding: "utf8" },
);
return {
status: result.status,
stdout: result.stdout,
stderr: result.stderr,
readExcerpt: async () =>
JSON.parse(
await readFile(path.join(root, "config/contracts/backend-http-contract-excerpt.json"), "utf8"),
) as { sections: Sections },
};
}
describe("check:backend-contract-drift (1105/07-01)", () => {
it("passes when the excerpt and the answer table match the pinned document", async () => {
const result = await drift();
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
it("fails when an answer's status is not the pinned document's", async () => {
const result = await drift({
answers: ANSWERS.map((answer) =>
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"answer 500 IDEMPOTENCY_COMPLETION_UNKNOWN is not a row of the pinned document's §2",
);
});
it("fails when the excerpt is not the pinned document's, even if the answers follow it", async () => {
const edited = T2B.map((line) => line.replace("| 503 |", "| 500 |"));
const result = await drift({
excerpt: { ...SECTIONS, "2": [T2A, edited] },
answers: ANSWERS.map((answer) =>
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"excerpt differs from the pinned document: §2 -| 결과 불명 | 500 |",
);
expect(result.stderr).toContain(
"excerpt differs from the pinned document: §2 +| 결과 불명 | 503 |",
);
});
it("fails on a row of the pinned document neither copied nor listed as not copied", async () => {
const result = await drift({ notCopied: [] });
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"§4 503 RATE_LIMIT_UNAVAILABLE is neither in the answer table nor in the pin's notCopied",
);
});
// D6g in the 2026-11-05 review: the backend changes a copied row after the pin.
it("fails on a copied row the backend changed after the pin", async () => {
const result = await drift({
head: contractDocument({
...SECTIONS,
"2": [T2A, T2B.map((line) => line.replace("| 503 |", "| 500 |"))],
}),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("| 결과 불명 | 500 |");
});
it("does not pass without a backend checkout", async () => {
const result = await drift({ backend: path.join(tmpdir(), "no-such-backend-checkout") });
expect(result.status).toBe(2);
expect(result.stderr).toContain("not compared");
});
it("writes the excerpt from the pinned document with --write-excerpt", async () => {
const result = await drift({
excerpt: { "2": [T2A], "4": [T4.slice(0, 3)] },
flags: ["--write-excerpt"],
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect((await result.readExcerpt()).sections).toEqual(SECTIONS);
});
});
/**
* 1105/16-02. `create:feature --with-create` copies four facts from the
* paired backend's feature scaffold (path plural rule, name limit 100, error
* codes, check order). The pin and this script covered only
* `docs/web/http-contract.md`, so a backend that changed its scaffold left
* the frontend generator writing another path, limit or code with no signal.
*/
describe("check:backend-contract-drift scaffold sources (1105/16-02)", () => {
it("reports a scaffold source the generator copies from, with where the copy is", async () => {
const result = await drift({ scaffoldHead: "public static final int NAME_MAX_LENGTH = 120;\n" });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`scaffold source ${AGGREGATE} changed`);
expect(result.stderr).toContain(
"recheck BACKEND_NAME_MAX_LENGTH in scripts/create-feature-write-slice.ts",
);
});
it("passes a later backend commit that changed neither the document nor a scaffold source", async () => {
const result = await drift({ otherHead: "backend, later\n" });
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("1 scaffold sources unchanged");
});
});