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

Tests depend on their order within a file: 66 tests in 24 of 80 sampled files fail under --randomize #17505

opened this in answer to

Merged 18h 19m ago, live in production

scout/forge:scout/17500-tests-depend-on-their-order-within-a-fil → main 0 commits fork

  • Merged. scout/17500-tests-depend-on-their-order-within-a-fil was merged into main as d8024b8.

Review

Sign in to review this change.
24 files changed +285 −114
test/app-empty-crew.test.ts +3 −3
@@ -4,7 +4,7 @@
44 * MCP tool answers the same line and has the same action (#15831).
55 */
66
7 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { afterEach, beforeEach, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
@@ -32,7 +32,7 @@ let owner = "";
3232 let reader = "";
3333 const KEY = process.env["ANTHROPIC_API_KEY"];
3434
35 beforeAll(async () => {
35 beforeEach(async () => {
3636 process.env["ANTHROPIC_API_KEY"] = "test-key";
3737 dir = await mkdtemp(join(tmpdir(), "forge-empty-crew-"));
3838 app = createApp({ dataDir: dir, port: 0 });
@@ -54,7 +54,7 @@ beforeAll(async () => {
5454 owner = await signInCookie(servers.url, "alice");
5555 reader = await signInCookie(servers.url, "bob");
5656 });
57 afterAll(async () => {
57 afterEach(async () => {
5858 servers.stop?.();
5959 if (KEY === undefined) delete process.env["ANTHROPIC_API_KEY"];
6060 else process.env["ANTHROPIC_API_KEY"] = KEY;
test/app-home-batched.test.ts +25 −14
@@ -1,5 +1,5 @@
11 /** An app home's `now` and `following` read in batches: 200 issues, 40 pulls, 5 runs (#6184); no statement grows with the rows (#6819). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
2 import { afterEach, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync, rmSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
@@ -9,6 +9,7 @@ import { createApp, type App } from "../src/app.ts";
99 import { forkRelation } from "../src/core/following.ts";
1010 import { deferredOf, repoGraph } from "../src/core/dependencies.ts";
1111 import { getRepo } from "../src/core/repos.ts";
12 import { setMember } from "../src/core/roles.ts";
1213 import { createUser } from "../src/core/users.ts";
1314 import { serve, type Servers } from "../src/http/server.ts";
1415 import { proveAll } from "./helpers/verified.ts";
@@ -92,18 +93,19 @@ async function queriesFor(path: string): Promise<number> {
9293 }
9394 /**
9495 * Background work (timers, following, run loops) can prepare statements on the same db
95 * while a page is read, and only ever adds to the count; the fewest of several reads is the page's own cost.
96 * while a page is read, and only ever adds to the count; the fewest of three reads is the page's
97 * own cost.
9698 */
9799 async function costOf(path: string): Promise<number> {
98100 let least = Infinity;
99 for (let i = 0; i < 7; i++) {
101 for (let i = 0; i < 3; i++) {
100102 await quiet(app.db); // start from rest, not in the tail of the last request's work
101103 least = Math.min(least, await queriesFor(path));
102104 }
103105 return least;
104106 }
105107
106 beforeAll(async () => {
108 beforeEach(async () => {
107109 root = mkdtempSync(join(tmpdir(), "forge-home-batched-"));
108110 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
109111 const u = await createUser(app.db, {
@@ -116,7 +118,7 @@ beforeAll(async () => {
116118 });
117119 if (!u.ok) throw new Error(u.error);
118120 proveAll(app);
119 const made = await createRepo(app, { id: u.value.id, username: "alice" } as never, { name: "vault" });
121 const made = await createRepo(app, u.value, { name: "vault" });
120122 if (!made.ok) throw new Error(String(made.error));
121123 const seeded = await commitToBranch(app, u.value, made.value, {
122124 message: "Start",
@@ -142,7 +144,7 @@ beforeAll(async () => {
142144 let diverged = false;
143145 for (let i = 0; i < 1000 && !diverged; i++) {
144146 diverged = (await forkRelation(app, forked.value))?.state === "diverged";
145 if (!diverged) await new Promise((r) => setTimeout(r, 30));
147 if (!diverged) await new Promise((r) => setTimeout(r, 5)); // real-timer: git follows the parent in the background; poll for its verdict
146148 }
147149 if (!diverged) throw new Error("the fork never read diverged");
148150 const db = app.db;
@@ -159,7 +161,9 @@ beforeAll(async () => {
159161 password: "a-good-passphrase",
160162 });
161163 if (!bob.ok) throw new Error(bob.error);
162 const elsewhere = await createRepo(app, { id: bob.value.id, username: "bob" } as never, { name: "elsewhere" });
164 proveAll(app);
165 setMember(app.db, bob.value.id, true, u.value.id, new Date());
166 const elsewhere = await createRepo(app, bob.value, { name: "elsewhere" });
163167 if (!elsewhere.ok) throw new Error(String(elsewhere.error));
164168 const seedElsewhere = (from: number, to: number) =>
165169 db.transaction(() => {
@@ -213,7 +217,7 @@ beforeAll(async () => {
213217 seedElsewhere(2, 30);
214218 manyStatements = await statementsByText(PAGES[0]!);
215219 });
216 afterAll(() => {
220 afterEach(() => {
217221 servers.stop();
218222 app.close();
219223 rmSync(root, { recursive: true, force: true });
@@ -237,17 +241,21 @@ test("following stays cheap on a diverged fork (regression guard; this pull does
237241 expect(Math.abs((await costOf(path)) - small[path]!)).toBeLessThanOrEqual(SLACK);
238242 });
239243
240 test("now costs the same statements on the live shape: 300 open issues, 2,000 closed, 3,500 edges, 20 pillars", async () => {
241 const repo = getRepo(app.db, "alice", "vault")!;
242 const author = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
244 /** Open issues past the seeded ones, then the live shape: closed issues, edges and pillars. */
245 const growToLive = (repoId: string, author: string) =>
243246 app.db.transaction(() => {
244247 for (let i = 200; i < 280; i++)
245248 app.db.query(
246249 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state)
247250 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, 'open')`,
248 ).run(`${repo.id}i${i}`, repo.id, 5000 + i, `Tell ${i}`, author);
249 seedLive(app.db, repo.id, author, 0);
251 ).run(`${repoId}i${i}`, repoId, 5000 + i, `Tell ${i}`, author);
252 seedLive(app.db, repoId, author, 0);
250253 })();
254
255 test("now costs the same statements on the live shape: 300 open issues, 2,000 closed, 3,500 edges, 20 pillars", async () => {
256 const repo = getRepo(app.db, "alice", "vault")!;
257 const author = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
258 growToLive(repo.id, author);
251259 // Counted, not timed: 2,000 closed issues and 3,500 edges cost four statements more than the small page
252260 // (measured), not one per row; a per-row read would add thousands.
253261 expect(Math.abs((await costOf("/alice/vault")) - small["/alice/vault"]!)).toBeLessThanOrEqual(4);
@@ -255,6 +263,9 @@ test("now costs the same statements on the live shape: 300 open issues, 2,000 cl
255263
256264 test("the lean deferred read says what the whole graph says, and something is deferred", () => {
257265 const repo = getRepo(app.db, "alice", "vault")!;
266 // The live shape is what defers anything: a few issues alone defer nothing.
267 const author = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
268 growToLive(repo.id, author);
258269 const whole = repoGraph(app.db, repo.id).deferred;
259270 expect(whole.size).toBeGreaterThan(0);
260271 expect([...deferredOf(app.db, repo)].sort()).toEqual([...whole].sort());
@@ -265,7 +276,7 @@ async function statementsByText(path: string): Promise<Map<string, number>> {
265276 const door = app.db as unknown as { query: (sql: string) => unknown };
266277 const original = app.db.query.bind(app.db);
267278 let best: Map<string, number> | undefined;
268 for (let run = 0; run < 5; run++) {
279 for (let run = 0; run < 3; run++) {
269280 await quiet(app.db);
270281 const seen = new Map<string, number>();
271282 door.query = (sql: string) => {
test/app-secrets-org-grant.test.ts +3 −3
@@ -4,7 +4,7 @@
44 * grant names, a move to another organization ends the grant, and a grant of
55 * one organization's secret to another's repository is refused.
66 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { afterEach, beforeEach, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
@@ -38,7 +38,7 @@ const started = (r: Repo): Record<string, string> =>
3838 needs: ["STRIPE_KEY"],
3939 });
4040
41 beforeAll(async () => {
41 beforeEach(async () => {
4242 dataDir = await mkdtemp(join(tmpdir(), "forge-org-grant-"));
4343 app = createApp({ dataDir, port: 0 });
4444 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
@@ -58,7 +58,7 @@ beforeAll(async () => {
5858 expect(putSecret(app, alice, "org", "orga", "STRIPE_KEY", "key-of-a").ok).toBe(true);
5959 expect(putSecret(app, alice, "org", "orgb", "STRIPE_KEY", "key-of-b").ok).toBe(true);
6060 });
61 afterAll(async () => {
61 afterEach(async () => {
6262 app.close();
6363 await rm(dataDir, { recursive: true, force: true });
6464 });
test/branches-action.test.ts +12 −4
@@ -1,5 +1,5 @@
11 /** createBranch / deleteBranch: a mirror's ref moves only after its origin took the push; a native repo's moves at once; a reader is refused. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
33 import { chmod, mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
@@ -41,7 +41,7 @@ const tip = (repo: Repo, branch: string) =>
4141 resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${branch}`);
4242 const originTip = (branch: string) => resolveOid(originDir, `refs/heads/${branch}`);
4343
44 beforeAll(async () => {
44 beforeEach(async () => {
4545 dataDir = await mkdtemp(join(tmpdir(), "forge-branches-action-"));
4646 app = createApp({ dataDir, port: 0 });
4747 app.bus.subscribe((e) => events.push(e));
@@ -91,7 +91,7 @@ beforeAll(async () => {
9191 mirror = getRepo(app.db, "ada", "gears")!;
9292 }, 30_000);
9393
94 afterAll(async () => {
94 afterEach(async () => {
9595 server?.stop(true);
9696 app?.close();
9797 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
@@ -132,6 +132,12 @@ describe("a reader", () => {
132132 });
133133
134134 describe("a mirrored repository", () => {
135 /** `feat` exists on the origin and on the mirror, as an accepted create leaves it. */
136 const withFeat = async () => {
137 reject = "";
138 must(await createBranch(app, ada, mirror, { name: "feat" }));
139 };
140
135141 test("a refusing origin leaves the local ref where it was, and the refusal is a refusal, not a failure", async () => {
136142 reject = "branch creation is closed here";
137143 const before = events.length;
@@ -151,6 +157,7 @@ describe("a mirrored repository", () => {
151157 });
152158
153159 test("a branch that exists locally is not created again", async () => {
160 await withFeat();
154161 expect(await createBranch(app, ada, mirror, { name: "feat" })).toEqual({ ok: false, error: "exists" });
155162 });
156163
@@ -169,6 +176,7 @@ describe("a mirrored repository", () => {
169176 });
170177
171178 test("a refusing origin keeps the local branch on delete", async () => {
179 await withFeat();
172180 reject = "deletes need review";
173181 const before = await tip(mirror, "feat");
174182 const r = await deleteBranch(app, ada, mirror, "feat");
@@ -178,7 +186,7 @@ describe("a mirrored repository", () => {
178186 });
179187
180188 test("an accepting origin drops the ref, then the local one goes and it is announced", async () => {
181 reject = "";
189 await withFeat();
182190 must(await deleteBranch(app, ada, mirror, "feat"));
183191 expect(await originTip("feat")).toBeUndefined();
184192 expect(await tip(mirror, "feat")).toBeUndefined();
test/build-pins.test.ts +29 −2
@@ -2,7 +2,7 @@
22 * Build pins: a writer marks a commit under refs/builds/<label>; the
33 * builds page lists them.
44 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
66 import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
@@ -17,6 +17,12 @@ import { repoDir } from "../src/git/repos.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
1818 import { nextLabel } from "../src/web/pages/builds.ts";
1919
20 /** Remove every pin of a repository: the refs under refs/builds, and the notes kept for them. */
21 const clearPins = async (dir: string) => {
22 await Bun.$`git -C ${dir} update-ref -d refs/forge/notes`.quiet().nothrow();
23 for (const pin of await listBuildPins(dir)) await Bun.$`git -C ${dir} update-ref -d refs/builds/${pin.label}`.quiet();
24 };
25
2026 describe("build pins", () => {
2127 let dataDir: string;
2228 let app: App;
@@ -92,6 +98,13 @@ describe("build pins", () => {
9298 await rm(dataDir, { recursive: true, force: true });
9399 });
94100
101 // Every test starts with no pins and pins what it needs itself.
102 beforeEach(() => clearPins(repoDir(app.reposRoot, "alice", "game")));
103 const pinV1 = async () => {
104 const made = await pinBuild(app, alice, fresh(), { label: "v1", oid: oids.one! });
105 if (!made.ok) throw new Error(String(made.error));
106 };
107
95108 test("a writer pins a commit from the form; it is a ref with its note and source", async () => {
96109 const res = await post("/alice/game/builds", aliceCookie, {
97110 sha: oids.one!,
@@ -101,7 +114,7 @@ describe("build pins", () => {
101114 });
102115 expect(res.status).toBe(303);
103116 expect(res.headers.get("location")).toBe("/alice/game/iterations?build=alice%2Fgame%3Av1");
104 const [pin] = await pins();
117 const pin = (await pins()).find((p) => p.label === "v1");
105118 expect(pin?.label).toBe("v1");
106119 expect(pin?.oid).toBe(oids.one!);
107120 expect(pin?.note).toBe("first playable");
@@ -123,6 +136,7 @@ describe("build pins", () => {
123136 });
124137
125138 test("bad labels, unknown commits and taken labels are refused", async () => {
139 await pinV1();
126140 for (const label of ["-x", "a/b", "a b", "x".repeat(41), "refs..x"])
127141 expect(
128142 (await pinBuild(app, alice, fresh(), { label, oid: oids.two! })).ok,
@@ -136,6 +150,7 @@ describe("build pins", () => {
136150 });
137151
138152 test("the API lists the pins to a reader and refuses a write without a token", async () => {
153 await pinV1();
139154 const listed = ((await (await fetch(`${base}/api/v1/repos/alice/game/builds`)).json()) as {
140155 items: { label: string }[];
141156 }).items;
@@ -191,6 +206,13 @@ describe("build pins pages and notes", () => {
191206 await rm(dataDir, { recursive: true, force: true });
192207 });
193208
209 const gameDir = () => repoDir(app.reposRoot, "alice", "game");
210 beforeEach(() => clearPins(gameDir()));
211 const pinV1 = async () => {
212 const made = await pinBuild(app, alice, getRepo(app.db, "alice", "game")!, { label: "v1", oid });
213 if (!made.ok) throw new Error(String(made.error));
214 };
215
194216 test("the form is offered to a writer, the list shows the pin, the branches page links both", async () => {
195217 const form = await (await fetch(`${servers.url}/alice/game/builds/new?sha=${oid}`, { headers: { cookie } })).text();
196218 expect(form).toContain('name="label"');
@@ -207,6 +229,7 @@ describe("build pins pages and notes", () => {
207229 });
208230
209231 test("a taken label is flashed back, not pinned twice", async () => {
232 await pinV1();
210233 const again = await post("/alice/game/builds", { sha: oid, label: "v1" });
211234 expect(again.status).toBe(303);
212235 expect(again.headers.get("location")).toContain("/builds/new");
@@ -214,6 +237,7 @@ describe("build pins pages and notes", () => {
214237 });
215238
216239 test("a note is appended through the API, and copied once into the intent doc", async () => {
240 await pinV1();
217241 const intent = join(dataDir, "intent.md");
218242 await Bun.write(intent, "# Intent\n");
219243 const noted = await notePin(
@@ -232,6 +256,7 @@ describe("build pins pages and notes", () => {
232256 });
233257
234258 test("an agent cannot pin or note, even holding write access", async () => {
259 await pinV1();
235260 const repo = getRepo(app.db, "alice", "game")!;
236261 const pins = () => listBuildPins(repoDir(app.reposRoot, "alice", "game"));
237262 const agent = { ...alice, kind: "agent" } as User;
@@ -242,6 +267,7 @@ describe("build pins pages and notes", () => {
242267 });
243268
244269 test("a note cannot open a comment or a heading in the intent doc", async () => {
270 await pinV1();
245271 const intent = join(dataDir, "intent-inject.md");
246272 await Bun.write(intent, "# Intent\n");
247273 const repo = getRepo(app.db, "alice", "game")!;
@@ -258,6 +284,7 @@ describe("build pins pages and notes", () => {
258284 });
259285
260286 test("deleting a pin removes the ref and the list forgets it; a stranger's form is refused", async () => {
287 await pinV1();
261288 expect((await post("/alice/game/builds/v1/delete", {}, "https://evil.test")).status).toBe(403);
262289 expect((await listBuildPins(repoDir(app.reposRoot, "alice", "game"))).length).toBe(1);
263290 expect((await post("/alice/game/builds/v1/delete", {})).status).toBe(303);
test/code-scanning.test.ts +41 −21
@@ -5,7 +5,7 @@
55 * with a reason. The fake secrets are built at run time, so this file is
66 * not itself a finding.
77 */
8 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
8 import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test";
99 import { mkdtemp, rm, writeFile } from "node:fs/promises";
1010 import { tmpdir } from "node:os";
1111 import { join } from "node:path";
@@ -84,7 +84,7 @@ const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T =>
8484
8585 /** The forge's own copy of the repository's default branch tip: what a release would cut. */
8686 async function tipOf(branch = "main"): Promise<string> {
87 const dir = join(dataDir, "repos", "alice", "square.git");
87 const dir = join(dataDir, "repos", "alice", `${repo.name}.git`);
8888 return (await git(["rev-parse", branch], dir)).out.trim();
8989 }
9090
@@ -113,34 +113,53 @@ afterAll(async () => {
113113 await rm(work, { recursive: true, force: true });
114114 });
115115
116 // Every test gets its own repository, so none leans on a finding another pushed.
117 let made = 0;
118 beforeEach(async () => {
119 repo = ok(await createRepo(app, alice, { name: `square${made++}`, visibility: "public" }));
120 ok(await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# square\n" }] }));
121 });
122
123 const cloneRepo = async (): Promise<string> => {
124 const url = `${servers.url.replace("http://", `http://alice:${token.alice}@`)}/alice/${repo.name}.git`;
125 const clone = join(work, repo.name);
126 expect((await git(["clone", "-q", url, clone], work)).code).toBe(0);
127 return clone;
128 };
129
130 /** A clone pushes a fake secret and a vulnerable pin to main, and the scan settles. */
131 const pushLeak = async () => {
132 const clone = await cloneRepo();
133 await writeFile(join(clone, "deploy.ts"), `export const key = "${AWS}";\n`);
134 await writeFile(join(clone, "package.json"), JSON.stringify({ dependencies: { lodash: "4.17.15" } }));
135 expect((await git(["add", "."], clone)).code).toBe(0);
136 expect((await git(["-c", "user.name=a", "-c", "user.email=a@x", "commit", "-qm", "oops"], clone)).code).toBe(0);
137 const pushed = await git(["push", "-q", "origin", "HEAD:main"], clone);
138 expect(pushed.code).toBe(0);
139 // The scan runs off the hook's answer: wait on the scan itself, not on a clock.
140 await scansSettled(app, repo.id);
141 };
142
143
116144 describe("a push", () => {
117145 test("a pushed fake secret is found, without its text", async () => {
118 const url = `${servers.url.replace("http://", `http://alice:${token.alice}@`)}/alice/square.git`;
119 const clone = join(work, "square");
120 expect((await git(["clone", "-q", url, clone], work)).code).toBe(0);
121 await writeFile(join(clone, "deploy.ts"), `export const key = "${AWS}";\n`);
122 await writeFile(join(clone, "package.json"), JSON.stringify({ dependencies: { lodash: "4.17.15" } }));
123 expect((await git(["add", "."], clone)).code).toBe(0);
124 expect((await git(["-c", "user.name=a", "-c", "user.email=a@x", "commit", "-qm", "oops"], clone)).code).toBe(0);
125 const pushed = await git(["push", "-q", "origin", "HEAD:main"], clone);
126 expect(pushed.code).toBe(0);
127 // The scan runs off the hook's answer: wait on the scan itself, not on a clock.
128 await scansSettled(app, repo.id);
146 await pushLeak();
129147 const found = listFindings(app.db, repo.id);
130148 expect(found.map((f) => [f.kind, f.path, f.line]).sort()).toEqual([
131149 ["advisory", "package.json", 0],
132150 ["secret", "deploy.ts", 1],
133151 ]);
134 const page = await (await fetch(`${servers.url}/alice/square/findings`)).text();
152 const page = await (await fetch(`${servers.url}/alice/${repo.name}/findings`)).text();
135153 expect(page).toContain("AWS access key");
136154 expect(page).toContain("deploy.ts:1");
137155 expect(page).not.toContain(AWS.slice(4));
138 const flows = await (await fetch(`${servers.url}/alice/square/flows`)).text();
156 const flows = await (await fetch(`${servers.url}/alice/${repo.name}/flows`)).text();
139157 expect(flows).toContain("Code scanning");
140158 expect(flows).toContain("2 high findings hold releases");
141159 }, 30_000);
142160
143161 test("a high finding holds a release; acceptance with a reason lifts it", async () => {
162 await pushLeak();
144163 const hold = await scanHold(app, repo, await tipOf());
145164 expect(hold.held).toBe(true);
146165 if (hold.held) expect(hold.line).not.toContain(AWS.slice(4));
@@ -154,7 +173,7 @@ describe("a push", () => {
154173 expect(acceptFinding(app, repo, alice, secret!.id, "again")).toMatchObject({ ok: false, status: 409 });
155174 expect((await scanHold(app, repo, await tipOf())).held).toBe(true);
156175 // Through the page's form, as a person does it.
157 const res = await fetch(`${servers.url}/alice/square/findings/${advisory!.id}/accept`, {
176 const res = await fetch(`${servers.url}/alice/${repo.name}/findings/${advisory!.id}/accept`, {
158177 method: "POST",
159178 headers: { authorization: `Bearer ${token.alice}`, "content-type": "application/x-www-form-urlencoded" },
160179 body: new URLSearchParams({ reason: "Dev only, upgrade tracked" }),
@@ -169,7 +188,7 @@ describe("a push", () => {
169188
170189 test("the nightly pass adds static analysis over the default branch and is then not due", async () => {
171190 ok(await commitToBranch(app, alice, repo, { message: "html", files: [{ path: "src/view.js", content: "el.inner" + "HTML = name;\n" }] }));
172 expect(nightlyDue(app.db, new Date().toISOString(), 10)).toContain(repo.id);
191 expect(nightlyDue(app.db, new Date().toISOString(), 1000)).toContain(repo.id);
173192 await scanNightly(app, repo);
174193 expect(listFindings(app.db, repo.id).some((f) => f.kind === "static" && f.path === "src/view.js")).toBe(true);
175194 expect(nightlyDue(app.db, new Date(Date.now() - 3_600_000).toISOString(), 10)).not.toContain(repo.id);
@@ -177,7 +196,7 @@ describe("a push", () => {
177196 });
178197
179198 test("a push of many new branches is scanned against main in a bounded number of git processes", async () => {
180 const clone = join(work, "square");
199 const clone = await cloneRepo();
181200 expect((await git(["fetch", "-q", "origin", "main"], clone)).code).toBe(0);
182201 let stream = "";
183202 for (let i = 0; i < 20; i++) {
@@ -223,7 +242,7 @@ describe("a push", () => {
223242 });
224243
225244 test("a file named with a newline is skipped and counted, and later files keep their own text", async () => {
226 const clone = join(work, "square");
245 const clone = await cloneRepo();
227246 expect((await git(["checkout", "-q", "-b", "nl", "origin/main"], clone)).code).toBe(0);
228247 expect((await git(["pull", "-q", "origin", "main"], clone)).code).toBe(0);
229248 await writeFile(join(clone, "a\nb.txt"), "plain\n");
@@ -239,14 +258,14 @@ describe("a push", () => {
239258 const at = listFindings(app.db, repo.id).filter((f) => f.oid === head);
240259 expect(at.map((f) => [f.path, f.line])).toEqual([["c.ts", 3]]);
241260 expect(lastScan(app.db, repo.id, "push")?.skipped).toBe(1);
242 const page = await (await fetch(`${servers.url}/alice/square/findings`)).text();
261 const page = await (await fetch(`${servers.url}/alice/${repo.name}/findings`)).text();
243262 expect(page).toContain("partial: 1 file not read");
244263 });
245264 });
246265
247266 describe("cat-file replies (#14959)", () => {
248267 test("a gitlink's commit body is stepped over: the file after it is still read", async () => {
249 const clone = join(work, "square");
268 const clone = await cloneRepo();
250269 expect((await git(["checkout", "-q", "-b", "gl", "origin/main"], clone)).code).toBe(0);
251270 expect((await git(["pull", "-q", "origin", "main"], clone)).code).toBe(0);
252271 const base = (await git(["rev-parse", "HEAD"], clone)).out.trim();
@@ -268,6 +287,7 @@ describe("cat-file replies (#14959)", () => {
268287 }, 30_000);
269288
270289 test("a missing name shaped like a blob header is read from the end and shifts no later reply", async () => {
290 await pushLeak();
271291 const tip = await tipOf();
272292 const deploy = listFindings(app.db, repo.id).find((f) => f.kind === "secret" && f.path === "deploy.ts")!;
273293 const ghost = { ...deploy, id: -1, path: "gone blob 100 x", fingerprint: "none" };
test/dataimport-doors.test.ts +3 −3
@@ -3,7 +3,7 @@
33 * gate as the API (the repository's admin; anyone else is offered nothing and
44 * changes nothing), the same engine, the same words.
55 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
77 import { mkdirSync, writeFileSync, existsSync } from "node:fs";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
@@ -31,7 +31,7 @@ let dee: User; // a reader
3131 let repo: Repo;
3232 let appId: string;
3333
34 beforeAll(async () => {
34 beforeEach(async () => {
3535 dataDir = await mkdtemp(join(tmpdir(), "forge-import-doors-"));
3636 app = createApp({ dataDir, port: 0, host: "forge.test" });
3737 const make = async (username: string, adminIfFirst = false) => {
@@ -54,7 +54,7 @@ beforeAll(async () => {
5454 writeFileSync(join(dir, "dump.sql"), "CREATE TABLE t(a); INSERT INTO t VALUES (1),(2);");
5555 }, 60_000);
5656
57 afterAll(async () => {
57 afterEach(async () => {
5858 app.db.close();
5959 await rm(dataDir, { recursive: true, force: true });
6060 });
test/feed-chips.test.ts +4 −2
@@ -2,7 +2,7 @@
22 * The chips: each switches off what it names and nothing else, through the
33 * one filter, on the feed API and the pure function alike; saved per viewer.
44 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5 import { afterAll, beforeAll, describe, expect, onTestFinished, test } from "bun:test";
66 import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
@@ -240,7 +240,9 @@ describe("the chips of a forge", () => {
240240
241241 test("a count is the posts drawn of its kind, whatever asks the home pins aside", async () => {
242242 const cookie = { cookie: `forge_session=${createSession(app.db, alice.id).token}` };
243 emit("pull.opened", carol, { number: 2, title: "Wait for me" });
243 const opened = emit("pull.opened", carol, { number: 2, title: "Wait for me" });
244 // The extra ask is this test's alone: it leaves the feed as it found it.
245 onTestFinished(() => void app.db.run("DELETE FROM event WHERE id = ?1", [opened.id]));
244246 const page = await (await fetch(`${servers.url}/live/feed`, { headers: cookie })).text();
245247 const drawnPulls = [...page.matchAll(/data-item="[^"]*"[^>]*data-kind="pull"/g)].length;
246248 expect(page).toMatch(new RegExp(`Pull requests ${drawnPulls}\\s*<`));
test/feed-team-waits.test.ts +3 −3
@@ -5,7 +5,7 @@
55 */
66
77 import { seatAs } from "./helpers/seat.ts";
8 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { afterEach, beforeEach, expect, test } from "bun:test";
99 import { mkdtemp, rm } from "node:fs/promises";
1010 import { tmpdir } from "node:os";
1111 import { join } from "node:path";
@@ -67,7 +67,7 @@ const pullNaming = async (teams: string[], opts: { late?: true; in?: Repo } = {}
6767 return o.value;
6868 };
6969
70 beforeAll(async () => {
70 beforeEach(async () => {
7171 dataDir = await mkdtemp(join(tmpdir(), "forge-feed-team-waits-"));
7272 app = createApp({ dataDir, port: 0 });
7373 const made = await createUser(app.db, {
@@ -97,7 +97,7 @@ beforeAll(async () => {
9797 saveTeam(app.db, "data-science", { charter: "", dial: 0, members: [user("pike").id] });
9898 }, 120_000);
9999
100 afterAll(async () => {
100 afterEach(async () => {
101101 for (let i = 0; i < 20; i++) await new Promise((done) => setImmediate(done));
102102 await Bun.sleep(100);
103103 app?.close();
test/flows-actions.test.ts +5 −3
@@ -1,5 +1,5 @@
11 /** Acting on a flow line where it stands (#9591): follow or stop, update a dependency; writer yes, reader and cross-origin no. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
33 import { createHmac } from "node:crypto";
44 import { mkdtemp, rm } from "node:fs/promises";
55 import { tmpdir } from "node:os";
@@ -21,14 +21,14 @@ let dir: string;
2121 let app: App;
2222 let servers: Servers;
2323 const KEY = "flows-actions-key";
24 beforeAll(async () => {
24 beforeEach(async () => {
2525 dir = await mkdtemp(join(tmpdir(), "forge-flows-actions-"));
2626 app = createApp({ dataDir: dir, port: 0, previewIdentityKey: KEY });
2727 const seeded = await seedPreview(app, { FORGE_APP_ENV: "preview" });
2828 if (!seeded.ok) throw new Error(seeded.error);
2929 servers = await serve(app);
3030 }, 30_000);
31 afterAll(async () => {
31 afterEach(async () => {
3232 servers.stop();
3333 app.close();
3434 await rm(dir, { recursive: true, force: true });
@@ -63,6 +63,8 @@ describe("follow or stop, on the line", () => {
6363 });
6464
6565 test("the action posts through the existing route: admin stops it, cross-origin and anonymous do not", async () => {
66 const repo = repoNow();
67 app.db.query("INSERT INTO repo_source (id, repo_id, url, branch, by_id, created_at) VALUES ('sa', ?1, 'https://example.com/a.git', 'main', 'u1', '2026-11-01T00:00:00Z')").run(repo.id);
6668 const url = `${servers.url}/${PREVIEW_ADMIN}/${PREVIEW_REPO}/settings/sources/sa/remove`;
6769 const count = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM repo_source WHERE id = 'sa'").get()!.n;
6870 const cross = await fetch(url, { method: "POST", redirect: "manual", headers: { ...headers(), origin: "https://evil.example" } });
test/forge-budget-verdict.test.ts +4 −4
@@ -5,7 +5,7 @@
55 * limit; a wake wakes only what its cause can fix; the terminal door is
66 * gated like the page.
77 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
99 import { mkdtemp, rm } from "node:fs/promises";
1010 import { writeFileSync } from "node:fs";
1111 import { tmpdir } from "node:os";
@@ -45,7 +45,7 @@ describe("the owner's limits as a verdict", () => {
4545 app.db.query("DELETE FROM run").run();
4646 };
4747
48 beforeAll(async () => {
48 beforeEach(async () => {
4949 dir = await mkdtemp(join(tmpdir(), "forge-verdict-"));
5050 app = createApp({ dataDir: dir, port: 0 });
5151 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-starter-passphrase", adminIfFirst: true });
@@ -58,7 +58,7 @@ describe("the owner's limits as a verdict", () => {
5858 repo = r.value;
5959 app.db.query("UPDATE repo SET autonomy = 'autonomous' WHERE id = ?1").run(repo.id);
6060 });
61 afterAll(async () => {
61 afterEach(async () => {
6262 app?.close();
6363 await rm(dir, { recursive: true, force: true });
6464 });
@@ -69,7 +69,7 @@ describe("the owner's limits as a verdict", () => {
6969 });
7070
7171 describe("on a forge of its own", () => {
72 beforeAll(() => writeFileSync(join(dir, "parent.json"), "{}"));
72 beforeEach(() => writeFileSync(join(dir, "parent.json"), "{}"));
7373
7474 test("a spent day stops the run and names the day limit", () => {
7575 clear();
test/forge-signin.test.ts +21 −8
@@ -291,19 +291,31 @@ describe("sign in through the parent forge", () => {
291291 drained: async () => {},
292292 };
293293 forgeSshSession(child)(session as never);
294 await Bun.sleep(300);
294 // The first paint is not instant on a cold process: wait for it, not a fixed time.
295 for (let i = 0; i < 60 && !screen.includes("alice"); i++) await Bun.sleep(50); // real-timer: the terminal paints on its own clock
295296 session.exit();
296297 expect(screen).toContain("alice");
297298 });
298299
299300 test("starting a sign-in is throttled, so a flood cannot push out those in flight", async () => {
300 const statuses: number[] = [];
301 for (let i = 0; i < 30; i++)
302 statuses.push((await fetch(`${childServers.url}/signin/parent`, { redirect: "manual" })).status);
303 expect(statuses).toContain(429);
304 const slow = await fetch(`${childServers.url}/signin/parent`, { redirect: "manual" });
305 expect(slow.status).toBe(429);
306 expect(Number(slow.headers.get("retry-after"))).toBeGreaterThan(0);
301 // Its own child, already holding its registration: the flood spends this forge's budget and
302 // registers nothing at the shared parent.
303 const dir = await mkdtemp(join(tmpdir(), "forge-signin-"));
304 dirs.push(dir);
305 const flooded = createApp({ dataDir: dir, port: 0, parentUrl: parentServers.url, parentLoopback: true });
306 const floodedServers = await serve(flooded);
307 keepClient(flooded.db, parentServers.url, `${floodedServers.url}${CALLBACK_PATH}`, "client-1");
308 try {
309 const statuses: number[] = [];
310 for (let i = 0; i < 30; i++)
311 statuses.push((await fetch(`${floodedServers.url}/signin/parent`, { redirect: "manual" })).status);
312 expect(statuses).toContain(429);
313 const slow = await fetch(`${floodedServers.url}/signin/parent`, { redirect: "manual" });
314 expect(slow.status).toBe(429);
315 expect(Number(slow.headers.get("retry-after"))).toBeGreaterThan(0);
316 } finally {
317 floodedServers.stop();
318 }
307319 });
308320 });
309321
@@ -487,6 +499,7 @@ describe("a parent's oversized register and token answers", () => {
487499
488500 test("a registration that streams forever is a 502, and few chunks are pulled", async () => {
489501 streaming = "register";
502 child.db.query("DELETE FROM rp_client").run();
490503 const res = await fetch(`${servers.url}/signin/parent`, { redirect: "manual" });
491504 expect(res.status).toBe(502);
492505 expect(pulled.n).toBeGreaterThan(0);
test/forks.test.ts +19 −6
@@ -1,4 +1,4 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
@@ -82,7 +82,8 @@ describe("forks", () => {
8282 return await res.text();
8383 };
8484
85 beforeAll(async () => {
85 // A fresh forge for every test: none leans on a fork or a commit another made.
86 beforeEach(async () => {
8687 dataDir = await mkdtemp(join(tmpdir(), "forge-fork-"));
8788 app = createApp({ dataDir, port: 0 });
8889 servers = await serve(app);
@@ -107,12 +108,19 @@ describe("forks", () => {
107108 await commitAs("alice", upstream, "README.md", "seed");
108109 }, 60_000);
109110
110 afterAll(async () => {
111 afterEach(async () => {
111112 servers.stop();
112113 app.close();
113114 await rm(dataDir, { recursive: true, force: true });
114115 });
115116
117 /** Bob's fork of upstream, with a commit of his own. */
118 const bobWithWork = async () => {
119 const bob = await forkAs("bob", upstream);
120 await commitAs("bob", bob, "feature.txt", "bob feature");
121 return bob;
122 };
123
116124 test("a fork borrows its parent's objects and a push to it never reaches the parent", async () => {
117125 const bob = await forkAs("bob", upstream);
118126 expect(bob.ownerName).toBe("bob");
@@ -129,6 +137,7 @@ describe("forks", () => {
129137 });
130138
131139 test("a fork follows its parent fast-forward only; one with work of its own is refused", async () => {
140 const bobOwn = await bobWithWork();
132141 const carol = await forkAs("carol", upstream);
133142 await commitAs("alice", upstream, "NEWS.md", "alice moves on");
134143 const moved = await tip(upstream);
@@ -140,8 +149,7 @@ describe("forks", () => {
140149 expect(again.to).toBe(moved!);
141150
142151 // The follower never merges: bob has work of his own and stays where he was.
143 const bob = getRepo(app.db, "bob", "app")!;
144 expect(await tip(bob)).not.toBe(moved);
152 expect(await tip(bobOwn)).not.toBe(moved);
145153 });
146154
147155 test("Update from parent merges a diverged fork cleanly, and refuses a conflicting one untouched", async () => {
@@ -194,6 +202,9 @@ describe("forks", () => {
194202 }, 30_000);
195203
196204 test("the About rail says how far a fork is from its parent, and offers an update only when one can be taken", async () => {
205 // Bob has work of his own; upstream then moves once, before dan forks.
206 await bobWithWork();
207 await commitAs("alice", upstream, "NEWS.md", "alice moves on");
197208 // Dan forks as upstream stands: level, nothing offered.
198209 await forkAs("dan", upstream);
199210 const current = await page("/dan/app", "dan");
@@ -223,6 +234,7 @@ describe("forks", () => {
223234 });
224235
225236 test("the fork count opens the list, and counts only forks the viewer may read", async () => {
237 for (const who of ["bob", "carol", "dan"]) await forkAs(who, upstream);
226238 const home = await page("/alice/app");
227239 expect(home).toContain('href="/alice/app/forks"');
228240 expect(home).toContain("3 forks");
@@ -246,6 +258,7 @@ describe("forks", () => {
246258 expect(refused.ok).toBe(false);
247259 if (!refused.ok) expect(refused.error).toBe("not_found");
248260
261 await forkAs("bob", upstream);
249262 const twice = await forkRepo(app, users["bob"]!, upstream);
250263 expect(twice.ok).toBe(false);
251264 if (!twice.ok) expect(twice.error).toBe("already_forked");
@@ -271,7 +284,7 @@ describe("forks", () => {
271284 });
272285
273286 test("deleting the parent detaches the fork, which survives whole", async () => {
274 const bob = getRepo(app.db, "bob", "app")!;
287 const bob = await bobWithWork();
275288 must(await deleteRepo(app, users["alice"]!, upstream));
276289
277290 expect(
test/front.test.ts +9 −3
@@ -5,7 +5,7 @@
55 * MCP alike. Refusals first: a stranger and a plain member never set it, and
66 * nothing private is ever shown, pinned or not.
77 */
8 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
8 import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
99 import { mkdirSync, writeFileSync } from "node:fs";
1010 import { mkdtemp, rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
@@ -224,7 +224,8 @@ describe("the front page", () => {
224224 body: JSON.stringify(body),
225225 });
226226
227 beforeAll(async () => {
227 // A fresh forge for every test: none leans on an app or a pin another made.
228 beforeEach(async () => {
228229 dataDir = await mkdtemp(join(tmpdir(), "forge-front-"));
229230 app = createApp({ dataDir, port: 0 });
230231 servers = await serve(app);
@@ -294,7 +295,7 @@ describe("the front page", () => {
294295 };
295296 }, 30_000);
296297
297 afterAll(async () => {
298 afterEach(async () => {
298299 restore();
299300 await runtime.stop();
300301 servers.stop();
@@ -467,6 +468,9 @@ describe("the front page", () => {
467468 });
468469
469470 test("a site admin pins, orders and hides; the first pin a stranger can read is featured, a private pin never shows", async () => {
471 await make(admin, "two");
472 await make(admin, "three");
473 await make(other, "loved");
470474 // The forge's own repository, still private: pinned first, shown never.
471475 const own = await createRepo(app, admin, {
472476 name: "forge",
@@ -621,6 +625,7 @@ describe("the front page", () => {
621625 expect(body).not.toContain("A merge nobody outside may read");
622626 });
623627 test("featured shows the crew at work on it right now, by issue", async () => {
628 await make(admin, "two");
624629 const issue = openIssue(
625630 app,
626631 admin,
@@ -653,6 +658,7 @@ describe("the front page", () => {
653658 });
654659
655660 test("never a letter tile: a pin without a stranger's picture, or one that is down, waits; the sweep wakes a pinned app asleep to picture it", async () => {
661 await make(admin, "two");
656662 await make(admin, "pinned-bare", { picture: false });
657663 const down = await make(admin, "pinned-down");
658664 states.set(down.record.id, "failed");
test/mcp-releases.test.ts +3 −3
@@ -1,5 +1,5 @@
11 /** `releases` is the /releases page over MCP: the same list, the same gate, no rollback. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
@@ -43,7 +43,7 @@ describe("MCP releases", () => {
4343 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
4444 };
4545
46 beforeAll(async () => {
46 beforeEach(async () => {
4747 process.env["FORGE_COMMIT"] = LIVE;
4848 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-releases-"));
4949 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge" });
@@ -65,7 +65,7 @@ describe("MCP releases", () => {
6565 repoId = made.value.id;
6666 }, 30_000);
6767
68 afterAll(async () => {
68 afterEach(async () => {
6969 if (saved === undefined) delete process.env["FORGE_COMMIT"];
7070 else process.env["FORGE_COMMIT"] = saved;
7171 servers.stop();
test/origins-import-labels.test.ts +7 −3
@@ -1,4 +1,4 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
@@ -42,7 +42,7 @@ const newIssue = (title: string) => {
4242 return made.value.id;
4343 };
4444
45 beforeAll(async () => {
45 beforeEach(async () => {
4646 dir = await mkdtemp(join(tmpdir(), "forge-origin-labels-"));
4747 app = createApp({ dataDir: dir, port: 0 });
4848 const admin = await seedAdmin(app, {
@@ -57,7 +57,7 @@ beforeAll(async () => {
5757 repoId = repo.value.id;
5858 });
5959
60 afterAll(async () => {
60 afterEach(async () => {
6161 await rm(dir, { recursive: true, force: true });
6262 });
6363
@@ -73,6 +73,10 @@ describe("importLabels", () => {
7373 });
7474
7575 test("a re-sync adopts the row by name, case-insensitively, and takes the new colour", () => {
76 importLabels(app.db, repoId, [
77 { remoteId: "1", name: "bug", color: "d73a4a" },
78 { remoteId: "2", name: "docs", color: "0075ca" },
79 ]);
7680 importLabels(app.db, repoId, [{ remoteId: "9", name: "BUG", color: "000000" }]);
7781 expect(rows()).toEqual(["bug", "docs"]);
7882 const bug = app.db
test/perf-jobs-per-forge.test.ts +3 −3
@@ -3,7 +3,7 @@
33 * two forges booted in one process, as two test files are, never read each
44 * other's jobs or children, and each forge's loop watch reads its own.
55 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { afterEach, beforeEach, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
@@ -16,13 +16,13 @@ let dirs: string[] = [];
1616 let one: App;
1717 let other: App;
1818
19 beforeAll(async () => {
19 beforeEach(async () => {
2020 dirs = [await mkdtemp(join(tmpdir(), "jobs-one-")), await mkdtemp(join(tmpdir(), "jobs-other-"))];
2121 one = createApp({ dataDir: dirs[0]!, url: "https://one.test", port: 0 });
2222 other = createApp({ dataDir: dirs[1]!, url: "https://other.test", port: 0 });
2323 });
2424
25 afterAll(async () => {
25 afterEach(async () => {
2626 one?.close();
2727 other?.close();
2828 for (const d of dirs) await rm(d, { recursive: true, force: true });
test/pinned-forge-recovery.test.ts +23 −2
@@ -4,7 +4,7 @@
44 * all leave a row a retry finishes. The terminal door reaches the same actions.
55 */
66 import { BUN_INTEGRITY } from "../src/cloud/bun_install.ts";
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
@@ -68,6 +68,19 @@ describe("pinned forge recovery", () => {
6868 };
6969 });
7070
71 // Every test starts with no pinned forge and no stubbed history; it deploys what it needs.
72 beforeEach(() => {
73 app.db.run("DELETE FROM pinned_forge");
74 calls.length = 0;
75 fail.clear();
76 deleted = new Set();
77 });
78 /** A running acme at V1, as a first deploy leaves it. */
79 const running = async () => {
80 expect((await deployPinned(app, admin(), input())).ok).toBe(true);
81 calls.length = 0;
82 };
83
7184 afterAll(async () => {
7285 app.close();
7386 await rm(dataDir, { recursive: true, force: true });
@@ -89,6 +102,7 @@ describe("pinned forge recovery", () => {
89102 });
90103
91104 test("an Update whose create fails after the delete can be rolled back or tried again", async () => {
105 await running();
92106 fail.set("POST /v2/droplets", 500);
93107 expect((await updatePinned(app, admin(), "acme", { version: V2 })).ok).toBe(false);
94108 expect(getPinned(app.db, "acme")).toMatchObject({ state: "failed", remote: "", version: V2 });
@@ -101,6 +115,7 @@ describe("pinned forge recovery", () => {
101115 });
102116
103117 test("a droplet already gone (404) counts as deleted", async () => {
118 await running();
104119 app.db.run("UPDATE pinned_forge SET remote = '777' WHERE name = 'acme'");
105120 deleted.add("/v2/droplets/777");
106121 expect((await updatePinned(app, admin(), "acme", { version: V2 })).ok).toBe(true);
@@ -108,7 +123,10 @@ describe("pinned forge recovery", () => {
108123 });
109124
110125 test("a failed forge may be told the version it already has, to finish the replacement", async () => {
111 app.db.run("UPDATE pinned_forge SET state = 'failed', remote = '' WHERE name = 'acme'");
126 await running();
127 fail.set("POST /v2/droplets", 500);
128 expect((await updatePinned(app, admin(), "acme", { version: V2 })).ok).toBe(false);
129 expect(getPinned(app.db, "acme")).toMatchObject({ state: "failed", version: V2 });
112130 expect((await updatePinned(app, admin(), "acme", { version: V2 })).ok).toBe(true);
113131 expect(getPinned(app.db, "acme")?.state).toBe("running");
114132 });
@@ -124,6 +142,8 @@ describe("pinned forge recovery", () => {
124142 });
125143
126144 test("terminal: the palette offers Pinned forges to an admin only; d, u and r reach the actions", async () => {
145 await running();
146 expect((await updatePinned(app, admin(), "acme", { version: V2 })).ok).toBe(true);
127147 const bob = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, "bob")! });
128148 const alice = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin() });
129149 expect(entry.offered(bob)).toBe(false);
@@ -147,6 +167,7 @@ describe("pinned forge recovery", () => {
147167 });
148168
149169 test("terminal: the screen follows the bus while it is on the stack", async () => {
170 await running();
150171 const alice = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin() });
151172 let invalidated = 0;
152173 const ctx = { push() {}, invalidate: () => invalidated++ } as never;
test/snapshot-mirror-page.test.ts +4 −3
@@ -4,7 +4,7 @@
44 * page never shows a value; a blank field keeps what was sealed; clear removes
55 * the names and, once the pass settles, the board card.
66 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
88 import { mkdtempSync, rmSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
@@ -54,7 +54,7 @@ describe("the mirror's admin routes", () => {
5454 );
5555 const sealed = () => mirrorSealedSet(app.db).sort();
5656
57 beforeAll(async () => {
57 beforeEach(async () => {
5858 root = mkdtempSync(join(tmpdir(), "forge-mirrorpage-"));
5959 app = createApp({ dataDir: root, port: 0 });
6060 for (const [username, password, adminIfFirst] of [
@@ -82,7 +82,7 @@ describe("the mirror's admin routes", () => {
8282 });
8383 servers = await serve(app);
8484 });
85 afterAll(async () => {
85 afterEach(async () => {
8686 servers.stop();
8787 await svc.stop();
8888 app.close();
@@ -120,6 +120,7 @@ describe("the mirror's admin routes", () => {
120120
121121 test("a blank field keeps what was sealed, and a changed target drops the old pass", async () => {
122122 const alice = await login("alice", "a-good-passphrase");
123 expect((await post("/mirror", full, alice)).status).toBe(303);
123124 await svc.mirrorFresh();
124125 recordMirror(root, { where: "old/bucket", attemptAt: new Date().toISOString(), reachable: true, syncedAt: new Date().toISOString() });
125126 expect((await post("/mirror", { ...full, endpoint: "", bucket: "other-bucket", access_key: "", secret_key: "" }, alice)).status).toBe(303);
test/spawn-upstream.test.ts +11 −5
@@ -73,9 +73,11 @@ describe("looking upstream", () => {
7373 });
7474
7575 test("an unreachable upstream keeps its error and what was known", async () => {
76 const known = await checkUpstream(app, { remote: parent, now: 2500 });
77 expect(known?.error).toBe("");
7678 const s = await checkUpstream(app, { remote: join(dir, "nowhere.git"), now: 3000 });
7779 expect(s?.error).not.toBe("");
78 expect(s?.behind).toBe(3);
80 expect(s?.behind).toBe(known!.behind);
7981 expect((await upstreamState(app))?.error).toBe(s!.error);
8082 });
8183
@@ -179,9 +181,13 @@ describe("looking upstream", () => {
179181 });
180182
181183 test("a severed forge is not checked", async () => {
182 const doc = await Bun.file(join(app.config.dataDir, "parent.json")).json();
183 doc.forgeCode.severedAt = new Date().toISOString();
184 await Bun.write(join(app.config.dataDir, "parent.json"), JSON.stringify(doc));
185 expect(await checkUpstream(app, { remote: parent })).toBeUndefined();
184 const file = join(app.config.dataDir, "parent.json");
185 const doc = await Bun.file(file).json();
186 try {
187 await Bun.write(file, JSON.stringify({ ...doc, forgeCode: { ...doc.forgeCode, severedAt: new Date().toISOString() } }));
188 expect(await checkUpstream(app, { remote: parent })).toBeUndefined();
189 } finally {
190 await Bun.write(file, JSON.stringify(doc));
191 }
186192 });
187193 });
test/teams-crew.test.ts +18 −2
@@ -7,7 +7,7 @@
77 * the org page lists each team's members with their roles, escaped.
88 */
99
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
1111 import { mkdtemp, rm } from "node:fs/promises";
1212 import { tmpdir } from "node:os";
1313 import { join } from "node:path";
@@ -109,6 +109,15 @@ describe("teams drive the crew", () => {
109109 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
110110 });
111111
112 // Every test starts from the same crew: the write team seats sentinel as
113 // builder and juniper as reviewer; no one else holds a seat. A test that
114 // needs more builds it in its own body.
115 beforeEach(() => {
116 app.db.query("DELETE FROM team_member WHERE team_id IN (?1, ?2)").run(crewTeam.id, readers.id);
117 expect(addTeamMember(app.db, crewTeam, sentinel.id, "builder")).toBe(true);
118 expect(addTeamMember(app.db, crewTeam, juniper.id, "reviewer")).toBe(true);
119 });
120
112121 afterAll(async () => {
113122 servers?.stop();
114123 await rm(dataDir, { recursive: true, force: true });
@@ -123,6 +132,7 @@ describe("teams drive the crew", () => {
123132 });
124133
125134 test("with no agent seated by a write team the roster is the crew, unchanged", () => {
135 app.db.query("DELETE FROM team_member WHERE team_id = ?1").run(crewTeam.id);
126136 // An agent on a read team grants nothing.
127137 expect(addTeamMember(app.db, readers, mason.id, "reviewer")).toBe(true);
128138 for (const target of [teamed, rostered, personal]) {
@@ -135,6 +145,7 @@ describe("teams drive the crew", () => {
135145 });
136146
137147 test("a write team with a reviewer is the crew: the routing picks its reviewer", () => {
148 app.db.query("DELETE FROM team_member WHERE team_id = ?1").run(crewTeam.id);
138149 expect(addTeamMember(app.db, crewTeam, mason.id, "reviewer")).toBe(true);
139150 expect(addTeamMember(app.db, crewTeam, sentinel.id, "builder")).toBe(true);
140151 // Every repository the org owns now reads its crew from the team …
@@ -152,7 +163,8 @@ describe("teams drive the crew", () => {
152163 });
153164
154165 test("a write team without a reviewer leaves the seat empty, not the roster's", () => {
155 app.db.query("UPDATE team_member SET role = 'planner' WHERE team_id = ?1 AND user_id = ?2").run(crewTeam.id, mason.id);
166 app.db.query("DELETE FROM team_member WHERE team_id = ?1 AND user_id = ?2").run(crewTeam.id, juniper.id);
167 expect(addTeamMember(app.db, crewTeam, mason.id, "planner")).toBe(true);
156168 expect(reviewersOf(app.db, teamed.id)).toEqual([]);
157169 expect(names(crewWithRole(app.db, [teamed.id], "planner").get(teamed.id))).toEqual(["mason"]);
158170 expect(reposWithBuilder(app.db, [teamed.id, personal.id])).toEqual(new Set([teamed.id, personal.id]));
@@ -160,6 +172,8 @@ describe("teams drive the crew", () => {
160172 });
161173
162174 test("a plain member of a write team holds no seat, so a membership from before roles changes no crew", async () => {
175 app.db.query("DELETE FROM team_member WHERE team_id = ?1 AND user_id = ?2").run(crewTeam.id, juniper.id);
176 expect(addTeamMember(app.db, crewTeam, mason.id, "planner")).toBe(true);
163177 const second = createTeam(app.db, org.id, "Second", "write");
164178 if (!second.ok) throw new Error(second.error);
165179 expect(addTeamMember(app.db, second.value, juniper.id)).toBe(true);
@@ -190,6 +204,7 @@ describe("teams drive the crew", () => {
190204 });
191205
192206 test("POST accepts and validates a role; GET lists it", async () => {
207 expect(addTeamMember(app.db, crewTeam, mason.id, "planner")).toBe(true);
193208 const bad = await api("POST", "", { user: "mason", role: "king" });
194209 expect(bad.status).toBe(422);
195210 expect(((await bad.json()) as { error: string }).error).toBe("bad_role");
@@ -205,6 +220,7 @@ describe("teams drive the crew", () => {
205220 });
206221
207222 test("DELETE with a role takes that role off and keeps the member; a bad role is refused", async () => {
223 expect(addTeamMember(app.db, crewTeam, mason.id, "reviewer")).toBe(true);
208224 expect((await api("DELETE", "/mason?role=king")).status).toBe(422);
209225 expect((await api("DELETE", "/mason?role=builder")).status).toBe(404);
210226 expect((await api("DELETE", "/mason?role=reviewer")).status).toBe(204);
test/tui-newforge-recipes.test.ts +9 −6
@@ -2,7 +2,7 @@
22 * The terminal's New forge screen has the page's recipes (#649): apps with a mode, Save as recipe,
33 * and Spawn from recipe, through the same door.
44 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { afterEach, beforeEach, expect, test } from "bun:test";
66 import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
@@ -23,7 +23,7 @@ let dir: string;
2323 let app: App;
2424 let admin: User;
2525
26 beforeAll(async () => {
26 beforeEach(async () => {
2727 dir = await mkdtemp(join(tmpdir(), "forge-tui-newforge-recipes-"));
2828 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
2929 const r = await createUser(app.db, {
@@ -35,7 +35,7 @@ beforeAll(async () => {
3535 useProbe(app, () => async () => true);
3636 usePlacement(app, hostedPlacement({ host: "forge.test" }));
3737 });
38 afterAll(async () => {
38 afterEach(async () => {
3939 app.db.close();
4040 await rm(dir, { recursive: true, force: true });
4141 });
@@ -64,10 +64,11 @@ async function open(keys: string): Promise<string> {
6464 }
6565 }
6666
67 const KEEP_KEYS =
68 "zed" + TAB.repeat(3) + "alice/shop:autonomous, alice/old:migration" + TAB.repeat(4) + "20" + TAB.repeat(6) + "client kit" + "\x10";
69
6770 test("Save as recipe keeps the apps with their modes and the budget, with the plan", async () => {
68 const keys =
69 "zed" + TAB.repeat(3) + "alice/shop:autonomous, alice/old:migration" + TAB.repeat(4) + "20" + TAB.repeat(6) + "client kit" + "\x10";
70 const screen = await open(keys);
71 const screen = await open(KEEP_KEYS);
7172 // Kept before the plan is asked for; the plan itself may refuse apps this forge does not have.
7273 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
7374 expect(listRecipes(dir, admin.id)[0]!.config).toEqual({
@@ -78,12 +79,14 @@ test("Save as recipe keeps the apps with their modes and the budget, with the pl
7879 });
7980
8081 test("a bad recipe name is refused beside its field and nothing is kept", async () => {
82 await open(KEEP_KEYS);
8183 const screen = await open("zed" + TAB.repeat(13) + "no/slash!" + "\x10");
8284 expect(screen).toContain("recipe name is 1-40 characters");
8385 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
8486 });
8587
8688 test("Spawn from recipe is offered once there is one", async () => {
89 await open(KEEP_KEYS);
8790 const screen = await open(TAB.repeat(14));
8891 expect(screen).toContain("Spawn from recipe");
8992 });
test/tui-signins-password.test.ts +3 −3
@@ -8,7 +8,7 @@
88 * account reads as Settings does; the typed text never appears in any frame a
99 * run painted; an agent is not offered `p`.
1010 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
1212 import { mkdtemp, rm } from "node:fs/promises";
1313 import { tmpdir } from "node:os";
1414 import { join } from "node:path";
@@ -95,7 +95,7 @@ describe("changing your password from the terminal", () => {
9595 const signsIn = async (username: string, password: string) =>
9696 (await new Session(forge, { sshUsername: "t", remoteAddress: "10.0.0.9" }).signIn(username, password)).ok;
9797
98 beforeAll(async () => {
98 beforeEach(async () => {
9999 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-signins-password-"));
100100 forge = createApp({ dataDir, port: 0 });
101101 const made = await createUser(forge.db, {
@@ -117,7 +117,7 @@ describe("changing your password from the terminal", () => {
117117 });
118118 if (!bob.ok) throw new Error(bob.error);
119119 });
120 afterAll(async () => {
120 afterEach(async () => {
121121 forge.close();
122122 await rm(dataDir, { recursive: true, force: true });
123123 });
test/view-source.test.ts +23 −5
@@ -1,4 +1,4 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
@@ -112,7 +112,19 @@ describe("RepoSource: one repository, two places to read it from", () => {
112112
113113 const requests = (): number => fake.state.requests.length;
114114
115 beforeAll(async () => {
115 /** Mirror octo/widgets and wait for the job to end. */
116 const mirrorWidgets = async (): Promise<void> => {
117 const started = await api(`/api/v1/user/origins/${originId}/mirror`, {
118 method: "POST",
119 body: JSON.stringify({ fullName: "octo/widgets" }),
120 });
121 expect(started.status).toBe(202);
122 const job = (await read<{ job: { id: string } }>(started)).job;
123 expect((await settled(job.id))?.stage).toBe("done");
124 };
125
126 // Two forges and an origin, new for every test: none leans on a mirror or a cache another warmed.
127 beforeEach(async () => {
116128 dataDir = await mkdtemp(join(tmpdir(), "forge-view-"));
117129 originDataDir = await mkdtemp(join(tmpdir(), "forge-view-up-"));
118130
@@ -297,7 +309,7 @@ describe("RepoSource: one repository, two places to read it from", () => {
297309 clearViewCache();
298310 });
299311
300 afterAll(async () => {
312 afterEach(async () => {
301313 fake.stop();
302314 servers.stop();
303315 originServers.stop();
@@ -598,7 +610,9 @@ describe("RepoSource: one repository, two places to read it from", () => {
598610
599611 test("mirroring busts what the browse cache believed", async () => {
600612 const source = live("octo/widgets");
601 // The mirror above ran after the cache was warmed by earlier reads.
613 // The cache is warmed by a read, then the mirror runs.
614 await source.tree("main", "");
615 await mirrorWidgets();
602616 const before = requests();
603617 await source.tree("main", "");
604618 expect(requests()).toBeGreaterThan(before);
@@ -669,6 +683,7 @@ describe("RepoSource: one repository, two places to read it from", () => {
669683 // ---- the equivalence that makes the interface worth having ----
670684
671685 test("the mirror and the origin answer the same questions the same way", async () => {
686 await mirrorWidgets();
672687 // Compare against the finished mirror: if the test that started it ran
673688 // out of time on a loaded machine, its import may still be running.
674689 const importing = runningJob(originId, "octo/widgets");
@@ -821,7 +836,8 @@ describe("RepoSource: one repository, two places to read it from", () => {
821836 // is the answers', not the clock's.
822837 }, 60_000);
823838
824 test("a local source refuses a repo the viewer cannot read", () => {
839 test("a local source refuses a repo the viewer cannot read", async () => {
840 await mirrorWidgets();
825841 app.db
826842 .query("UPDATE repo SET visibility = 'private' WHERE name = 'widgets'")
827843 .run();
@@ -843,6 +859,7 @@ describe("RepoSource: one repository, two places to read it from", () => {
843859 // ---- the API over it ----
844860
845861 test("the browse routes answer with the local shapes", async () => {
862 await mirrorWidgets();
846863 const landing = await read<{
847864 source: string;
848865 fullName: string;
@@ -995,6 +1012,7 @@ describe("RepoSource: one repository, two places to read it from", () => {
9951012 });
9961013
9971014 test("the picker says which rows are already mirrored", async () => {
1015 await mirrorWidgets();
9981016 const rows = await read<
9991017 { fullName: string; mirroredAs: { owner: string; name: string } | null }[]
10001018 >(await api(`/api/v1/user/origins/${originId}/repos?refresh=1`));

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs