Files
clean-architecture-frontend…/tests/browser-capabilities/browser-files.spec.ts
T
DongHyeonka ee37dd86a2 fix(test): capability 파일·다운로드 테스트의 버튼을 앱 위 고정 층에 둔다
문제: FE-GATE-008의 test:browser-capabilities가 firefox에서 가끔 30초 시간
초과로 떨어졌다. browser-files.spec.ts의 두 test가 번갈아 걸렸다. 하나는
"filechooser"를, 다른 하나는 "download"를 기다리다 끝났다. desktop에서
firefox capability suite를 30회씩 돌리면 두 test 60건 중 3건이 떨어졌다(두
번 모두). 부하와는 상관없었다(1.05에서도 남). 리뷰 14.7절은 이것을 "알려진
flake"로 두었다(1103/11-10).

원인: 두 test는 `goto("/")` 직후 label·input·button을 `<body>` 끝, 앱 root
뒤에 붙이고 그 button을 누른다. 그때 앱은 아직 그리는 중이다. 실패한 6건의
event 기록(진단 branch, 커밋 안 함)은 모두 같았다.
- pointerdown·mousedown은 button("Choose test file"/"Download generated").
- 30~45 ms 뒤 pointerup·mouseup은 홈 화면 내용("프로젝트 시작점…").
- click은 둘의 공통 조상(앱 root)이라 button의 handler가 돌지 않았다
  (`__browserFileResult` 없음). 그래서 picker도 download도 없었다.
- 위치까지 적은 3건에서 그 사이 scrollY는 24로 같았다. body 높이는 744에서 756으로, button top은
  696에서 708로 둘 다 12 px 늘었다. 앱 내용이 클릭 도중 12 px 자랐고,
  viewport 아래 끝의 button 중앙 좌표가 button 밖이 됐다. 통과한 run은
  pointerdown 때 이미 756이었다.

고른 방법: 두 test가 붙이는 control을 `position: fixed` 층(왼쪽 위, 가장
높은 z-index)에 둔다. 앱의 흐름 밖이라 앱이 늦게 그려도 button이 움직이지
않는다. 제품 코드는 바꾸지 않는다.

버린 대안:
- 앱이 다 그려질 때까지 기다린다. "다 그려짐"을 정할 신호가 없다. 늦게 오는
  글꼴이나 내용이 생기면 다시 깨진다.
- `dispatchEvent("click")`이나 `force` click. 신뢰된 사용자 입력이 아니어서
  firefox가 file picker를 열지 않는다. test가 증명하려는 것을 지운다.
- 재시도·timeout 늘리기·worker 줄이기. 금지된 우회이고 원인이 남는다.

위험·한계: 고정 층이 앱 header 왼쪽 위를 덮는다. 두 test는 앱 UI를 누르지
않는다. 다른 capability spec은 body에 control을 붙이지 않는다(grep).

검증 (desktop):
- RED(커밋 안 한 재현): mousedown 때 앱 root에 400 px를 더하고 layout을
  다시 계산한다(앱이 늦게 그리는 것과 같은 일). 수정 전 spec은 세 엔진 두
  test 6/6 실패(filechooser·download 대기 시간 초과).
- GREEN: 같은 재현에서 수정 뒤 6/6 통과.
- 실제 조건 firefox capability suite ×30: 수정 전 두 번 다 3 failed /
  657 passed, 수정 뒤 660 passed.
2026-11-05 09:51:10 +09:00

473 lines
15 KiB
TypeScript

import { expect, test } from "../support/browser/strict-browser-test.ts";
/**
* 1103/11-10. The controls these tests add sit in a fixed layer above the
* app. The app is still rendering when a test clicks; in the document flow,
* after its root, its content moved the button between mousedown and mouseup.
* The mouseup then landed on the app, the click went to their common ancestor
* and the button's handler never ran: no file chooser, no download, and the
* test waited 30 s for the event.
*/
const FIXED_CONTROLS =
"position: fixed; inset-block-start: 0; inset-inline-start: 0; z-index: 2147483647; background: Canvas;";
test("selects, inspects, streams, and previews a real browser File", async ({
page,
}) => {
await page.goto("/");
await page.evaluate(async (fixedControls) => {
const modulePath =
"/src/adapters/browser-files/index.ts";
const {
createBrowserFileRuntime,
browserFilePolicyReference,
} = await import(/* @vite-ignore */ modulePath);
const input = document.createElement("input");
input.id = "capability-file-input";
input.type = "file";
const label = document.createElement("label");
label.htmlFor = input.id;
label.textContent = "PNG file";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Choose test file";
const controls = document.createElement("div");
controls.style.cssText = fixedControls;
controls.append(label, input, button);
document.body.append(controls);
const filePolicy = browserFilePolicyReference(
"avatar",
"select-inspect-preview-png",
);
const runtime = createBrowserFileRuntime({
input,
policies: [
{
reference: filePolicy,
selection: {
policyId: "avatar-v1",
purpose: "avatar",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 1024,
maxTotalBytes: 1024,
allowEmpty: false,
accept: [
{
mediaType: "image/png",
extensions: [".png"],
},
],
},
inspection: {
policyId: "png-signature-v1",
maxInspectionBytes: 16,
acceptedSignatures: [
{
mediaType: "image/png",
extensions: [".png"],
patterns: [
{
offset: 0,
bytes: [137, 80, 78, 71, 13, 10, 26, 10],
},
],
},
],
},
preview: {
allowedMediaTypes: ["image/png"],
maxPreviewBytes: 1024,
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: Object.freeze({ handoff() {} }),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
const state = globalThis as typeof globalThis & {
__browserFileResult?: Promise<unknown>;
};
button.addEventListener("click", () => {
state.__browserFileResult = (async () => {
const selected = await runtime.baselinePicker.select({
policy: filePolicy,
});
if (
!selected.ok ||
selected.value.kind !== "SELECTED" ||
selected.value.files.length !== 1
) {
runtime.dispose();
return selected;
}
const candidate = selected.value.files[0]!;
const signal = new AbortController().signal;
const inspected = await runtime.content.inspect({
ref: candidate.ref,
policy: filePolicy,
signal,
});
const range = await runtime.content.readRange({
ref: candidate.ref,
offset: 1,
length: 4,
signal,
});
const opened = await runtime.content.openSource({
ref: candidate.ref,
signal,
});
const streamed: number[] = [];
if (opened.ok) {
for await (const chunk of opened.value.stream(signal)) {
if (chunk.ok) streamed.push(...chunk.value);
}
}
const verificationReceipt = inspected.ok
? inspected.value.verificationReceipt
: null;
if (!verificationReceipt) {
runtime.dispose();
return inspected;
}
const preview = await runtime.previews.create({
ref: candidate.ref,
verificationReceipt,
policy: filePolicy,
maxPreviewBytes: 1024,
signal,
});
let previewBytes: number[] = [];
let previewProtocol: string | null = null;
if (preview.ok) {
previewProtocol = new URL(preview.value.url).protocol;
previewBytes = Array.from(
new Uint8Array(await (await fetch(preview.value.url)).arrayBuffer()),
);
preview.value.release();
}
runtime.baselinePicker.release(candidate.ref);
runtime.dispose();
return {
selected,
inspected,
range: range.ok ? Array.from(range.value) : range,
streamed,
preview: preview.ok ? { ok: true } : preview,
previewBytes,
previewProtocol,
};
})();
});
}, FIXED_CONTROLS);
const chooserPromise = page.waitForEvent("filechooser");
await page.getByRole("button", { name: "Choose test file" }).click();
const chooser = await chooserPromise;
const bytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3, 4]);
await chooser.setFiles({
name: "sample.png",
mimeType: "image/png",
buffer: bytes,
});
const result = await page.evaluate(async () => {
const state = globalThis as typeof globalThis & {
__browserFileResult?: Promise<unknown>;
};
return await state.__browserFileResult;
});
expect(result).toMatchObject({
selected: {
ok: true,
value: {
kind: "SELECTED",
files: [{ sizeBytes: bytes.byteLength, source: "NATIVE_INPUT" }],
},
},
inspected: {
ok: true,
value: {
byteLength: bytes.byteLength,
detectedMediaType: "image/png",
signature: "MATCHED",
},
},
range: [80, 78, 71, 13],
streamed: Array.from(bytes),
preview: { ok: true },
previewBytes: Array.from(bytes),
previewProtocol: "blob:",
});
});
test("hands a bounded generated Blob to the real browser download path", async ({
page,
}) => {
await page.goto("/");
await page.evaluate(async (fixedControls) => {
const modulePath = "/src/adapters/browser-files/index.ts";
const {
createBrowserFileRuntime,
createAnchorDownloadHost,
browserFilePolicyReference,
} = await import(/* @vite-ignore */ modulePath);
const input = document.createElement("input");
input.type = "file";
input.id = "unused-download-input";
const label = document.createElement("label");
label.htmlFor = input.id;
label.textContent = "Unused file control";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Download generated file";
const controls = document.createElement("div");
controls.style.cssText = fixedControls;
controls.append(label, input, button);
document.body.append(controls);
const downloadPolicy = browserFilePolicyReference(
"generated-export",
"bounded-object-url-bin",
);
const runtime = createBrowserFileRuntime({
input,
policies: [
{
reference: downloadPolicy,
download: {
strategy: "BOUNDED_OBJECT_URL",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 1024,
maxBufferedBytes: 1024,
integrity: "OPTIONAL",
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: createAnchorDownloadHost(document),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
const state = globalThis as typeof globalThis & {
__browserDownloadResult?: Promise<unknown>;
};
button.addEventListener("click", () => {
state.__browserDownloadResult = runtime.downloads
.deliver({
policy: downloadPolicy,
source: {
kind: "GENERATED",
bytes: {
byteLength: 5,
async *stream() {
yield {
ok: true as const,
value: new Uint8Array([1, 2]),
};
yield {
ok: true as const,
value: new Uint8Array([3, 4, 5]),
};
},
},
},
suggestedFileName: "report",
maxTransferBytes: 1024,
maxBufferedBytes: 1024,
signal: new AbortController().signal,
onProgress() {},
})
.finally(() => runtime.dispose());
});
}, FIXED_CONTROLS);
const downloadPromise = page.waitForEvent("download");
await page
.getByRole("button", { name: "Download generated file" })
.click();
const download = await downloadPromise;
const stream = await download.createReadStream();
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
const result = await page.evaluate(async () => {
const state = globalThis as typeof globalThis & {
__browserDownloadResult?: Promise<unknown>;
};
return await state.__browserDownloadResult;
});
expect(download.suggestedFilename()).toBe("report.bin");
expect(Buffer.concat(chunks)).toEqual(Buffer.from([1, 2, 3, 4, 5]));
expect(result).toMatchObject({
ok: true,
value: {
kind: "BROWSER_HANDOFF",
},
});
});
/**
* R3-6 / STO-08. The enhanced picker keeps `window.showOpenFilePicker` and
* calls it later. Called with the options object as receiver it would reject
* with "Illegal invocation" (TypeError → UNAVAILABLE). This spec passes the
* real, unbound function and an injected `isActive: true` reading so the app's
* own activation precheck lets the call through; with no real user gesture the
* browser must then reject with its activation error (SecurityError →
* PERMISSION_DENIED). Browsers without the API return UNSUPPORTED, because
* the capability evidence gate forbids skipped cases.
*/
test("calls the real showOpenFilePicker without a receiver and gets the activation error", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const system = (globalThis as typeof globalThis & {
showOpenFilePicker?: (options?: unknown) => Promise<unknown>;
}).showOpenFilePicker;
if (typeof system !== "function") return { kind: "UNSUPPORTED" as const };
// Playwright evaluates with a user gesture, so wait until that transient
// activation expires (5s in Chromium) to get a real "no gesture" call.
const deadline = performance.now() + 10_000;
while (navigator.userActivation.isActive && performance.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const activationExpired = !navigator.userActivation.isActive;
const errorName = async (call: () => Promise<unknown>) => {
try {
await call();
return "RESOLVED";
} catch (error) {
return error instanceof Error ? error.name : String(error);
}
};
// Controls: the native activation error, and what a wrong receiver does.
const directWithoutGesture = await errorName(() => system());
const wrongReceiver = await errorName(() =>
Reflect.apply(system, {}, []) as Promise<unknown>,
);
const modulePath = "/src/adapters/browser-files/index.ts";
const { createBrowserFileRuntime, browserFilePolicyReference } =
(await import(
/* @vite-ignore */ modulePath
)) as typeof import("../../src/adapters/browser-files/index.ts");
const input = document.createElement("input");
input.type = "file";
const filePolicy = browserFilePolicyReference("avatar", "enhanced-unbound");
const runtime = createBrowserFileRuntime({
input,
showOpenFilePicker: system as never,
userActivation: { isActive: true },
policies: [
{
reference: filePolicy,
selection: {
policyId: "avatar-v1",
purpose: "avatar",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 1024,
maxTotalBytes: 1024,
allowEmpty: false,
accept: [{ mediaType: "image/png", extensions: [".png"] }],
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: Object.freeze({ handoff() {} }),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
if (!runtime.enhancedPicker) {
throw new Error("Enhanced picker was not composed.");
}
try {
const selected = await runtime.enhancedPicker.select({
policy: filePolicy,
});
return {
kind: "SUPPORTED" as const,
activationExpired,
directWithoutGesture,
wrongReceiver,
selected,
};
} finally {
runtime.dispose();
}
});
if (result.kind === "UNSUPPORTED") {
expect(result).toEqual({ kind: "UNSUPPORTED" });
return;
}
expect(result.activationExpired).toBe(true);
expect(result.directWithoutGesture).toBe("SecurityError");
expect(result.wrongReceiver).toBe("TypeError");
expect(result.selected).toMatchObject({
ok: false,
error: { code: "PERMISSION_DENIED", operation: "FILE_SELECT" },
});
});