Files
clean-architecture-frontend…/tests/unit/install-visual-test-fonts.test.ts
DongHyeonka 2db8b90e3d ci(gates): browser job의 visual 글꼴 deb 패키지를 캐시한다
문제:
merge / browser tests job이 매 실행마다 apt-get update와 약 220MB의
Noto/Liberation 글꼴 패키지를 인터넷 미러에서 다시 받아 약 31초(최대 71초)를
쓴다.

고른 방법과 버린 대안:
- scripts/lib/visual-test-fonts.ts에 이미지 sha256 digest 앞 12자와
  VISUAL_TEST_FONT_PACKAGES 해시로 정확한 캐시 키를 만드는 helper를 둔다.
  restore-keys 없이 정확한 키만 쓴다.
- scripts/generate-ci-workflow.ts가 merge_browser의 browser-install(image)
  앞에 main 전용 actions/cache 저장·복원 step과 비-main 전용
  actions/cache/restore 복원 step을 두고(main-push-reuse 조건 포함),
  scripts/ci/install-visual-test-fonts.sh에 VISUAL_TEST_FONT_PACKAGES 목록을
  그대로 넘긴다.
- scripts/ci/install-visual-test-fonts.sh는 캐시 폴더에 .deb가 있으면
  apt-get 없이 dpkg -i로 설치하고, 비어 있으면 --download-only로 내려받은 뒤
  partial·lock을 지우고 dpkg -i로 설치한다.
- 버린 대안: 커스텀 Playwright 이미지 레지스트리 등록(소유자 레지스트리 설정·
  토큰 필요), /var/lib/apt/lists만 캐시(220MB 다운로드 남음), 글꼴 폴더 tar
  캐시(dpkg 상태 불일치).

위험·한계:
- main push reuse(CI-FE-0004)가 동작하는 main push에서는 글꼴 step이 건너뛰므로
  캐시는 재사용이 아닌 main push 또는 workflow_dispatch(main)에서 최초 저장된다.
- runner 캐시 저장소(5GB 상한)에 약 220MB가 더해진다.
- release_gate의 non-imaged playwright install --with-deps 경로는 바꾸지 않았다.

검증:
- C3 RED(트리 fcc122aa91a6): ci-browser-image.test.ts rc=1 (1 failed | 3 passed)
- laptop-gate check:types, lint, verify:documentation, 단위 시험 5파일(535 passed) rc=0
- scripts/verify.sh docs rc=0, scripts/verify.sh hooks rc=0 (112 tests)

Refs: CI-FE-0003
2026-12-04 08:44:46 +09:00

