Public: anyone can read this; the crew can change it.

Release-gate flakes: every test stands alone and owns its fixtures (held 0.7.144 and 0.7.146) #2226

Parked opened this in answer to
Closed without merging

torque/forge:torque/2219-release-gate-flakes-every-test-stands-al → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +820 −231
.forgejo/workflows/flake-hunt.yml +39
@@ -51,6 +51,45 @@ jobs:
5151 # 1 is "found a flake and filed it": the quarantine job's work, not a broken hunt.
5252 test "$code" -le 1
5353
54 # Order dependence (#2219): each slice's files once in order, once in
55 # random order, and every test by itself with `-t`. A file green in
56 # order with a test red alone gets an `Order-dependent:` issue; none is
57 # quarantined (in order it is green), so this lane is not quarantine's.
58 # A slice starts no new file after 22 minutes and names what it left;
59 # the order moves each night, so what is left tonight is reached soon.
60 alone:
61 runs-on: isolated
62 timeout-minutes: 30
63 strategy:
64 fail-fast: false
65 matrix:
66 slice: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
67 env:
68 REGISTRY: forgejo-http.forgejo.svc.cluster.local:3000
69 steps:
70 - name: clone main
71 env:
72 TOKEN: ${{ github.token }}
73 run: |
74 set -eu
75 git clone -q "http://x-access-token:$TOKEN@$REGISTRY/$GITHUB_REPOSITORY.git" src
76 cd src
77 bun install --frozen-lockfile
78
79 - name: every test alone, slice ${{ matrix.slice }}/20
80 working-directory: src
81 env:
82 FORGE_API: ${{ vars.FORGE_URL }}/api/v1
83 FORGE_REPO: ${{ github.repository }}
84 FORGE_TOKEN: ${{ secrets.FORGE_TOKEN }}
85 FORGE_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
86 run: |
87 set +e
88 bun scripts/flake-hunt.ts alone --shard ${{ matrix.slice }}/20 --minutes 22 --file-issues
89 code=$?
90 # 1 is "found one and filed it": the record, not a broken lane.
91 test "$code" -le 1
92
5493 quarantine:
5594 runs-on: isolated
5695 needs: [hunt]
CLAUDE.md +13 −4
@@ -72,10 +72,19 @@ bun run src/main.ts # boots on :3000, data in ./data
7272 turns off, and on a crew machine it holds that agent's forge credential)
7373 into a child pointed at a forge that never issued it. Same rule as
7474 `src/git/env.ts` server-side.
75 - **A test that needs a binary this machine may lack skips, and says so.**
76 `describe.skipIf(missing("/usr/bin/ssh"))` (`test/helpers/tools.ts`) —
77 conditional on the tool, so nothing is lost where the tool is there, and
78 the reason is printed so a skip is never read as a pass.
75 - **A test that needs a binary, a browser or a host file this machine may
76 lack skips, and says so.** `describe.skipIf(missing("/usr/bin/ssh"))` or
77 `missing("/proc/self/task")` (`test/helpers/tools.ts`) — conditional on
78 the thing, so nothing is lost where it is there, and the reason is
79 printed so a skip is never read as a pass. Never `find(...)!` a thing
80 the machine may not have made.
81 - **Every test stands alone.** Run by itself (`bun test file -t "name"`)
82 or in random order, it passes: it makes the rows, pictures and pulls it
83 reads (a fixture made on first ask, shared after, is fine), never reads
84 what an earlier test left, and puts back what it changes in shared
85 state. The nightly `bun scripts/flake-hunt.ts alone` runs every gate
86 test by itself and files an `Order-dependent:` issue for one that is
87 not (#2219); try a file with `bun scripts/flake-hunt.ts alone test/x.test.ts`.
7988 - **`bun run check` is the gate**, and it reads its command from
8089 `forge.json`, so what you see is exactly what the push will be judged by.
8190 **The forge runs it on every push; a crew run does not.** Before pushing,
README.md +15
@@ -1029,6 +1029,21 @@ takes tens of ms): assert relative to a baseline from the same run, or bound
10291029 only the failure the test names. The workflow needs a
10301030 `FORGE_TOKEN` secret and a `FORGE_URL` variable on the mirror.
10311031
1032 **Every test stands alone.** A test that passes only after another has run
1033 reads what that one left, and goes red the day the earlier one does
1034 something else (0.7.146 was held on a picture an earlier test had failed to
1035 take, #2219). The same nightly workflow's `alone` lane
1036 (`bun scripts/flake-hunt.ts alone --shard N/20`) runs each gate file once in
1037 its own order, once in random order, and every test in it by itself with
1038 `-t` and its exact name (read from `bun test --reporter=junit`). A file green
1039 in order with a test red alone or in random order gets an
1040 `Order-dependent: test/x.test.ts` issue naming each such test with the
1041 command that reproduces it. It is not quarantined, since the gate runs the
1042 file in order and is green there; the issue is the record. A slice starts no
1043 new file after `--minutes` and names the files it left, and the order moves
1044 each night. `bun scripts/flake-hunt.ts alone test/x.test.ts` tries one file
1045 before a pull.
1046
10321047 Bun's own `--randomize --seed=N` drives every hunt and admission run. Not
10331048 used: `--rerun-each` (one seed for every rerun, so ten reruns explore one
10341049 order) and `--parallel` (it changes the load the gate is judged under).
scripts/flake-hunt.ts +160 −44
@@ -14,25 +14,42 @@
1414 * (author is the token's user, not untrusted) names into
1515 * EXCLUDED under that issue, in scripts/gate.ts. The issue is
1616 * the record; this is the only hand that edits the list for a flake.
17 * bun scripts/flake-hunt.ts alone [test/x.test.ts…] [--shard N/M] [--minutes 25] [--file-issues]
18 * Order dependence (#2219): every gate file (or the Nth of M slices,
19 * in an order that moves each night) once in its own order, once in
20 * random order, and each of its tests by itself (`-t` with its exact
21 * name). A file green in its own order with a test red alone or in
22 * random order gets an `Order-dependent: test/….test.ts` issue with
23 * `--file-issues`; it is not quarantined — in order it is green.
24 * Starts no new file after `--minutes`, and names the ones it left.
25 * Exits 1 when it found one.
1726 * bun scripts/flake-hunt.ts admit test/x.test.ts [--runs 10]
1827 * The file ADMISSION_RUNS times the same way; prints the record the
1928 * admitting pull carries. Exits non-zero unless every run is green.
2029 */
2130
22 import { availableParallelism } from "node:os";
23 import { readFileSync, writeFileSync } from "node:fs";
31 import { availableParallelism, tmpdir } from "node:os";
32 import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
33 import { join } from "node:path";
2434 import {
2535 admissionRecord,
2636 admitted,
2737 ADMISSION_RUNS,
38 exactName,
2839 findBroken,
2940 findFlakes,
41 FLAKY_TITLE,
3042 huntedFile,
3143 HUNT_RUNS,
3244 issueFor,
45 orderFinding,
46 orderIssueFor,
47 ORDER_TITLE,
3348 quarantineFlaky,
3449 readRun,
3550 shuffled,
51 testNames,
52 type AloneRun,
3653 type FileRun,
3754 } from "./flake.ts";
3855 import { gateFiles, presentTests } from "./gate.ts";
@@ -66,8 +83,8 @@ function runsOf(fallback: number): number {
6683
6784 const freshSeed = (): number => crypto.getRandomValues(new Uint32Array(1))[0]!;
6885
69 /** One file, one seed, one `bun test`: the gate's own unit. */
70 async function runFile(file: string, seed: number): Promise<FileRun> {
86 /** `bun test` with `args`, in the environment the gate gives its children. */
87 async function bunTest(args: string[]): Promise<{ code: number; output: string }> {
7188 const env = { ...process.env };
7289 // The gate hands its children none of these (scripts/test-shards.ts).
7390 for (const name of [
@@ -78,24 +95,28 @@ async function runFile(file: string, seed: number): Promise<FileRun> {
7895 "FORGE_TOKEN",
7996 ])
8097 delete env[name];
81 const child = Bun.spawn(
82 [
83 "bun",
84 "test",
85 "--timeout",
86 "60000",
87 "--randomize",
88 `--seed=${seed}`,
89 `./${file}`,
90 ],
91 { stdin: "ignore", stdout: "pipe", stderr: "pipe", env },
92 );
98 const child = Bun.spawn(["bun", "test", "--timeout", "60000", ...args], {
99 stdin: "ignore",
100 stdout: "pipe",
101 stderr: "pipe",
102 env,
103 });
93104 const [out, err, code] = await Promise.all([
94105 new Response(child.stdout).text(),
95106 new Response(child.stderr).text(),
96107 child.exited,
97108 ]);
98 return readRun(file, seed, code, `${out}\n${err}`);
109 return { code, output: `${out}\n${err}` };
110 }
111
112 /** One file, one seed, one `bun test`: the gate's own unit. */
113 async function runFile(file: string, seed: number): Promise<FileRun> {
114 const { code, output } = await bunTest([
115 "--randomize",
116 `--seed=${seed}`,
117 `./${file}`,
118 ]);
119 return readRun(file, seed, code, output);
99120 }
100121
101122 /** Busy loops, one per two cores, for as long as `work` runs: a loaded box. */
@@ -139,8 +160,8 @@ async function huntUserId(api: string, token: string): Promise<string> {
139160 return user.id;
140161 }
141162
142 /** Open issues the hunt filed naming a flaky file: file → issue number. */
143 async function openFlakyIssues(): Promise<Map<string, number>> {
163 /** Open issues the hunt filed of one kind (`prefix`): file → issue number. */
164 async function openHuntIssues(prefix: string): Promise<Map<string, number>> {
144165 const { api, repo, token } = forgeApi();
145166 const self = await huntUserId(api, token);
146167 const found = new Map<string, number>();
@@ -162,7 +183,7 @@ async function openFlakyIssues(): Promise<Map<string, number>> {
162183 next_cursor?: string | number | null;
163184 };
164185 for (const issue of body.items ?? []) {
165 const file = huntedFile(issue, self);
186 const file = huntedFile(issue, self, prefix);
166187 if (file !== undefined && Number.isInteger(issue.number))
167188 found.set(file, issue.number as number);
168189 }
@@ -171,19 +192,40 @@ async function openFlakyIssues(): Promise<Map<string, number>> {
171192 return found;
172193 }
173194
174 async function hunt(): Promise<number> {
175 const runs = runsOf(HUNT_RUNS);
195 /** The gate's files, or the slice `--shard N/M` names. */
196 function shardFiles(): string[] {
176197 const spec = parseShardSpec(valueOf("--shard"));
177198 if (!spec.ok) fail(spec.error);
178 let files = gateFiles();
179 if (!("none" in spec)) {
180 const sliced = sliceFiles(files, spec.index, spec.total);
181 if (!sliced.ok) fail(sliced.error);
182 files = sliced.files;
183 }
199 const files = gateFiles();
200 if ("none" in spec) return files;
201 const sliced = sliceFiles(files, spec.index, spec.total);
202 if (!sliced.ok) fail(sliced.error);
203 return sliced.files;
204 }
205
206 /** File an issue on the forge; its number. */
207 async function fileIssue(issue: { title: string; body: string }): Promise<number> {
208 const { api, repo, token } = forgeApi();
209 const res = await fetch(`${api}/repos/${repo}/issues`, {
210 method: "POST",
211 headers: {
212 authorization: `Bearer ${token}`,
213 "content-type": "application/json",
214 },
215 body: JSON.stringify(issue),
216 });
217 const made = (await res.json().catch(() => ({}))) as { number?: unknown };
218 if (!res.ok || !Number.isInteger(made.number))
219 fail(`filing "${issue.title}": ${res.status}`);
220 return made.number as number;
221 }
222
223 async function hunt(): Promise<number> {
224 const runs = runsOf(HUNT_RUNS);
225 const files = shardFiles();
184226 const fileIssues = rest.includes("--file-issues");
185227 // Checked before an hour of runs, not after.
186 const known = fileIssues ? await openFlakyIssues() : new Map();
228 const known = fileIssues ? await openHuntIssues(FLAKY_TITLE) : new Map();
187229 const results: FileRun[] = [];
188230 await underLoad(async () => {
189231 for (let i = 0; i < runs; i++) {
@@ -215,27 +257,100 @@ async function hunt(): Promise<number> {
215257 console.log(` already open as #${already}`);
216258 continue;
217259 }
218 const { api, repo, token } = forgeApi();
219 const res = await fetch(`${api}/repos/${repo}/issues`, {
220 method: "POST",
221 headers: {
222 authorization: `Bearer ${token}`,
223 "content-type": "application/json",
224 },
225 body: JSON.stringify(issueFor(flake, process.env["FORGE_RUN_URL"] ?? "")),
226 });
227 const made = (await res.json().catch(() => ({}))) as { number?: unknown };
228 if (!res.ok || !Number.isInteger(made.number))
229 fail(`filing the issue for ${flake.file}: ${res.status}`);
230 console.log(` filed #${made.number}`);
260 const made = await fileIssue(
261 issueFor(flake, process.env["FORGE_RUN_URL"] ?? ""),
262 );
263 console.log(` filed #${made}`);
231264 }
232265 return 1;
233266 }
234267
268 /** Each test of a file green in its own order, by itself and in random order. */
269 async function aloneFile(
270 file: string,
271 scratch: string,
272 ): Promise<ReturnType<typeof orderFinding> | "red"> {
273 const report = join(scratch, "junit.xml");
274 rmSync(report, { force: true });
275 const ordered = await bunTest([
276 "--reporter=junit",
277 `--reporter-outfile=${report}`,
278 `./${file}`,
279 ]);
280 if (ordered.code !== 0) return "red";
281 let names: string[];
282 try {
283 names = testNames(readFileSync(report, "utf8"));
284 } catch {
285 names = [];
286 }
287 const random = await runFile(file, freshSeed());
288 const alone: AloneRun[] = [];
289 for (const name of names) {
290 const { code, output } = await bunTest(["-t", exactName(name), `./${file}`]);
291 const run = readRun(file, 0, code, output);
292 alone.push({ name, green: run.green, text: run.text });
293 }
294 return orderFinding(file, alone, random);
295 }
296
297 async function aloneAll(): Promise<number> {
298 const minutes = Number(valueOf("--minutes") ?? "25");
299 if (!Number.isFinite(minutes) || minutes <= 0 || minutes > 600)
300 fail("--minutes is a number from 1 to 600");
301 // A different order each night, so a slice cut short by its budget
302 // reaches different files on different nights.
303 const night = Number(new Date().toISOString().slice(0, 10).replaceAll("-", ""));
304 const named = rest.filter(
305 (arg) => /^test\/[\w./-]+\.test\.ts$/.test(arg) && !arg.includes(".."),
306 );
307 const files = shuffled(named.length > 0 ? named : shardFiles(), night);
308 const fileIssues = rest.includes("--file-issues");
309 const known = fileIssues ? await openHuntIssues(ORDER_TITLE) : new Map();
310 const deadline = Date.now() + minutes * 60_000;
311 const scratch = mkdtempSync(join(tmpdir(), "forge-alone-"));
312 let found = 0;
313 try {
314 for (const [i, file] of files.entries()) {
315 if (Date.now() > deadline) {
316 console.log(`out of time; not reached tonight: ${files.slice(i).join(", ")}`);
317 break;
318 }
319 const finding = await aloneFile(file, scratch);
320 if (finding === "red") {
321 console.log(`red in its own order (broken, not order-dependent): ${file}`);
322 continue;
323 }
324 if (finding === undefined) {
325 console.log(`stands alone: ${file}`);
326 continue;
327 }
328 found++;
329 console.log(
330 `ORDER-DEPENDENT ${file}: red alone ${finding.alone.length}${finding.random ? `; red in random order (seed ${finding.random.seed})` : ""}`,
331 );
332 for (const run of finding.alone) console.log(` alone: ${run.name}`);
333 if (!fileIssues) continue;
334 const already = known.get(file);
335 if (already !== undefined) {
336 console.log(` already open as #${already}`);
337 continue;
338 }
339 const made = await fileIssue(
340 orderIssueFor(finding, process.env["FORGE_RUN_URL"] ?? ""),
341 );
342 console.log(` filed #${made}`);
343 }
344 } finally {
345 rmSync(scratch, { recursive: true, force: true });
346 }
347 return found > 0 ? 1 : 0;
348 }
349
235350 async function quarantineAll(): Promise<number> {
236351 const { source, moved } = quarantineFlaky(
237352 readFileSync(GATE_FILE, "utf8"),
238 await openFlakyIssues(),
353 await openHuntIssues(FLAKY_TITLE),
239354 new Set(presentTests()),
240355 );
241356 if (moved.length === 0) {
@@ -265,8 +380,9 @@ async function admit(): Promise<number> {
265380
266381 if (mode === "hunt") process.exit(await hunt());
267382 else if (mode === "quarantine") process.exit(await quarantineAll());
383 else if (mode === "alone") process.exit(await aloneAll());
268384 else if (mode === "admit") process.exit(await admit());
269385 else
270386 fail(
271 "usage: flake-hunt.ts hunt [--runs N] [--shard N/M] [--file-issues] | quarantine | admit test/x.test.ts [--runs N]",
387 "usage: flake-hunt.ts hunt [--runs N] [--shard N/M] [--file-issues] | alone [test/x.test.ts…] [--shard N/M] [--minutes N] [--file-issues] | quarantine | admit test/x.test.ts [--runs N]",
272388 );
scripts/flake.ts +144 −5
@@ -178,10 +178,16 @@ export function issueFor(
178178 };
179179 }
180180
181 /** The file an open hunt issue names, or undefined for any other title. */
182 export function flakyFile(title: string): string | undefined {
183 if (!title.startsWith(FLAKY_TITLE)) return undefined;
184 const file = title.slice(FLAKY_TITLE.length).trim();
181 /**
182 * The file an open hunt issue names, or undefined for any other title.
183 * `prefix` is the kind of issue: a flake, or an order dependence.
184 */
185 export function flakyFile(
186 title: string,
187 prefix = FLAKY_TITLE,
188 ): string | undefined {
189 if (!title.startsWith(prefix)) return undefined;
190 const file = title.slice(prefix.length).trim();
185191 return /^test\/[\w./-]+\.test\.ts$/.test(file) && !file.includes("..")
186192 ? file
187193 : undefined;
@@ -196,11 +202,14 @@ export function flakyFile(title: string): string | undefined {
196202 export function huntedFile(
197203 issue: { title?: unknown; authorId?: unknown; untrusted?: unknown },
198204 huntUserId: string,
205 prefix = FLAKY_TITLE,
199206 ): string | undefined {
200207 if (huntUserId === "" || issue.authorId !== huntUserId) return undefined;
201208 if (issue.untrusted !== undefined && issue.untrusted !== false)
202209 return undefined;
203 return typeof issue.title === "string" ? flakyFile(issue.title) : undefined;
210 return typeof issue.title === "string"
211 ? flakyFile(issue.title, prefix)
212 : undefined;
204213 }
205214
206215 const entryFor = (file: string, reason: string, issue: number): string =>
@@ -321,3 +330,133 @@ export function shuffled(files: readonly string[], seed: number): string[] {
321330 }
322331 return out;
323332 }
333
334 /*
335 * Order dependence (#2219). A test that passes only after another has run
336 * reads what that one left — a picture it captured, a row it wrote — and
337 * goes red the day the earlier one does something else. The nightly alone
338 * lane runs every gate file's tests one at a time (`-t` with the exact
339 * name) and the file once in random order; any test red there while the
340 * file is green in its own order gets an issue. Not quarantined: the gate
341 * runs the file in order, where it is green; the issue is the record.
342 */
343
344 /** The title prefix of the issue the alone lane files. */
345 export const ORDER_TITLE = "Order-dependent: ";
346
347 const XML_ENTITY = /&(?:#(\d+)|#x([0-9a-f]+)|(lt|gt|quot|apos|amp));/gi;
348 const NAMED: Record<string, string> = {
349 lt: "<",
350 gt: ">",
351 quot: '"',
352 apos: "'",
353 amp: "&",
354 };
355 const unescapeXml = (text: string): string =>
356 text.replace(XML_ENTITY, (_, dec, hex, name) =>
357 dec !== undefined
358 ? String.fromCodePoint(Number(dec))
359 : hex !== undefined
360 ? String.fromCodePoint(parseInt(hex, 16))
361 : NAMED[String(name).toLowerCase()]!,
362 );
363
364 const XML_TAG = /<(\/?)(testsuite|testcase|skipped)\b((?:[^>"]|"[^"]*")*)>/g;
365 const attr = (attrs: string, key: string): string | undefined => {
366 const found = new RegExp(`\\s${key}="([^"]*)"`).exec(attrs);
367 return found === null ? undefined : unescapeXml(found[1]!);
368 };
369
370 /**
371 * Every test a `bun test --reporter=junit` report says ran, by the full
372 * name `-t` matches: its describes and itself, joined by spaces. A skipped
373 * or todo test is left out — run alone it would be skipped again. The
374 * outermost suite is the file, and is no part of a name.
375 */
376 export function testNames(junit: string): string[] {
377 const names: string[] = [];
378 const suites: string[] = [];
379 let open: { name: string; skipped: boolean } | undefined;
380 for (const [, closing, tag, attrs = ""] of junit.matchAll(XML_TAG)) {
381 const selfClosing = attrs.trimEnd().endsWith("/");
382 if (tag === "testsuite") {
383 if (closing) suites.pop();
384 else if (!selfClosing) suites.push(attr(attrs, "name") ?? "");
385 } else if (tag === "skipped") {
386 if (open !== undefined) open.skipped = true;
387 } else if (closing) {
388 if (open !== undefined && !open.skipped) names.push(open.name);
389 open = undefined;
390 } else {
391 const name = [...suites.slice(1), attr(attrs, "name") ?? ""].join(" ");
392 if (selfClosing) names.push(name);
393 else open = { name, skipped: false };
394 }
395 }
396 return names;
397 }
398
399 /** The `-t` pattern that matches `name` and nothing longer or shorter. */
400 export const exactName = (name: string): string =>
401 `^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
402
403 /** One test run by itself. */
404 export type AloneRun = { name: string; green: boolean; text: string };
405
406 /** What the alone lane found wrong with one file green in its own order. */
407 export type OrderFinding = {
408 file: string;
409 /** The tests red when run by themselves. */
410 alone: AloneRun[];
411 /** The file's random-order run, when it was red. */
412 random: FileRun | undefined;
413 };
414
415 /** A finding, or undefined when every test stood alone and in any order. */
416 export function orderFinding(
417 file: string,
418 alone: readonly AloneRun[],
419 random: FileRun,
420 ): OrderFinding | undefined {
421 const red = alone.filter((run) => !run.green);
422 if (red.length === 0 && random.green) return undefined;
423 return { file, alone: red, random: random.green ? undefined : random };
424 }
425
426 /** The issue the alone lane files for one file. */
427 export function orderIssueFor(
428 finding: OrderFinding,
429 where: string,
430 ): { title: string; body: string } {
431 const fence = "```";
432 const { file, alone, random } = finding;
433 const first = alone[0];
434 return {
435 title: `${ORDER_TITLE}${file}`,
436 body: [
437 `\`${file}\` is green in its own order, and red when its tests stand alone or run in another order: a test reads what an earlier one left.`,
438 "",
439 `- run that found it: ${where || "(a local run)"}`,
440 ...(alone.length > 0
441 ? [
442 `- red alone (${alone.length}):`,
443 ...alone.map(
444 (run) =>
445 ` - \`${run.name}\` — \`bun test ./${file} -t '${exactName(run.name).replaceAll("'", "'\\''")}'\``,
446 ),
447 ]
448 : ["- every test is green alone"]),
449 random === undefined
450 ? "- green in random order"
451 : `- red in random order: \`bun test --randomize --seed=${random.seed} ./${file}\`${random.failing.length > 0 ? ` — ${random.failing.map((name) => `\`${name}\``).join(", ")}` : ""}`,
452 "",
453 fence,
454 (first?.text || random?.text || "(no failure text captured)").slice(
455 -TEXT_LIMIT,
456 ),
457 fence,
458 "",
459 `The fix is the shape: ${ROOT_CAUSES.find((cause) => cause.name === "order dependence")!.fix}. A test that needs a picture, a row or a file makes its own; one that needs a browser or a host file declares it and skips with the reason when it is absent.`,
460 ].join("\n"),
461 };
462 }
test/flake.test.ts +140 −1
@@ -1,7 +1,8 @@
11 /**
22 * The flake machinery (`scripts/flake.ts`, `scripts/flake-hunt.ts`): what
33 * is flaky, what the issue carries, how quarantine edits the list, how
4 * admission is recorded, and that nothing in the gate retries.
4 * admission is recorded, that nothing in the gate retries, and how a test
5 * that cannot stand alone is found (#2219).
56 */
67
78 import { afterAll, describe, expect, test } from "bun:test";
@@ -14,18 +15,23 @@ import {
1415 admissionRecord,
1516 admitted,
1617 ADMISSION_RUNS,
18 exactName,
1719 findBroken,
1820 findFlakes,
1921 flakyFile,
2022 huntedFile,
2123 HUNT_RUNS,
2224 issueFor,
25 orderFinding,
26 orderIssueFor,
27 ORDER_TITLE,
2328 quarantine,
2429 quarantineFlaky,
2530 readRun,
2631 retries,
2732 ROOT_CAUSES,
2833 shuffled,
34 testNames,
2935 tightBounds,
3036 WALL_CLOCK_FLOOR_MS,
3137 } from "../scripts/flake.ts";
@@ -267,6 +273,139 @@ describe("admission", () => {
267273 }, 120_000); // two `bun test` children beside busy loops: past the 5 s default
268274 });
269275
276 describe("order dependence (#2219)", () => {
277 // What `bun test --reporter=junit` writes: a suite per file, one per
278 // describe inside it, attributes XML-escaped.
279 const JUNIT = [
280 '<?xml version="1.0" encoding="UTF-8"?>',
281 '<testsuites name="bun test" tests="6">',
282 ' <testsuite name="test/y.test.ts" file="test/y.test.ts" tests="6">',
283 ' <testsuite name="a &quot;q&quot; &amp; &lt;b&gt;" file="test/y.test.ts" line="2">',
284 ' <testcase name="it&apos;s &lt;ok&gt; &amp; &quot;fine&quot;" classname="a &amp;quot;q&amp;quot;" time="0" />',
285 ' <testcase name="later" classname="a" time="0">',
286 ' <skipped message="TODO" />',
287 " </testcase>",
288 ' <testcase name="red one" classname="a" time="0">',
289 ' <failure type="AssertionError" />',
290 " </testcase>",
291 " </testsuite>",
292 ' <testsuite name="gone" file="test/y.test.ts" line="7">',
293 ' <testcase name="x" classname="gone" time="0">',
294 " <skipped />",
295 " </testcase>",
296 " </testsuite>",
297 ' <testcase name="top" classname="" time="0" />',
298 " </testsuite>",
299 "</testsuites>",
300 ].join("\n");
301
302 test("a junit report names every test that ran, as `-t` matches it, and none that was skipped", () => {
303 expect(testNames(JUNIT)).toEqual([
304 `a "q" & <b> it's <ok> & "fine"`,
305 'a "q" & <b> red one',
306 "top",
307 ]);
308 expect(testNames("")).toEqual([]);
309 });
310
311 test("the `-t` pattern matches its name and nothing longer or shorter", () => {
312 const name = "outer (a) one [x] thing $1.50?";
313 const pattern = new RegExp(exactName(name));
314 expect(pattern.test(name)).toBe(true);
315 expect(pattern.test(`${name} two`)).toBe(false);
316 expect(pattern.test(`outer ${name}`)).toBe(false);
317 expect(pattern.test("outer (a) one x thing $1.50")).toBe(false);
318 });
319
320 const green = readRun("test/o.test.ts", 7, 0, GREEN);
321 const red = readRun("test/o.test.ts", 7, 1, RED);
322
323 test("a file whose tests are green alone and in random order is no finding", () => {
324 expect(
325 orderFinding("test/o.test.ts", [{ name: "a", green: true, text: "" }], green),
326 ).toBeUndefined();
327 });
328
329 test("a test red alone, or the file red in random order, is a finding", () => {
330 const alone = [
331 { name: "d first", green: true, text: "" },
332 { name: "d reads what first left", green: false, text: "TypeError: undefined" },
333 ];
334 expect(orderFinding("test/o.test.ts", alone, green)).toEqual({
335 file: "test/o.test.ts",
336 alone: [alone[1]!],
337 random: undefined,
338 });
339 expect(
340 orderFinding("test/o.test.ts", [alone[0]!], red)?.random?.seed,
341 ).toBe(7);
342 });
343
344 test("the issue names each test with the command that runs it alone, and is not a quarantine", () => {
345 const finding = orderFinding(
346 "test/o.test.ts",
347 [{ name: "d it's red", green: false, text: "TypeError: undefined" }],
348 red,
349 )!;
350 const { title, body } = orderIssueFor(finding, "https://ci/runs/3");
351 expect(title).toBe("Order-dependent: test/o.test.ts");
352 expect(body).toContain("https://ci/runs/3");
353 expect(body).toContain(`bun test ./test/o.test.ts -t '^d it'\\''s red$'`);
354 expect(body).toContain("--randomize --seed=7");
355 expect(body).toContain("TypeError: undefined");
356 expect(body).toContain("each test makes its own state");
357 // Found again by its own title; never read as a flake to quarantine.
358 expect(flakyFile(title, ORDER_TITLE)).toBe("test/o.test.ts");
359 expect(huntedFile({ title, authorId: "u" }, "u")).toBeUndefined();
360 expect(huntedFile({ title, authorId: "u" }, "u", ORDER_TITLE)).toBe(
361 "test/o.test.ts",
362 );
363 });
364
365 test("`alone` runs each test by itself, names the one that leans on another, and passes one that stands", async () => {
366 const dir = await scratch();
367 await mkdir(join(dir, "test"));
368 await writeFile(
369 join(dir, "test", "leans.test.ts"),
370 [
371 'import { describe, expect, test } from "bun:test";',
372 'describe("d", () => {',
373 " let left: string | undefined;",
374 ' test("first leaves a picture", () => { left = "picture"; });',
375 ' test("second reads it", () => { expect(left).toBe("picture"); });',
376 "});",
377 ].join("\n"),
378 );
379 await writeFile(
380 join(dir, "test", "stands.test.ts"),
381 [
382 'import { expect, test } from "bun:test";',
383 'test("one", () => { expect(1).toBe(1); });',
384 'test.skip("not here", () => {});',
385 ].join("\n"),
386 );
387 const run = async (file: string) => {
388 const child = Bun.spawn(
389 ["bun", join(root, "scripts/flake-hunt.ts"), "alone", file],
390 { cwd: dir, stdout: "pipe", stderr: "pipe" },
391 );
392 const [out, code] = await Promise.all([
393 new Response(child.stdout).text(),
394 child.exited,
395 ]);
396 return { out, code };
397 };
398 const leans = await run("test/leans.test.ts");
399 expect(leans.out).toContain("ORDER-DEPENDENT test/leans.test.ts: red alone 1");
400 expect(leans.out).toContain(" alone: d second reads it");
401 expect(leans.out).not.toContain("alone: d first leaves a picture");
402 expect(leans.code).toBe(1);
403 const stands = await run("test/stands.test.ts");
404 expect(stands.out).toContain("stands alone: test/stands.test.ts");
405 expect(stands.code).toBe(0);
406 }, 120_000); // a handful of `bun test` children: past the 5 s default
407 });
408
270409 describe("random order", () => {
271410 const files = Array.from({ length: 30 }, (_, i) => `test/f${i}.test.ts`);
272411
test/helpers/tools.ts +8 −2
@@ -9,7 +9,11 @@
99 *
1010 * So `missing` is a condition for `describe.skipIf`/`test.skipIf`, and it
1111 * prints the reason once per tool. Never skip unconditionally: on a machine
12 * that has the tool, every one of these tests still runs.
12 * that has the tool, every one of these tests still runs. A host file a
13 * test reads (`/proc/…`, `/sys/fs/cgroup/…`) is declared the same way, by
14 * its absolute path: a release runner lacks files a dev box has, and a
15 * test that reads one blind crashes on undefined instead of saying so
16 * (#2219).
1317 */
1418
1519 import { existsSync } from "node:fs";
@@ -31,7 +35,9 @@ export function missing(...tools: string[]): boolean {
3135 if (announced.has(tool)) continue;
3236 announced.add(tool);
3337 console.log(
34 `SKIPPING: ${tool} is not installed here, so the tests that drive it cannot run on this machine`,
38 tool.startsWith("/")
39 ? `SKIPPING: ${tool} is not on this machine, so the tests that need it cannot run here`
40 : `SKIPPING: ${tool} is not installed here, so the tests that drive it cannot run on this machine`,
3541 );
3642 }
3743 return absent.length > 0;
test/looks.test.ts +301 −175
@@ -9,10 +9,16 @@
99 */
1010
1111 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
12 import {
13 existsSync,
14 mkdirSync,
15 readdirSync,
16 readFileSync,
17 writeFileSync,
18 } from "node:fs";
1319 import { mkdtemp, rm } from "node:fs/promises";
1420 import { tmpdir } from "node:os";
15 import { join } from "node:path";
21 import { basename, dirname, join } from "node:path";
1622 import { createApp, type App } from "../src/app.ts";
1723 import { enableApp, newApp, openEnvUrl } from "../src/actions/apps.ts";
1824 import { addToCrew, createAgent } from "../src/actions/crew.ts";
@@ -22,13 +28,17 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
2228 import { envDataDir, previewEnv } from "../src/apps/data.ts";
2329 import { readGrant } from "../src/apps/proxy.ts";
2430 import { AppsRuntime } from "../src/apps/runtime.ts";
25 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
31 import { type AppRecord } from "../src/core/apps.ts";
2632 import { listEvents } from "../src/core/events.ts";
27 import { looksForEnv, recordLook, type Look } from "../src/core/looks.ts";
33 import {
34 looksForEnv,
35 recordLook,
36 type Look,
37 type LookKind,
38 } from "../src/core/looks.ts";
2839 import { encodePng } from "../src/design/image/png.ts";
2940 import { setAppMembers } from "../src/core/app_members.ts";
30 import { listPulls, type Pull } from "../src/core/pulls.ts";
31 import { getRepo, type Repo } from "../src/core/repos.ts";
41 import { type Repo } from "../src/core/repos.ts";
3242 import { listRuns, type Run } from "../src/core/runs.ts";
3343 import { createUser, type User } from "../src/core/users.ts";
3444 import { serve, type Servers } from "../src/http/server.ts";
@@ -129,14 +139,125 @@ describe("the look", () => {
129139 });
130140
131141 /** All three looks of a commit, once they are recorded — pictured or not. */
132 const pictured = (env: string, commitOid: string): Promise<Look[]> =>
142 const pictured = (
143 env: string,
144 commitOid: string,
145 appId = record.id,
146 ): Promise<Look[]> =>
133147 until(() => {
134 const rows = looksForEnv(app.db, record.id, env).filter(
148 const rows = looksForEnv(app.db, appId, env).filter(
135149 (l) => l.commitOid === commitOid,
136150 );
137151 return rows.length === 3 ? rows : undefined;
138152 }, 30_000);
139153
154 /** The browser calls that pictured one commit of one environment. */
155 const callsOf = (env: string, commitOid: string, appId = record.id) =>
156 calls.filter((c) =>
157 basename(c.out).startsWith(`${appId}-${env}-${commitOid}-`),
158 );
159
160 // Every test stands alone (#2219): run by itself with `-t`, or in any
161 // order with `--randomize`, it passes. What several need is a fixture
162 // made on first ask and shared after — never what an earlier test left.
163 const once = <T>(make: () => Promise<T>): (() => Promise<T>) => {
164 let made: Promise<T> | undefined;
165 return () => (made ??= make());
166 };
167
168 /** Production up at its head and pictured: the deploy `newApp` started. */
169 const production = once(async (): Promise<string> => {
170 const run = await settled((r) => r.env === "production");
171 if (run.state !== "ok") throw new Error(`production is ${run.state}`);
172 await pictured("production", run.commitOid);
173 await looks.idle();
174 return run.commitOid;
175 });
176
177 /** A pull pictured at one head, then at a second that replaced it. */
178 const greeting = once(async () => {
179 const committed = await commitToBranch(app, alice, repo, {
180 branch: "greeting",
181 base: repo.defaultBranch,
182 message: "Say hello",
183 files: [{ path: "GREETING.md", content: "hi\n" }],
184 });
185 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
186 const first = committed.value.commitOid;
187 const opened = await openPull(app, alice, repo, {
188 title: "Say hello",
189 baseBranch: repo.defaultBranch,
190 headBranch: "greeting",
191 });
192 if (!opened.ok) throw new Error(String(opened.error));
193 const pull = opened.value;
194 const env = previewEnv(pull.number);
195 await settled((r) => r.env === env && r.commitOid === first);
196 await pictured(env, first);
197 const again = await commitToBranch(app, alice, repo, {
198 branch: "greeting",
199 message: "More greeting",
200 files: [{ path: "GREETING.md", content: "hi again\n" }],
201 });
202 if (!again.ok) throw new Error(JSON.stringify(again.error));
203 const second = again.value.commitOid;
204 await settled((r) => r.env === env && r.commitOid === second);
205 await pictured(env, second);
206 await until(() =>
207 looksForEnv(app.db, record.id, env).every((l) => l.commitOid === second)
208 ? true
209 : undefined,
210 );
211 return { pull, env, first, second };
212 });
213
214 /** A picture a test owns: its file under the data directory, and its row. */
215 const seedLook = (
216 appId: string,
217 env: string,
218 commitOid: string,
219 kind: LookKind,
220 takenAs: "owner" | "nobody" = "owner",
221 png: Uint8Array = PNG,
222 ): Look => {
223 const path = `looks/${appId}/${env}/${commitOid}-${kind}.png`;
224 mkdirSync(dirname(join(dataDir, path)), { recursive: true });
225 writeFileSync(join(dataDir, path), png);
226 return recordLook(app.db, { appId, env, commitOid, kind, path, takenAs });
227 };
228
229 /**
230 * `body`, then production's pictures put back as they were: a test that
231 * drops, fails or rewrites one leaves nothing for the next to trip on.
232 */
233 const keepingProduction = async (body: () => Promise<void>) => {
234 await production();
235 const kept = looksForEnv(app.db, record.id, "production");
236 const files = kept
237 .filter((l) => l.path !== "")
238 .map((l) => [l.path, readFileSync(join(dataDir, l.path))] as const);
239 try {
240 await body();
241 } finally {
242 await looks.idle();
243 app.db
244 .query(`DELETE FROM look WHERE app_id = ?1 AND env = 'production'`)
245 .run(record.id);
246 for (const l of kept)
247 recordLook(app.db, {
248 appId: l.appId,
249 env: l.env,
250 commitOid: l.commitOid,
251 page: l.page,
252 kind: l.kind,
253 path: l.path,
254 error: l.error ?? undefined,
255 takenAs: l.takenAs,
256 });
257 for (const [path, bytes] of files) writeFileSync(join(dataDir, path), bytes);
258 }
259 };
260
140261 beforeAll(async () => {
141262 dataDir = await mkdtemp(join(tmpdir(), "forge-looks-"));
142263 app = createApp({ dataDir, port: 0 });
@@ -186,14 +307,11 @@ describe("the look", () => {
186307 await rm(dataDir, { recursive: true, force: true });
187308 });
188309
189 let pull: Pull;
190 let first = "";
191 let second = "";
192
193310 test("a green deploy is pictured at all three widths, once per head — phone and desktop as the owner, the thumb as a stranger, reduced from the desktop page; a newer head replaces", async () => {
194 const production = await settled((r) => r.env === "production");
195 expect(production.state).toBe("ok");
196 const rows = await pictured("production", production.commitOid);
311 const head = await production();
312 const rows = looksForEnv(app.db, record.id, "production").filter(
313 (l) => l.commitOid === head,
314 );
197315 expect(rows.map((l) => l.kind).sort()).toEqual([
198316 "desktop",
199317 "phone",
@@ -202,23 +320,31 @@ describe("the look", () => {
202320 for (const look of rows) {
203321 expect(look.error).toBeNull();
204322 expect(look.path).toBe(
205 `looks/${record.id}/production/${production.commitOid}-${look.kind}.png`,
323 `looks/${record.id}/production/${head}-${look.kind}.png`,
206324 );
207325 expect(existsSync(join(dataDir, look.path))).toBe(true);
208326 }
209327 // The browser was pointed at the grant door on the forge's own port,
210 // and the grant names the owner as an admin.
211 expect(calls).toHaveLength(3);
328 // and the grant names the owner as an admin. The first three takings
329 // of the head are the deploy's; a later sweep may retake a thumb.
330 const taken = callsOf("production", head).slice(0, 3);
331 expect(taken.map((c) => basename(c.out).split("-").at(-1)).sort()).toEqual(
332 ["desktop.png", "phone.png", "thumb.png"],
333 );
212334 // Taken to one side and moved in whole: nothing half-written lives
213335 // under the environment, and nothing is left behind on the side.
214 for (const call of calls)
336 for (const call of taken)
215337 expect(call.out).toContain(join("looks", ".taking"));
216 expect(readdirSync(join(dataDir, "looks", ".taking"))).toEqual([]);
217 const phone = calls.find((c) => c.width === 390)!;
338 expect(
339 readdirSync(join(dataDir, "looks", ".taking")).filter((name) =>
340 name.startsWith(record.id),
341 ),
342 ).toEqual([]);
343 const phone = taken.find((c) => c.width === 390)!;
218344 expect(phone.height).toBe(844);
219345 // Desktop and thumb are both taken in desktop's window: a browser does
220346 // not lay a page out at a tile's size.
221 const wide = calls.filter((c) => c.width === 1280);
347 const wide = taken.filter((c) => c.width === 1280);
222348 expect(wide.map((c) => c.height)).toEqual([800, 800]);
223349 const thumb = rows.find((l) => l.kind === "thumb")!;
224350 expect(pngSize(join(dataDir, thumb.path))).toEqual([640, 400]);
@@ -226,7 +352,7 @@ describe("the look", () => {
226352 expect(pngSize(join(dataDir, desktop.path))).toEqual([1280, 800]);
227353 // The thumb's grant names nobody: the tile a stranger is shown is the
228354 // page as a stranger sees it.
229 const thumbCall = calls.find((c) => c.out.endsWith("-thumb.png"))!;
355 const thumbCall = taken.find((c) => c.out.endsWith("-thumb.png"))!;
230356 const thumbGrant = readGrant(
231357 dataDir,
232358 new URL(thumbCall.url).searchParams.get("t") ?? "",
@@ -244,66 +370,32 @@ describe("the look", () => {
244370 });
245371 expect(grant?.who).toEqual({ id: alice.id, name: "alice", role: "admin" });
246372
247 // A pull's preview, the same way.
248 const committed = await commitToBranch(app, alice, repo, {
249 branch: "greeting",
250 base: repo.defaultBranch,
251 message: "Say hello",
252 files: [{ path: "GREETING.md", content: "hi\n" }],
253 });
254 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
255 first = committed.value.commitOid;
256 const opened = await openPull(app, alice, repo, {
257 title: "Say hello",
258 baseBranch: repo.defaultBranch,
259 headBranch: "greeting",
260 });
261 if (!opened.ok) throw new Error(String(opened.error));
262 pull = opened.value;
263 const env = previewEnv(pull.number);
264 expect((await settled((r) => r.env === env)).state).toBe("ok");
265 expect(await pictured(env, first)).toHaveLength(3);
266 expect(calls).toHaveLength(6);
267 expect(new URL(calls[3]!.url).hostname).toBe(
373 // A pull's preview, the same way: three pictures of each head, and the
374 // older head's pictures gone once the newer is pictured.
375 const { pull, env, first, second } = await greeting();
376 expect(callsOf(env, first)).toHaveLength(3);
377 expect(callsOf(env, second)).toHaveLength(3);
378 expect(new URL(callsOf(env, first)[0]!.url).hostname).toBe(
268379 `hello--${pull.number}.${DOMAIN}`,
269380 );
381 expect(looksForEnv(app.db, record.id, env)).toHaveLength(3);
382 expect(
383 existsSync(join(dataDir, "looks", record.id, env, `${first}-phone.png`)),
384 ).toBe(false);
270385
271386 // The same head green again is not pictured again.
272 runtime.requestDeploy(record, repo, env, first, "redeploy");
387 runtime.requestDeploy(record, repo, env, second, "redeploy");
273388 expect(
274389 (await settled((r) => r.env === env && r.reason === "redeploy")).state,
275390 ).toBe("ok");
276391 await looks.idle();
277 expect(calls).toHaveLength(6);
392 expect(callsOf(env, second)).toHaveLength(3);
278393 expect(looksForEnv(app.db, record.id, env)).toHaveLength(3);
279
280 // A newer head is pictured, and the older head's pictures go.
281 const again = await commitToBranch(app, alice, repo, {
282 branch: "greeting",
283 message: "More greeting",
284 files: [{ path: "GREETING.md", content: "hi again\n" }],
285 });
286 if (!again.ok) throw new Error(JSON.stringify(again.error));
287 second = again.value.commitOid;
288 expect(
289 (await settled((r) => r.env === env && r.commitOid === second)).state,
290 ).toBe("ok");
291 expect(await pictured(env, second)).toHaveLength(3);
292 expect(calls).toHaveLength(9);
293 await until(() =>
294 looksForEnv(app.db, record.id, env).every((l) => l.commitOid === second)
295 ? true
296 : undefined,
297 );
298 expect(existsSync(join(dataDir, rows[0]!.path))).toBe(true);
299 expect(
300 existsSync(join(dataDir, "looks", record.id, env, `${first}-phone.png`)),
301 ).toBe(false);
302394 }, 120_000);
303395
304396 test("the pull page shows both pictures; the route serves them cached, and refuses a stranger", async () => {
397 const { pull, env, first, second } = await greeting();
305398 const base = `/alice/hello`;
306 const env = `pull-${pull.number}`;
307399 const page = await (
308400 await web(`${base}/pulls/${pull.number}`, aliceCookie)
309401 ).text();
@@ -341,87 +433,94 @@ describe("the look", () => {
341433 (await web(`${base}/looks/pull-99/${second}/phone.png`, aliceCookie))
342434 .status,
343435 ).toBe(404);
344 });
436 }, 120_000);
345437
346 let unpictured: Pull;
347
348 test("a picture that could not be taken is recorded with its reason, and the page says so", async () => {
349 mode = "fail";
350 const env = `pull-${pull.number}`;
351 const moved = await commitToBranch(app, alice, repo, {
352 branch: "greeting",
353 message: "Once more",
354 files: [{ path: "GREETING.md", content: "hi once more\n" }],
355 });
356 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
357 const third = moved.value.commitOid;
358 expect(
359 (await settled((r) => r.env === env && r.commitOid === third)).state,
360 ).toBe("ok");
361 const rows = await pictured(env, third);
362 for (const look of rows) {
363 expect(look.error).toBe("the browser fell over");
364 expect(look.path).toBe("");
365 }
366 // The last good pictures stay, and the page says the head has moved
367 // and why there is no picture of it.
368 const page = await (
369 await web(`/alice/hello/pulls/${pull.number}`, aliceCookie)
370 ).text();
371 expect(page).toContain(`/looks/${env}/${second}/phone.png`);
372 expect(page.replace(/\s+/g, " ")).toContain("the head has moved since");
373 expect(page).toContain("the browser fell over");
374 expect(
375 (await web(`/alice/hello/looks/${env}/${third}/phone.png`, aliceCookie))
376 .status,
377 ).toBe(404);
378
379 // A pull that never had a picture says so, without one.
438 /** A branch off the default with one file, opened as a pull and settled. */
439 const pullOf = async (branchName: string, file: string) => {
380440 const branch = await commitToBranch(app, alice, repo, {
381 branch: "second",
441 branch: branchName,
382442 base: repo.defaultBranch,
383 message: "Second",
384 files: [{ path: "SECOND.md", content: "2\n" }],
443 message: branchName,
444 files: [{ path: file, content: `${branchName}\n` }],
385445 });
386446 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
387447 const opened = await openPull(app, alice, repo, {
388 title: "Second",
448 title: branchName,
389449 baseBranch: repo.defaultBranch,
390 headBranch: "second",
450 headBranch: branchName,
391451 });
392452 if (!opened.ok) throw new Error(String(opened.error));
393 unpictured = opened.value;
394 const env2 = `pull-${unpictured.number}`;
395 expect((await settled((r) => r.env === env2)).state).toBe("ok");
396 await pictured(env2, branch.value.commitOid);
397 const none = await (
398 await web(`/alice/hello/pulls/${unpictured.number}`, aliceCookie)
399 ).text();
400 expect(none).toContain("<h2>Look</h2>");
401 expect(none).toContain("No picture of");
402 expect(none).toContain("the browser fell over");
403 expect(none).not.toContain(`/looks/${env2}/`);
404 mode = "ok";
453 const env = previewEnv(opened.value.number);
454 const commitOid = branch.value.commitOid;
455 expect(
456 (await settled((r) => r.env === env && r.commitOid === commitOid)).state,
457 ).toBe("ok");
458 return { pull: opened.value, env, commitOid };
459 };
460
461 test("a picture that could not be taken is recorded with its reason, and the page says so", async () => {
462 const { pull, env, commitOid: good } = await pullOf("faltering", "FALTER.md");
463 expect((await pictured(env, good)).every((l) => l.error === null)).toBe(
464 true,
465 );
466 mode = "fail";
467 try {
468 const moved = await commitToBranch(app, alice, repo, {
469 branch: "faltering",
470 message: "Once more",
471 files: [{ path: "FALTER.md", content: "once more\n" }],
472 });
473 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
474 const third = moved.value.commitOid;
475 expect(
476 (await settled((r) => r.env === env && r.commitOid === third)).state,
477 ).toBe("ok");
478 const rows = await pictured(env, third);
479 for (const look of rows) {
480 expect(look.error).toBe("the browser fell over");
481 expect(look.path).toBe("");
482 }
483 // The last good pictures stay, and the page says the head has moved
484 // and why there is no picture of it.
485 const page = await (
486 await web(`/alice/hello/pulls/${pull.number}`, aliceCookie)
487 ).text();
488 expect(page).toContain(`/looks/${env}/${good}/phone.png`);
489 expect(page.replace(/\s+/g, " ")).toContain("the head has moved since");
490 expect(page).toContain("the browser fell over");
491 expect(
492 (await web(`/alice/hello/looks/${env}/${third}/phone.png`, aliceCookie))
493 .status,
494 ).toBe(404);
495
496 // A pull that never had a picture says so, without one.
497 const never = await pullOf("unpictured", "NEVER.md");
498 await pictured(never.env, never.commitOid);
499 const none = await (
500 await web(`/alice/hello/pulls/${never.pull.number}`, aliceCookie)
501 ).text();
502 expect(none).toContain("<h2>Look</h2>");
503 expect(none).toContain("No picture of");
504 expect(none).toContain("the browser fell over");
505 expect(none).not.toContain(`/looks/${never.env}/`);
506 } finally {
507 mode = "ok";
508 }
405509 }, 120_000);
406510
407511 test("a closed pull's pictures go with its preview", async () => {
408 const env = `pull-${unpictured.number}`;
512 const { pull, env, commitOid } = await pullOf("closing", "CLOSING.md");
513 await pictured(env, commitOid);
409514 expect(looksForEnv(app.db, record.id, env).length).toBeGreaterThan(0);
410 const closed = await setIssueStateThrough(
411 app,
412 alice,
413 repo,
414 unpictured,
415 "closed",
416 );
515 const closed = await setIssueStateThrough(app, alice, repo, pull, "closed");
417516 expect(closed.ok).toBe(true);
418517 expect(looksForEnv(app.db, record.id, env)).toHaveLength(0);
419518 expect(existsSync(join(dataDir, "looks", record.id, env))).toBe(false);
420519 const page = await (
421 await web(`/alice/hello/pulls/${unpictured.number}`, aliceCookie)
520 await web(`/alice/hello/pulls/${pull.number}`, aliceCookie)
422521 ).text();
423522 expect(page).not.toContain("<h2>Look</h2>");
424 });
523 }, 120_000);
425524
426525 test("a look is taken from `app.serving`, while the deploy's tests are still running, and a red check afterward does not remove it", async () => {
427526 // The app's test blocks on this file until the look has been taken.
@@ -490,6 +589,7 @@ describe("the look", () => {
490589 }, 30_000);
491590
492591 test("two events for one environment, back to back, leave one queued look — at the newer commit", async () => {
592 await production();
493593 const before = calls.length;
494594 const live = runtime.envStatus(record, "production");
495595 if (live === undefined) throw new Error("production is not live");
@@ -518,8 +618,7 @@ describe("the look", () => {
518618 });
519619 await looks.idle();
520620 // The superseded commit was never even looked at: production's own
521 // head was already pictured (from the first test), so nothing new
522 // was captured for it either.
621 // head was already pictured, so nothing new was captured for it either.
523622 expect(calls.length).toBe(before);
524623 expect(
525624 looksForEnv(app.db, record.id, "production").some(
@@ -528,7 +627,13 @@ describe("the look", () => {
528627 ).toBe(false);
529628 });
530629
531 test("the app's head shows production as a thumb", async () => {
630 test("the app's head shows production as a thumb", () =>
631 keepingProduction(async () => {
632 const head = await production();
633 // Its own pictures of production's head, not the deploy's.
634 for (const kind of ["phone", "desktop"] as const)
635 seedLook(record.id, "production", head, kind);
636 seedLook(record.id, "production", head, "thumb", "nobody");
532637 const scout = await createAgent(app, alice, { username: "scout" });
533638 if (!scout.ok) throw new Error(String(scout.error));
534639 expect(addToCrew(app, alice, repo, "scout").ok).toBe(true);
@@ -553,12 +658,9 @@ describe("the look", () => {
553658
554659 const studio = `${aliceCookie}; forge_mode=studio`;
555660 const page = await (await web("/alice/hello", studio)).text();
556 const production = looksForEnv(app.db, record.id, "production").find(
557 (l) => l.kind === "thumb",
558 )!;
559661 expect(page).toContain(`class="look-now"`);
560662 expect(page).toContain(
561 `src="/alice/hello/looks/production/${production.commitOid}/thumb.png?v=`,
663 `src="/alice/hello/looks/production/${head}/thumb.png?v=`,
562664 );
563665
564666 // A commit pictured before the thumb kind existed has only its phone
@@ -576,13 +678,10 @@ describe("the look", () => {
576678 )
577679 .run(record.id);
578680 const fallback = await (await web("/alice/hello", studio)).text();
579 const productionDesktop = looksForEnv(app.db, record.id, "production").find(
580 (l) => l.kind === "desktop",
581 )!;
582681 expect(fallback).toContain(
583 `src="/alice/hello/looks/production/${productionDesktop.commitOid}/desktop.png?v=`,
682 `src="/alice/hello/looks/production/${head}/desktop.png?v=`,
584683 );
585 }, 120_000);
684 }), 120_000);
586685
587686 test("app.looks naming two pages pictures both, distinctly, and the pull page groups them", async () => {
588687 const branch = await commitToBranch(app, alice, repo, {
@@ -661,12 +760,18 @@ describe("the look", () => {
661760 expect(page).toContain(`alt="hello #${opened.value.number} on a phone"`);
662761 }, 120_000);
663762
664 test("the sweep pictures a running production missing one: a thumb from before thumbs were the page is retaken as a stranger; one that failed is not retried each sweep", async () => {
763 test("the sweep pictures a running production missing one: a thumb from before thumbs were the page is retaken as a stranger; one that failed is not retried each sweep", () =>
764 keepingProduction(async () => {
765 const head = await production();
665766 const status = runtime.envStatus(record, "production")!;
666767 expect(status.state).toBe("running");
667 const head = status.commitOid;
668 // Whatever production lacks at its head now (an earlier test dropped
669 // its thumb), the sweep takes.
768 expect(status.commitOid).toBe(head);
769 // Production lacks its thumb at its head: the sweep takes it.
770 app.db
771 .query(
772 `DELETE FROM look WHERE app_id = ?1 AND env = 'production' AND kind = 'thumb'`,
773 )
774 .run(record.id);
670775 looks.sweep();
671776 await looks.idle();
672777 const thumbAtHead = (): Look | undefined =>
@@ -714,16 +819,20 @@ describe("the look", () => {
714819 looks.sweep();
715820 await looks.idle();
716821 expect(calls).toHaveLength(before + 1);
717 }, 60_000);
822 }), 60_000);
718823
719824 test("pictures are shown only to those allowed to see them (#727): on a public repository hosting a private app, a stranger gets none, a signed-in reader the thumb, a writer all", async () => {
720825 // `hello` is a private app; its repository is made public here.
721826 expect(record.access).toBe("private");
827 await keepingProduction(async () => {
828 const head = await production();
722829 app.db.query(`UPDATE repo SET visibility = 'public' WHERE id = ?1`).run(repo.id);
723830 try {
724 const head = runtime.envStatus(record, "production")!.commitOid;
725 // The test before left this head's thumb failed; picture it again.
726 const thumbPath = `looks/${record.id}/production/${head}-thumb.png`;
831 // Its own pictures of the head: phone and desktop as the owner, and
832 // a thumb from before thumbs were taken as nobody.
833 seedLook(record.id, "production", head, "phone");
834 seedLook(record.id, "production", head, "desktop");
835 const thumbPath = seedLook(record.id, "production", head, "thumb").path;
727836 const retake = () =>
728837 recordLook(app.db, {
729838 appId: record.id,
@@ -732,8 +841,6 @@ describe("the look", () => {
732841 kind: "thumb",
733842 path: thumbPath,
734843 });
735 writeFileSync(join(dataDir, thumbPath), PNG);
736 retake();
737844 const at = (kind: string) => `/alice/hello/looks/production/${head}/${kind}.png`;
738845 const status = async (kind: string, cookie: string) =>
739846 (await web(at(kind), cookie)).status;
@@ -806,8 +913,10 @@ describe("the look", () => {
806913 } finally {
807914 app.db.query(`UPDATE app SET access = 'private' WHERE id = ?1`).run(record.id);
808915 app.db.query(`UPDATE repo SET visibility = 'private' WHERE id = ?1`).run(repo.id);
916 setAppMembers(app.db, record.id, [], alice.id);
809917 }
810 });
918 });
919 }, 60_000);
811920
812921 test("a public app's previews are taken as nobody, so a reader of its pull sees the Look card; a picture taken as the owner stays the writers' (#738)", async () => {
813922 const made = await newApp(app, alice, { name: "gallery", visibility: "public" });
@@ -871,31 +980,48 @@ describe("the look", () => {
871980 }, 120_000);
872981
873982 test("a public app made private after its pictures were taken: a reader gets them no more, and no Look card; its writer still does (#845)", async () => {
874 const gallery = getRepo(app.db, "alice", "gallery")!;
875 const galleryApp = getAppByRepo(app.db, gallery.id)!;
876 const look = looksForEnv(app.db, galleryApp.id, "production").find(
877 (l) => l.kind === "phone" && l.error === null,
878 )!;
983 // Its own public app and pull; the pictures are rows it writes itself.
984 const made = await newApp(app, alice, { name: "keepsake", visibility: "public" });
985 if (!made.ok) throw new Error(String(made.error));
986 const keepsake = made.value.repo;
987 const keepsakeApp = made.value.app;
988 const branch = await commitToBranch(app, alice, keepsake, {
989 branch: "frame",
990 base: keepsake.defaultBranch,
991 message: "A frame",
992 files: [{ path: "FRAME.md", content: "frame\n" }],
993 });
994 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
995 const opened = await openPull(app, alice, keepsake, {
996 title: "A frame",
997 baseBranch: keepsake.defaultBranch,
998 headBranch: "frame",
999 });
1000 if (!opened.ok) throw new Error(String(opened.error));
1001 const pull = opened.value;
1002 const env = previewEnv(pull.number);
1003 const commit = branch.value.commitOid;
1004 // Whatever the service takes of this preview is in before the fixture
1005 // is written over it, so the rows below are the ones read.
1006 await settled((r) => r.env === env, keepsake.id);
1007 await pictured(env, commit, keepsakeApp.id);
1008 await looks.idle();
8791009 // Taken as nobody while the app was public.
880 app.db.query(`UPDATE look SET taken_as = 'nobody' WHERE app_id = ?1`).run(galleryApp.id);
881 const at = `/alice/gallery/looks/production/${look.commitOid}/phone.png`;
1010 seedLook(keepsakeApp.id, env, commit, "phone", "nobody");
1011 seedLook(keepsakeApp.id, env, commit, "desktop", "nobody");
1012 const at = `/alice/keepsake/looks/${env}/${commit}/phone.png`;
8821013 expect((await web(at, bobCookie)).status).toBe(200);
883 const pull = listPulls(app.db, gallery.id, { state: "open" })[0]!;
8841014 const card = async (cookie: string) =>
885 (await (await web(`/alice/gallery/pulls/${pull.number}`, cookie)).text()).includes("<h2>Look</h2>");
1015 (await (await web(`/alice/keepsake/pulls/${pull.number}`, cookie)).text()).includes("<h2>Look</h2>");
8861016 expect(await card(bobCookie)).toBe(true);
8871017 // Made private: the same files, asked again on every fetch.
888 app.db.query(`UPDATE app SET access = 'private' WHERE id = ?1`).run(galleryApp.id);
889 try {
890 expect((await web(at, bobCookie)).status).toBe(404);
891 expect((await web(at, "")).status).toBe(404);
892 expect(await card(bobCookie)).toBe(false);
893 expect((await web(at, aliceCookie)).status).toBe(200);
894 expect(await card(aliceCookie)).toBe(true);
895 } finally {
896 app.db.query(`UPDATE app SET access = 'public' WHERE id = ?1`).run(galleryApp.id);
897 }
898 });
1018 app.db.query(`UPDATE app SET access = 'private' WHERE id = ?1`).run(keepsakeApp.id);
1019 expect((await web(at, bobCookie)).status).toBe(404);
1020 expect((await web(at, "")).status).toBe(404);
1021 expect(await card(bobCookie)).toBe(false);
1022 expect((await web(at, aliceCookie)).status).toBe(200);
1023 expect(await card(aliceCookie)).toBe(true);
1024 }, 120_000);
8991025
9001026 test("memory pressure is what the container truly holds, never its page cache", async () => {
9011027 const { cgroupMemoryPressure, memoryPressure } =

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs