Cotton code
158 lines · 6.1 KB · TypeScriptRaw
import { execFileSync } from "node:child_process";import { readFileSync } from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";import { WORKER_ENV_VARS, boxTestTimeout, parseWorkerCap, takeWorkerCap } from "../../vitest.workers";const ROOT = path.resolve(__dirname, "../..");/** Every workspace directory that runs vitest, from git rather than a hand-kept list. */function testablePackages(): { dir: string; config: string | null }[] {  const manifests = execFileSync("git", ["ls-files", "packages/*/package.json", "apps/*/package.json"], {    cwd: ROOT,    encoding: "utf8",  })    .split("\n")    .filter(Boolean);  const out: { dir: string; config: string | null }[] = [];  for (const manifest of manifests) {    const pkg = JSON.parse(readFileSync(path.join(ROOT, manifest), "utf8")) as {      scripts?: Record<string, string>;    };    if (!pkg.scripts?.test?.includes("vitest")) continue;    const dir = path.dirname(manifest);    const config =      ["vitest.config.ts", "vitest.config.mts", "vite.config.ts"].find((name) => {        try {          readFileSync(path.join(ROOT, dir, name), "utf8");          return true;        } catch {          return false;        }      }) ?? null;    out.push({ dir, config });  }  return out;}describe("parseWorkerCap — the one knob, parsed the same way everywhere", () => {  it("answers undefined when nothing is set, so the default stays the default", () => {    expect(parseWorkerCap(undefined)).toBeUndefined();    expect(parseWorkerCap("")).toBeUndefined();  });  it("reads a whole number", () => {    expect(parseWorkerCap("2")).toBe(2);    expect(parseWorkerCap(" 3 ")).toBe(3);  });  it("passes a percentage through, because vitest understands one", () => {    expect(parseWorkerCap("50%")).toBe("50%");  });  it.each(["nonsense", "0", "-1", "2.5", "200%", "0%"])(    "throws on %s rather than silently ignoring it",    (raw) => {      expect(() => parseWorkerCap(raw)).toThrow(/VITEST_MAX_WORKERS/);    },  );});describe("takeWorkerCap — one rule for every pool and both vitest majors", () => {  it("caps from VITEST_MAX_WORKERS", () => {    expect(takeWorkerCap({ VITEST_MAX_WORKERS: "2" })).toEqual({ maxWorkers: 2, minWorkers: 1 });  });  it.each(["VITEST_MAX_FORKS", "VITEST_MAX_THREADS"])(    "accepts %s as an alias, so a cap meant for one pool still lands",    (name) => {      expect(takeWorkerCap({ [name]: "2" })).toEqual({ maxWorkers: 2, minWorkers: 1 });    },  );  it("prefers VITEST_MAX_WORKERS over the pool-specific aliases", () => {    expect(takeWorkerCap({ VITEST_MAX_WORKERS: "2", VITEST_MAX_FORKS: "8" })).toEqual({      maxWorkers: 2,      minWorkers: 1,    });  });  it("answers an empty object when unset, so config and CI keep today's speed", () => {    expect(takeWorkerCap({})).toEqual({});  });  it("consumes every pool env var it read, so vitest cannot re-apply a conflicting pair", () => {    // The CI runner exports a min/max pair that contradicts itself; vitest reads    // those AFTER the config and they win, and Tinypool then refuses to build a    // pool whose minimum exceeds its maximum. Deleting them is what makes the    // returned numbers the ones that actually apply.    const env: NodeJS.ProcessEnv = {      VITEST_MAX_FORKS: "1",      VITEST_MIN_FORKS: "4",      VITEST_MAX_THREADS: "1",      VITEST_MIN_THREADS: "4",    };    expect(takeWorkerCap(env)).toEqual({ maxWorkers: 1, minWorkers: 1 });    for (const name of WORKER_ENV_VARS) expect(env[name]).toBeUndefined();    expect(env.VITEST_MIN_FORKS).toBeUndefined();    expect(env.VITEST_MIN_THREADS).toBeUndefined();  });  it("never returns a minimum above its maximum, by construction", () => {    const cap = takeWorkerCap({ VITEST_MAX_WORKERS: "1" }) as { maxWorkers: number; minWorkers: number };    expect(cap.minWorkers).toBeLessThanOrEqual(cap.maxWorkers);  });});describe("every package that runs vitest honours the knob", () => {  const packages = testablePackages();  it("finds the workspace's test packages at all", () => {    // The floor is here to catch the sweep finding NOTHING (a glob that    // stopped matching reads as a green run over zero packages), not to pin a    // headcount. There are three packages today: the site, the Mac's    // TypeScript half and the relay.    expect(packages.length).toBeGreaterThan(2);  });  it.each(packages.map((p) => p.dir))("%s has a vitest config of its own", (dir) => {    // Without one, vitest walks UP to the repo root, and a package whose pool    // nobody declared is a package nobody can cap.    const found = packages.find((p) => p.dir === dir);    expect(found?.config).not.toBeNull();  });  it.each(packages.map((p) => p.dir))("%s spreads takeWorkerCap() into its test config", (dir) => {    const found = packages.find((p) => p.dir === dir);    const text = readFileSync(path.join(ROOT, dir, found?.config ?? "vitest.config.ts"), "utf8");    expect(text).toMatch(/vitest\.workers/);    expect(text.replace(/\s+/g, " ")).toMatch(/\.\.\.takeWorkerCap\(\)/);  });});describe("turbo passes the knob through to every package task", () => {  it("names each env var in globalPassThroughEnv", () => {    // turbo.json is JSONC — read it as text rather than parsing it.    const turbo = readFileSync(path.join(ROOT, "turbo.json"), "utf8");    const list = /"globalPassThroughEnv":\s*\[([^\]]*)\]/.exec(turbo)?.[1] ?? "";    for (const name of WORKER_ENV_VARS) {      expect(list).toContain(`"${name}"`);    }  });});// RULE: On the box (Linux) a Worker test gets 30 s, because vitest's 5 s default there measures the box's load, not the code; a Mac keeps the default (15 Nov 2026).describe("boxTestTimeout — 30 s on the box, the default on a Mac", () => {  it("gives Linux 30 s and a Mac nothing of its own", () => {    expect(boxTestTimeout("linux")).toEqual({ testTimeout: 30_000 });    expect(boxTestTimeout("darwin")).toEqual({});  });  it("is spread into the Worker's test config", () => {    const config = readFileSync(path.join(__dirname, "../../apps/business/vitest.config.ts"), "utf8");    expect(config).toContain("...boxTestTimeout(),");  });});