143 lines
5.6 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
VISUAL_TEST_FONT_CACHE,
VISUAL_TEST_FONT_PACKAGES,
visualTestFontCacheKey,
} from "../../scripts/lib/visual-test-fonts.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
/** Measured max runtime of one bash invocation of install-visual-test-fonts.sh on desktop. */
const INSTALL_SCRIPT_MS = 60;
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function createStubBin(options: Readonly<{ failOnApt?: boolean; aptWritesDebs?: boolean; installed?: boolean }> = {}) {
const root = await mkdtemp(path.join(tmpdir(), "visual-test-fonts-"));
roots.push(root);
const bin = path.join(root, "bin");
const cacheDir = path.join(root, "cache dir");
const logFile = path.join(root, "calls.log");
await mkdir(bin, { recursive: true });
await mkdir(cacheDir, { recursive: true });
const writeStub = async (name: string, body: string) => {
const file = path.join(bin, name);
await writeFile(file, `#!/usr/bin/env bash\nset -euo pipefail\n${body}\n`, "utf8");
await chmod(file, 0o755);
};
// Fake sudo simply logs and executes the command directly so the test runs
// identically on hosts with or without system sudo.
await writeStub("sudo", 'exec "$@"');
await writeStub(
"apt-get",
options.failOnApt
? 'echo "unexpected apt-get call: $*" >&2; exit 99'
: [
`echo "apt-get $*" >> ${JSON.stringify(logFile)}`,
...(options.aptWritesDebs
? [
'if [[ "$1" == "install" ]]; then',
' dir=""',
' for arg in "$@"; do',
' case "$arg" in Dir::Cache::archives=*) dir="${arg#Dir::Cache::archives=}" ;; esac',
" done",
' touch "$dir/fonts-noto-core_1.deb" "$dir/fonts-noto-cjk_1.deb" "$dir/lock"',
"fi",
]
: []),
].join("\n"),
);
await writeStub("dpkg", `echo "dpkg $*" >> ${JSON.stringify(logFile)}`);
await writeStub(
"dpkg-query",
options.installed ? 'echo "install ok installed"' : 'echo "deinstall ok config-files"',
);
const run = (...args: string[]) =>
spawnSync("bash", [VISUAL_TEST_FONT_CACHE.installScript, ...args], {
encoding: "utf8",
env: {
PATH: `${bin}:${process.env.PATH ?? ""}`,
},
});
const readLog = async () => {
try {
return (await readFile(logFile, "utf8")).trim().split("\n").filter(Boolean);
} catch {
return [];
}
};
return { root, cacheDir, run, readLog };
}
describe("visualTestFontCacheKey", () => {
const digest = "baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07";
const image = `mcr.microsoft.com/playwright:v1.62.0-noble@sha256:${digest}`;
it("keys on the pinned image digest and package list, changing when either changes", () => {
const key = visualTestFontCacheKey(image);
expect(key).toMatch(/^fe-visual-fonts-baed2032d533-[0-9a-f]{12}$/u);
expect(visualTestFontCacheKey(image, VISUAL_TEST_FONT_PACKAGES.slice(0, -1))).not.toBe(key);
expect(visualTestFontCacheKey(`mcr.microsoft.com/playwright:v1.63.0-noble@sha256:${"f".repeat(64)}`)).not.toBe(key);
});
it("refuses an unpinned image without a sha256 digest", () => {
expect(() => visualTestFontCacheKey("mcr.microsoft.com/playwright:v1.62.0-noble")).toThrow(/sha256 digest/u);
});
});
describe("scripts/ci/install-visual-test-fonts.sh", { timeout: childProcessTimeout(INSTALL_SCRIPT_MS) }, () => {
it("installs cached .deb files via dpkg without invoking apt-get on a cache hit", async () => {
const { cacheDir, run, readLog } = await createStubBin({ failOnApt: true });
await writeFile(path.join(cacheDir, "fonts-noto-core_1.deb"), "deb");
await writeFile(path.join(cacheDir, "fonts-noto-cjk_1.deb"), "deb");
const result = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES);
expect(result.status, result.stderr).toBe(0);
const calls = await readLog();
expect(calls).toHaveLength(1);
expect(calls[0]).toContain("dpkg -i ");
expect(calls[0]).toContain("fonts-noto-core_1.deb");
expect(calls[0]).toContain("fonts-noto-cjk_1.deb");
});
it("downloads .deb archives, strips partial/lock metadata, and runs dpkg -i on a cache miss", async () => {
const { cacheDir, run, readLog } = await createStubBin({ aptWritesDebs: true });
const result = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES);
expect(result.status, result.stderr).toBe(0);
const calls = await readLog();
expect(calls).toHaveLength(3);
expect(calls[0]).toBe("apt-get update");
expect(calls[1]).toBe(
`apt-get install -y --download-only -o Dir::Cache::archives=${cacheDir} ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`,
);
expect(calls[2]).toContain("dpkg -i ");
await expect(stat(path.join(cacheDir, "partial"))).rejects.toThrow();
await expect(stat(path.join(cacheDir, "lock"))).rejects.toThrow();
});
it("fails closed when no package names are given or no .deb is downloaded for an uninstalled package", async () => {
const { cacheDir, run } = await createStubBin({ aptWritesDebs: false, installed: false });
expect(run(cacheDir).status).toBe(2);
const missing = run(cacheDir, ...VISUAL_TEST_FONT_PACKAGES);
expect(missing.status).toBe(1);
expect(missing.stderr).toContain("no .deb archive downloaded");
});
});