Playwright가 재시도하지 않아 실패가 흔들림인지 회귀인지 run에 남지
않는다. CI=true에서만 한 번 더 돌고, 재시도에서 통과해도 실패로
끝낸다. 설정 helper로만 주고 검사기가 설정 객체의 key를 거절한다.
failOnFlakyTests만으로는 재시도에서만 test.fail()에 닿은 시험의 첫
실패가 통과로 바뀐다. helper의 reporter가 실패한 시도를 따로 판정하고
다른 보고에 없는 원인을 색 코드 없이 찍는다. e2e 공유 fixture 빌드는 재시도에서 앞
시도의 실패 기록을 다시 쓰지 않는다(카드 C9). package script와 게이트
args는 029 파서와 이어 쓴 script 때문에 버렸다. CI 판별은 러너 정책이라
CI env를 읽는다.
위험·한계: 많이 깨진 run은 브라우저 게이트가 최대 약 두 배 걸린다
(추정). 명령줄 --reporter는 이 판정 reporter를 뺀다. JUnit에서 실패한
시험의 시간과 failure/error 분류는 첫 시도 기준이 된다. 검사기는 spec
안의 describe.configure({ retries })를 보지 않는다. 빌드가 실패 기록
없이 끊기면(worker 종료, hook 시간 초과) 재시도도 기다리다 실패한다.
검증: main으로 옮기기 전 트리 c8df70ab에서 test:unit 3632개, types,
lint, FE-GATE-029, verify:documentation rc=0, 변이 30개 검출. desktop
실제 브라우저: 일시 빌드 실패는 6 flaky, 계속 실패는 3 failed, 숨은
실패는 rc=1과 원인 출력. 트리 3dea9c06에서 숨은 expect 실패의 색 코드
시험이 고치기 전 1개 실패, 고친 뒤 35개 통과.
Refs: CI-FE-0001
778 lines
28 KiB
TypeScript
778 lines
28 KiB
TypeScript
import { parseAsync } from "@babel/core";
|
|
import { mkdir, readFile, readdir, stat } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { z } from "zod";
|
|
|
|
import {
|
|
computeHttpScenarioCatalogDigest,
|
|
httpScenarioExpectationSchema,
|
|
httpScenarioReceiptSchema,
|
|
sameScenarioJson,
|
|
type HttpScenarioExpectation,
|
|
type HttpScenarioReceipt,
|
|
} from "./lib/http-scenario-evidence.ts";
|
|
import { REPOSITORY_LAYOUT_FILE, selectRepositoryPaths } from "./lib/repository-layout.ts";
|
|
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
|
import { testEvidenceReportSchema } from "./lib/test-evidence-artifact.ts";
|
|
|
|
const scenarioContributionSchema = z
|
|
.object({
|
|
owner: z.string().min(1),
|
|
path: z.string().min(1),
|
|
expectationExport: z.string().min(1),
|
|
receiptPath: z.string().min(1),
|
|
receiptSchemaVersion: z.number().int().positive(),
|
|
})
|
|
.strict();
|
|
|
|
const sourceContractSchema = z
|
|
.object({
|
|
owner: z.string().min(1),
|
|
path: z.string().min(1),
|
|
requiredTokens: z.array(z.string().min(1)),
|
|
})
|
|
.strict();
|
|
|
|
const policySchema = z
|
|
.object({
|
|
schemaVersion: z.literal(2),
|
|
scenarioCatalogs: z.array(scenarioContributionSchema),
|
|
sourceContracts: z.array(sourceContractSchema),
|
|
})
|
|
.strict();
|
|
|
|
function argumentValue(name: string, fallback: string): string {
|
|
const index = process.argv.indexOf(name);
|
|
return index >= 0 && process.argv[index + 1]
|
|
? process.argv[index + 1]
|
|
: fallback;
|
|
}
|
|
|
|
function optionalArgumentValue(name: string): string | undefined {
|
|
const index = process.argv.indexOf(name);
|
|
return index >= 0 ? process.argv[index + 1] : undefined;
|
|
}
|
|
|
|
const sourceRoot = argumentValue("--source-root", "tests");
|
|
const artifactPath = argumentValue(
|
|
"--artifact",
|
|
"artifacts/quality/test-evidence.json",
|
|
);
|
|
const policyPath = argumentValue(
|
|
"--policy",
|
|
"config/testing/test-evidence.json",
|
|
);
|
|
const explicitCatalogPath = optionalArgumentValue("--catalog");
|
|
// 1112/03-03. The forbidOnly rule read only the repository's configs and ran
|
|
// only in the full check, so no fixture could show it still fires.
|
|
// `--playwright-config <file>` (repeatable) checks those files in any mode.
|
|
const explicitPlaywrightConfigs = process.argv.flatMap((argument, index) =>
|
|
argument === "--playwright-config" && process.argv[index + 1] ? [process.argv[index + 1]!] : [],
|
|
);
|
|
const explicitReceiptPath = optionalArgumentValue("--receipt");
|
|
const fixtureMode = sourceRoot !== "tests";
|
|
const sourceOnly = process.argv.includes("--source-only");
|
|
const scenarioOnly = process.argv.includes("--scenario-only");
|
|
const skipScenarioExecutions = process.argv.includes(
|
|
"--skip-scenario-executions",
|
|
);
|
|
const failures: string[] = [];
|
|
const facts = {
|
|
scannedFiles: 0,
|
|
visualBaselines: 0,
|
|
sharedScenarios: 0,
|
|
declaredScenarioExecutions: 0,
|
|
executedScenarioExecutions: 0,
|
|
playwrightConfigs: [] as string[],
|
|
};
|
|
|
|
type BabelOptions = NonNullable<Parameters<typeof parseAsync>[1]>;
|
|
type BabelParserPlugin = NonNullable<NonNullable<BabelOptions["parserOpts"]>["plugins"]>[number];
|
|
type SyntaxNode = { readonly type: string; readonly [key: string]: unknown };
|
|
|
|
// REV-FE-0003. The files Playwright runs by default (`testMatch` is
|
|
// `**/*.@(spec|test).?(c|m)[jt]s?(x)` and playwright.config.ts does not set
|
|
// it) and the forbidden fixtures.
|
|
const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?|fixture|txt)$/u;
|
|
// Code that can call skip: not text snapshots (`.txt`) or declarations (`.d.ts`).
|
|
const SKIP_CODE_PATTERN = /(?<!\.d)\.(?:[cm]?[jt]sx?|fixture)$/u;
|
|
const TEST_NAMES = new Set(["test", "it", "describe"]);
|
|
// `test.describe.skip`, `test.describe.serial`, `test.step.skip`: a member of
|
|
// a test object that is itself a test object.
|
|
const TEST_MEMBERS = new Set([...TEST_NAMES, "serial", "parallel", "step"]);
|
|
const SKIP_METHODS = new Set(["skip", "fixme"]);
|
|
const RETRY_OPTIONS = new Set(["retries", "failOnFlakyTests"]);
|
|
const SYNTAX_METADATA = new Set([
|
|
"loc",
|
|
"start",
|
|
"end",
|
|
"range",
|
|
"extra",
|
|
"comments",
|
|
"leadingComments",
|
|
"trailingComments",
|
|
"innerComments",
|
|
]);
|
|
|
|
function isSyntaxNode(value: unknown): value is SyntaxNode {
|
|
return typeof value === "object" && value !== null && typeof (value as { type?: unknown }).type === "string";
|
|
}
|
|
|
|
function syntaxChildren(node: SyntaxNode): SyntaxNode[] {
|
|
const children: SyntaxNode[] = [];
|
|
for (const [key, value] of Object.entries(node)) {
|
|
if (SYNTAX_METADATA.has(key)) continue;
|
|
for (const item of Array.isArray(value) ? value : [value]) {
|
|
if (isSyntaxNode(item)) children.push(item);
|
|
}
|
|
}
|
|
return children;
|
|
}
|
|
|
|
function walkSyntax(root: SyntaxNode, visit: (node: SyntaxNode) => void): void {
|
|
const pending = [root];
|
|
for (let node = pending.pop(); node; node = pending.pop()) {
|
|
visit(node);
|
|
pending.push(...syntaxChildren(node).reverse());
|
|
}
|
|
}
|
|
|
|
/** `name`, `"name"` or `["name"]`: the name a member or an import specifier uses. */
|
|
function staticName(node: unknown, computed = false): string | undefined {
|
|
if (!isSyntaxNode(node)) return undefined;
|
|
if (node.type === "Identifier" && !computed) return node["name"] as string;
|
|
if (node.type === "StringLiteral") return node["value"] as string;
|
|
return undefined;
|
|
}
|
|
|
|
function isMember(node: SyntaxNode): boolean {
|
|
return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
|
|
}
|
|
|
|
function isCall(node: SyntaxNode): boolean {
|
|
return node.type === "CallExpression" || node.type === "OptionalCallExpression";
|
|
}
|
|
|
|
function memberName(node: SyntaxNode): string | undefined {
|
|
return staticName(node["property"], node["computed"] === true);
|
|
}
|
|
|
|
/** The identifier a chain such as `test.describe.serial(…)` or `test.info().skip` starts from. */
|
|
function chainRoot(node: unknown): string | undefined {
|
|
let current = node;
|
|
while (isSyntaxNode(current)) {
|
|
if (current.type === "Identifier") return current["name"] as string;
|
|
if (isMember(current)) current = current["object"];
|
|
else if (isCall(current)) current = current["callee"];
|
|
else if (current.type === "TSNonNullExpression") current = current["expression"];
|
|
else return undefined;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Whether `node` is a test object whose `skip`·`fixme` skips a test: a test
|
|
* name or an import alias of one, a `testInfo` parameter, `test.info()`, a
|
|
* `test.extend(…)` result, or `test.describe`-like members of these.
|
|
*/
|
|
function isTestObject(node: unknown, names: ReadonlySet<string>): boolean {
|
|
if (!isSyntaxNode(node)) return false;
|
|
if (node.type === "Identifier") return names.has(node["name"] as string);
|
|
if (node.type === "TSNonNullExpression") return isTestObject(node["expression"], names);
|
|
if (isMember(node)) {
|
|
const name = memberName(node) ?? "";
|
|
const object = node["object"];
|
|
// `import * as strict from "…"; strict.test.skip()`.
|
|
if (TEST_NAMES.has(name) && isSyntaxNode(object) && object.type === "Identifier") {
|
|
if (names.has(`* as ${object["name"] as string}`)) return true;
|
|
}
|
|
return TEST_MEMBERS.has(name) && isTestObject(object, names);
|
|
}
|
|
if (isCall(node)) {
|
|
const callee = node["callee"];
|
|
return (
|
|
isSyntaxNode(callee) &&
|
|
isMember(callee) &&
|
|
["info", "extend"].includes(memberName(callee) ?? "") &&
|
|
isTestObject(callee["object"], names)
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function isTestInfoType(parameter: SyntaxNode): boolean {
|
|
const annotation = parameter["typeAnnotation"];
|
|
const type = isSyntaxNode(annotation) ? annotation["typeAnnotation"] : undefined;
|
|
return isSyntaxNode(type) && type.type === "TSTypeReference" && staticName(type["typeName"]) === "TestInfo";
|
|
}
|
|
|
|
/**
|
|
* Names that hold a test object in this file. Collected in source order,
|
|
* so an alias is known before the calls that use it.
|
|
*/
|
|
function testObjectNames(root: SyntaxNode): Set<string> {
|
|
const names = new Set([...TEST_NAMES, "testInfo"]);
|
|
walkSyntax(root, (node) => {
|
|
if (node.type === "ImportSpecifier") {
|
|
const imported = staticName(node["imported"]);
|
|
const local = staticName(node["local"]);
|
|
if (imported && local && TEST_NAMES.has(imported)) names.add(local);
|
|
} else if (node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") {
|
|
const local = staticName(node["local"]);
|
|
if (local) names.add(`* as ${local}`);
|
|
} else if (node.type === "ImportDeclaration" && staticName(node["source"]) === "@playwright/test") {
|
|
// `import pw from "@playwright/test"`: the default export is `test` itself.
|
|
for (const specifier of (node["specifiers"] as unknown[] | undefined) ?? []) {
|
|
if (!isSyntaxNode(specifier) || specifier.type !== "ImportDefaultSpecifier") continue;
|
|
const local = staticName(specifier["local"]);
|
|
if (local) names.add(local);
|
|
}
|
|
} else if (node.type === "VariableDeclarator") {
|
|
const local = staticName(node["id"]);
|
|
if (local && isTestObject(node["init"], names)) names.add(local);
|
|
} else if (/Function|Method/u.test(node.type)) {
|
|
for (const parameter of (node["params"] as unknown[] | undefined) ?? []) {
|
|
const local = isSyntaxNode(parameter) ? staticName(parameter) : undefined;
|
|
if (local && isSyntaxNode(parameter) && isTestInfoType(parameter)) names.add(local);
|
|
}
|
|
} else if (isCall(node) && isTestCallee(node["callee"], names)) {
|
|
// `test(title, async ({ page }, testInfo) => …)`, `test.beforeEach(…)`:
|
|
// the second parameter of a test callback is its TestInfo. Not
|
|
// `it.each(rows)(title, (a, b) => …)`, whose parameters are table data.
|
|
for (const argument of (node["arguments"] as unknown[] | undefined) ?? []) {
|
|
if (!isSyntaxNode(argument) || !/Function/u.test(argument.type)) continue;
|
|
const local = staticName((argument["params"] as unknown[] | undefined)?.[1]);
|
|
if (local) names.add(local);
|
|
}
|
|
}
|
|
});
|
|
return names;
|
|
}
|
|
|
|
function isTestCallee(callee: unknown, names: ReadonlySet<string>): boolean {
|
|
if (!isSyntaxNode(callee) || isCall(callee)) return false;
|
|
if (names.has(chainRoot(callee) ?? "")) return true;
|
|
// `strict.test(…)`, `strict.test.beforeEach(…)` after `import * as strict`,
|
|
// but not `db.withCursor(…)` after `import * as db`.
|
|
for (let current: unknown = callee; isSyntaxNode(current) && isMember(current); current = current["object"]) {
|
|
if (isTestObject(current, names)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function parserPlugins(file: string): BabelParserPlugin[] {
|
|
if (/\.[cm]?jsx?$/u.test(file)) return ["jsx"];
|
|
if (/\.[cm]?tsx$/u.test(file)) return ["typescript", "jsx"];
|
|
return ["typescript"];
|
|
}
|
|
|
|
async function parseSyntax(file: string, source: string): Promise<SyntaxNode> {
|
|
const syntaxTree = await parseAsync(source, {
|
|
filename: file,
|
|
babelrc: false,
|
|
configFile: false,
|
|
sourceType: "unambiguous",
|
|
parserOpts: { plugins: parserPlugins(file) },
|
|
});
|
|
if (!isSyntaxNode(syntaxTree)) throw new Error("Babel returned no syntax tree");
|
|
return syntaxTree;
|
|
}
|
|
|
|
/**
|
|
* Whether an object in `source` has a `retries`·`failOnFlakyTests` key: plain,
|
|
* quoted, `["retries"]` or shorthand. A comment, a string and a longer key
|
|
* ("http-retries") are none.
|
|
*/
|
|
async function setsRetryOption(file: string, source: string): Promise<boolean> {
|
|
let found = false;
|
|
walkSyntax(await parseSyntax(file, source), (node) => {
|
|
if (node.type !== "ObjectProperty" && node.type !== "ObjectMethod") return;
|
|
if (RETRY_OPTIONS.has(staticName(node["key"], node["computed"] === true) ?? "")) found = true;
|
|
});
|
|
return found;
|
|
}
|
|
|
|
/** Each `skip`·`fixme` call on a test object, as `<callee> at line <n>` (e.g. `testInfo.skip at line 3`). */
|
|
async function skipCalls(file: string, source: string): Promise<string[]> {
|
|
const syntaxTree = await parseSyntax(file, source);
|
|
const names = testObjectNames(syntaxTree);
|
|
const calls: string[] = [];
|
|
walkSyntax(syntaxTree, (node) => {
|
|
if (!isCall(node)) return;
|
|
const callee = node["callee"];
|
|
if (!isSyntaxNode(callee) || !isMember(callee)) return;
|
|
const method = memberName(callee);
|
|
if (!method || !SKIP_METHODS.has(method) || !isTestObject(callee["object"], names)) return;
|
|
const line = (node["loc"] as { start?: { line?: number } } | undefined)?.start?.line ?? 0;
|
|
const text = source.slice(callee["start"] as number, callee["end"] as number).replace(/\s+/gu, "");
|
|
calls.push(`${text.slice(0, 60)} at line ${line}`);
|
|
});
|
|
return calls;
|
|
}
|
|
|
|
async function filesBelow(target: string): Promise<string[]> {
|
|
try {
|
|
const metadata = await stat(target);
|
|
if (metadata.isFile()) return [target];
|
|
const entries = await readdir(target, { withFileTypes: true });
|
|
const groups = await Promise.all(
|
|
entries.map((entry) => filesBelow(path.join(target, entry.name))),
|
|
);
|
|
return groups.flat();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function duplicates(values: readonly string[]): string[] {
|
|
const seen = new Set<string>();
|
|
const duplicate = new Set<string>();
|
|
for (const value of values) {
|
|
if (seen.has(value)) duplicate.add(value);
|
|
seen.add(value);
|
|
}
|
|
return [...duplicate].sort();
|
|
}
|
|
|
|
function isSorted(values: readonly string[]): boolean {
|
|
return values.every(
|
|
(value, index) => index === 0 || values[index - 1]!.localeCompare(value) <= 0,
|
|
);
|
|
}
|
|
|
|
async function readJson(target: string): Promise<unknown> {
|
|
return JSON.parse(await readFile(target, "utf8"));
|
|
}
|
|
|
|
async function loadCatalogExport(
|
|
target: string,
|
|
exportName: string,
|
|
): Promise<unknown> {
|
|
if (target.endsWith(".json")) {
|
|
const document = await readJson(target);
|
|
return (document as Readonly<Record<string, unknown>>)[exportName];
|
|
}
|
|
const module = (await import(
|
|
`${pathToFileURL(path.resolve(target)).href}?test-evidence=${Date.now()}`
|
|
)) as Readonly<Record<string, unknown>>;
|
|
return module[exportName];
|
|
}
|
|
|
|
async function checkScenarioContribution(
|
|
contribution: z.output<typeof scenarioContributionSchema>,
|
|
): Promise<void> {
|
|
const catalogPath = explicitCatalogPath ?? contribution.path;
|
|
const receiptPath = explicitReceiptPath ?? contribution.receiptPath;
|
|
let expectations: readonly HttpScenarioExpectation[];
|
|
try {
|
|
expectations = z
|
|
.array(httpScenarioExpectationSchema)
|
|
.parse(
|
|
await loadCatalogExport(catalogPath, contribution.expectationExport),
|
|
);
|
|
} catch (error) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-CATALOG-SCHEMA] ${catalogPath}: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
facts.declaredScenarioExecutions += expectations.length;
|
|
facts.sharedScenarios += new Set(
|
|
expectations.map((entry) => entry.scenarioId),
|
|
).size;
|
|
const declarationIds = expectations.map((entry) => entry.executionId);
|
|
if (declarationIds.length === 0) {
|
|
failures.push(`[TEST-EVIDENCE-CATALOG-ZERO] ${catalogPath}: no declarations`);
|
|
}
|
|
const duplicateDeclarations = duplicates(declarationIds);
|
|
if (duplicateDeclarations.length > 0) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-DECLARATION-DUPLICATE] ${catalogPath}: ${duplicateDeclarations.join(", ")}`,
|
|
);
|
|
}
|
|
for (const entry of expectations) {
|
|
if (entry.executionId !== `${entry.operationId}::${entry.scenarioId}`) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXECUTION-ID-SCHEMA] ${catalogPath}: ${entry.executionId}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
let receipt: HttpScenarioReceipt;
|
|
try {
|
|
const parsedReceipt = httpScenarioReceiptSchema.safeParse(
|
|
await readJson(receiptPath),
|
|
);
|
|
if (!parsedReceipt.success) {
|
|
if (
|
|
parsedReceipt.error.issues.some((issue) =>
|
|
issue.message.includes("must be sorted by execution ID"),
|
|
)
|
|
) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXECUTION-ID-UNSORTED] ${receiptPath}`,
|
|
);
|
|
}
|
|
if (
|
|
parsedReceipt.error.issues.some((issue) =>
|
|
issue.message.includes("row IDs must exactly equal executed IDs"),
|
|
)
|
|
) {
|
|
failures.push(`[TEST-EVIDENCE-EXECUTION-ROW-DRIFT] ${receiptPath}`);
|
|
}
|
|
throw parsedReceipt.error;
|
|
}
|
|
receipt = parsedReceipt.data;
|
|
} catch (error) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-RECEIPT-SCHEMA] ${receiptPath}: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
return;
|
|
}
|
|
facts.executedScenarioExecutions += receipt.rows.length;
|
|
if (receipt.schemaVersion !== contribution.receiptSchemaVersion) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-RECEIPT-VERSION] ${receiptPath}: expected ${contribution.receiptSchemaVersion}, observed ${receipt.schemaVersion}`,
|
|
);
|
|
}
|
|
if (receipt.rows.length === 0 || receipt.executedIds.length === 0) {
|
|
failures.push(`[TEST-EVIDENCE-EXECUTION-ZERO] ${receiptPath}: no executions`);
|
|
}
|
|
if (receipt.catalogTotal !== declarationIds.length) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-CATALOG-TOTAL] ${receiptPath}: expected ${declarationIds.length}, observed ${receipt.catalogTotal}`,
|
|
);
|
|
}
|
|
const duplicateExecutedIds = duplicates(receipt.executedIds);
|
|
const rowIds = receipt.rows.map((row) => row.executionId);
|
|
const duplicateRows = duplicates(rowIds);
|
|
if (duplicateExecutedIds.length > 0 || duplicateRows.length > 0) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXECUTION-ID-DUPLICATE] ${receiptPath}: ${[...new Set([...duplicateExecutedIds, ...duplicateRows])].sort().join(", ")}`,
|
|
);
|
|
}
|
|
if (!isSorted(receipt.executedIds) || !isSorted(rowIds)) {
|
|
failures.push(`[TEST-EVIDENCE-EXECUTION-ID-UNSORTED] ${receiptPath}`);
|
|
}
|
|
if (!sameScenarioJson(receipt.executedIds, rowIds)) {
|
|
failures.push(`[TEST-EVIDENCE-EXECUTION-ROW-DRIFT] ${receiptPath}`);
|
|
}
|
|
|
|
const declared = new Set(declarationIds);
|
|
const executed = new Set(receipt.executedIds);
|
|
const missing = [...declared].filter((executionId) => !executed.has(executionId)).sort();
|
|
const extra = [...executed].filter((executionId) => !declared.has(executionId)).sort();
|
|
if (missing.length > 0) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXECUTION-ID-MISSING] ${receiptPath}: ${missing.join(", ")}`,
|
|
);
|
|
}
|
|
if (extra.length > 0) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXECUTION-ID-EXTRA] ${receiptPath}: ${extra.join(", ")}`,
|
|
);
|
|
}
|
|
|
|
const expectedDigest = computeHttpScenarioCatalogDigest(
|
|
receipt.schemaVersion,
|
|
expectations,
|
|
);
|
|
if (receipt.catalogDigest !== expectedDigest) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-CATALOG-DIGEST] ${receiptPath}: expected ${expectedDigest}, observed ${receipt.catalogDigest}`,
|
|
);
|
|
}
|
|
|
|
const declarationsById = new Map(
|
|
expectations.map((entry) => [entry.executionId, entry] as const),
|
|
);
|
|
for (const row of receipt.rows) {
|
|
const declaration = declarationsById.get(row.executionId);
|
|
if (!declaration) continue;
|
|
if (!sameScenarioJson(row.expected, declaration.expected)) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-EXPECTED-DRIFT] ${receiptPath}: ${row.executionId}`,
|
|
);
|
|
}
|
|
if (row.testDeadlineOverrideMs !== declaration.testDeadlineOverrideMs) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-DEADLINE-DRIFT] ${receiptPath}: ${row.executionId}`,
|
|
);
|
|
}
|
|
if (!sameScenarioJson(row.observed, row.expected)) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-OBSERVATION-MISMATCH] ${receiptPath}: ${row.executionId}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!scenarioOnly) {
|
|
const sourceFiles = (await filesBelow(sourceRoot)).filter(
|
|
(file) => fixtureMode || !file.split(path.sep).includes("fixtures"),
|
|
);
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
for (const file of sourceFiles) {
|
|
if (!SOURCE_FILE_PATTERN.test(file)) continue;
|
|
const source = await readFile(file, "utf8");
|
|
facts.scannedFiles += 1;
|
|
if (/\b(?:test|it|describe)(?:\.describe)?\.only\s*\(/.test(source)) {
|
|
failures.push(`${file}: focused test (.only) runs alone and hides the rest of the suite`);
|
|
}
|
|
// REV-FE-0003. A regular expression saw only `test.skip(`; it missed
|
|
// `testInfo.skip(`, `test.info().skip(` and `strictTest.skip(` after
|
|
// `import { test as strictTest }`. The syntax tree sees each call.
|
|
let skips: string[] = [];
|
|
if (SKIP_CODE_PATTERN.test(file) && /\b(?:skip|fixme)\b/u.test(source)) {
|
|
try {
|
|
skips = await skipCalls(file, source);
|
|
} catch (error) {
|
|
failures.push(
|
|
`${file}: cannot parse to look for skip/fixme: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
if (skips.length > 0) {
|
|
const quarantines = [
|
|
...source.matchAll(
|
|
/quarantine\(owner=[^)]+,\s*defect=[^)]+,\s*expires=(\d{4}-\d{2}-\d{2})\)/g,
|
|
),
|
|
];
|
|
if (quarantines.length === 0) {
|
|
failures.push(`${file}: skip/fixme lacks owned expiring quarantine (${skips.join(", ")})`);
|
|
}
|
|
for (const [, expires = ""] of quarantines) {
|
|
if (expires < today) failures.push(`${file}: quarantine expired on ${expires}`);
|
|
}
|
|
}
|
|
const wholeUiMask =
|
|
/\bmask\s*:\s*\[[\s\S]{0,240}(?:locator|getByRole)\s*\(\s*["'](?:html|body|main|application|document)["']/i;
|
|
if (wholeUiMask.test(source)) {
|
|
failures.push(`${file}: screenshot mask may not cover the whole UI`);
|
|
}
|
|
}
|
|
}
|
|
|
|
let parsedPolicy: z.output<typeof policySchema> | undefined;
|
|
if (!fixtureMode || scenarioOnly) {
|
|
try {
|
|
parsedPolicy = policySchema.parse(await readJson(policyPath));
|
|
} catch (error) {
|
|
failures.push(
|
|
`[TEST-EVIDENCE-POLICY-SCHEMA] ${policyPath}: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (parsedPolicy) {
|
|
for (const contract of parsedPolicy.sourceContracts) {
|
|
let source: string;
|
|
try {
|
|
source = await readFile(contract.path, "utf8");
|
|
} catch (error) {
|
|
failures.push(
|
|
`${contract.path}: cannot read source contract (${error instanceof Error ? error.message : String(error)})`,
|
|
);
|
|
continue;
|
|
}
|
|
for (const token of contract.requiredTokens) {
|
|
if (!source.includes(token)) {
|
|
failures.push(
|
|
`${contract.path}: ${contract.owner} evidence contract is missing ${token}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
const shouldCheckScenarioExecutions =
|
|
scenarioOnly ||
|
|
(!sourceOnly && !skipScenarioExecutions && !fixtureMode);
|
|
if (shouldCheckScenarioExecutions) {
|
|
if (parsedPolicy.scenarioCatalogs.length === 0) {
|
|
failures.push("[TEST-EVIDENCE-CATALOG-ZERO] policy has no scenario catalogs");
|
|
}
|
|
if (
|
|
(explicitCatalogPath !== undefined || explicitReceiptPath !== undefined) &&
|
|
parsedPolicy.scenarioCatalogs.length !== 1
|
|
) {
|
|
failures.push(
|
|
"[TEST-EVIDENCE-FIXTURE-SCOPE] explicit catalog/receipt requires exactly one contribution",
|
|
);
|
|
} else {
|
|
for (const contribution of parsedPolicy.scenarioCatalogs) {
|
|
await checkScenarioContribution(contribution);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A config this checkout lacks fails by name, with where it was named. The
|
|
* full check used to end on ENOENT before it wrote its report: a product that
|
|
* deletes playwright.capabilities.config.ts with its capability and keeps the
|
|
* registry entry saw a stack trace in FE-GATE-008 (fe-ci-next (3)).
|
|
*/
|
|
async function playwrightConfigFailures(
|
|
configs: readonly string[],
|
|
namedBy: "registry" | "argument",
|
|
): Promise<string[]> {
|
|
const failures: string[] = [];
|
|
for (const config of configs) {
|
|
let source: string;
|
|
try {
|
|
source = await readFile(config, "utf8");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
failures.push(
|
|
namedBy === "registry"
|
|
? `${config}: ${REPOSITORY_LAYOUT_FILE} lists it in playwright-configs, but this checkout has no such file; restore it or remove its entry`
|
|
: `${config}: --playwright-config names it, but this checkout has no such file`,
|
|
);
|
|
continue;
|
|
}
|
|
if (!source.includes("forbidOnly: true")) {
|
|
failures.push(`${config}: missing forbidOnly: true, so a committed test.only passes the gate`);
|
|
}
|
|
// FLAKY-3: a retry set anywhere but flakyJudgement() lets a test that
|
|
// passes on its retry pass the gate. A property after the spread wins, so
|
|
// any failOnFlakyTests of the config's own is refused with it. This reads
|
|
// keys; what a config evaluates to is
|
|
// tests/unit/playwright-flaky-judgement.test.ts's to judge.
|
|
if (/\b(?:retries|failOnFlakyTests)\b/u.test(source)) {
|
|
try {
|
|
if (await setsRetryOption(config, source)) {
|
|
failures.push(
|
|
`${config}: retries come only from ...flakyJudgement(), so a test that passes on its retry still fails the gate`,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
failures.push(
|
|
`${config}: cannot parse to look for retries: ${error instanceof Error ? error.message : String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
return failures;
|
|
}
|
|
|
|
// The configs the run names, in every mode but the scenario check; without
|
|
// them the full check reads the repository's and a fixture run reads none.
|
|
// A fixture run depends only on what it is given: a removal drill's copy
|
|
// deletes playwright.capabilities.config.ts but keeps its registry entry, and
|
|
// every fixture run there failed on ENOENT when it read the registry (main run
|
|
// 376, FE-GATE-030). The report lists what was read.
|
|
if (!scenarioOnly) {
|
|
// playwright.dev.config.ts spreads playwright.config.ts.
|
|
facts.playwrightConfigs = explicitPlaywrightConfigs.length > 0
|
|
? explicitPlaywrightConfigs
|
|
: fixtureMode
|
|
? []
|
|
: [...selectRepositoryPaths("playwright-configs")];
|
|
failures.push(
|
|
...(await playwrightConfigFailures(
|
|
facts.playwrightConfigs,
|
|
explicitPlaywrightConfigs.length > 0 ? "argument" : "registry",
|
|
)),
|
|
);
|
|
}
|
|
|
|
if (!fixtureMode && !scenarioOnly) {
|
|
// Without the e2e config there are no tokens to read; the config check
|
|
// above has named it when the run's configs include it (from the registry or
|
|
// --playwright-config), and this names it when they do not.
|
|
let e2eConfig: string | undefined;
|
|
try {
|
|
e2eConfig = await readFile("playwright.config.ts", "utf8");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
if (!facts.playwrightConfigs.includes("playwright.config.ts")) {
|
|
failures.push(
|
|
"playwright.config.ts: the full check reads its release evidence tokens, but this checkout has no such file",
|
|
);
|
|
}
|
|
}
|
|
for (const token of [
|
|
"pnpm build",
|
|
"pnpm preview",
|
|
"reuseExistingServer: false",
|
|
'"junit"',
|
|
'trace: "retain-on-failure"',
|
|
'"chromium-compact"',
|
|
'"firefox"',
|
|
'"webkit"',
|
|
]) {
|
|
if (e2eConfig !== undefined && !e2eConfig.includes(token)) {
|
|
failures.push(`playwright.config.ts missing release evidence token ${token}`);
|
|
}
|
|
}
|
|
// 1112/03-04. That a browser spec takes the strict fixture's `test` is an
|
|
// ESLint rule now (eslint.config.ts, tests/unit/browser-spec-imports.test.ts),
|
|
// which reads the import instead of looking for the path as text.
|
|
|
|
const baselineFiles = (await filesBelow("tests/visual/__snapshots__")).filter(
|
|
(file) => file.endsWith(".png"),
|
|
);
|
|
facts.visualBaselines = baselineFiles.length;
|
|
if (facts.visualBaselines < 4) {
|
|
failures.push("visual baseline requires at least four risk surfaces");
|
|
}
|
|
for (const required of selectRepositoryPaths("visual-evidence")) {
|
|
if ((await filesBelow(required)).length === 0) {
|
|
failures.push(`test evidence missing ${required}`);
|
|
}
|
|
}
|
|
|
|
if (!sourceOnly) {
|
|
for (const required of [
|
|
"artifacts/tests/storybook/results.xml",
|
|
"artifacts/tests/visual/results.xml",
|
|
]) {
|
|
if ((await filesBelow(required)).length === 0) {
|
|
failures.push(`test evidence missing ${required}`);
|
|
}
|
|
}
|
|
|
|
for (const required of [
|
|
"dist/index.html",
|
|
"dist/config.json",
|
|
"dist/release-manifest.json",
|
|
"dist/runtime-config.schema.json",
|
|
"dist/.vite/manifest.json",
|
|
]) {
|
|
if ((await filesBelow(required)).length === 0) {
|
|
failures.push(`built-dist contract missing ${required}`);
|
|
}
|
|
}
|
|
const sourceMaps = (await filesBelow("dist")).filter((file) =>
|
|
file.endsWith(".map"),
|
|
);
|
|
if (sourceMaps.length > 0) {
|
|
failures.push(`production dist contains source maps: ${sourceMaps.join(", ")}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const report = {
|
|
schemaVersion: 2 as const,
|
|
sourceRoot,
|
|
status: failures.length === 0 ? ("PASS" as const) : ("FAIL" as const),
|
|
facts,
|
|
failures,
|
|
};
|
|
await mkdir(path.dirname(artifactPath), { recursive: true });
|
|
await writeValidatedJsonArtifact({
|
|
path: artifactPath,
|
|
schema: testEvidenceReportSchema,
|
|
value: report,
|
|
});
|
|
if (failures.length > 0) {
|
|
process.stderr.write(`Test evidence failed:\n- ${failures.join("\n- ")}\n`);
|
|
process.exit(1);
|
|
}
|
|
process.stdout.write(
|
|
`Test evidence: PASS (${facts.scannedFiles} files, ${facts.visualBaselines} baselines, ${facts.declaredScenarioExecutions} declared/${facts.executedScenarioExecutions} executed scenarios)\n`,
|
|
);
|