Cotton code
156 lines · 11.1 KB · TypeScriptRaw
import { execFileSync, spawnSync } from "node:child_process";import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { expect, it } from "vitest";import { requires } from "./requires";const wrapper = resolve(__dirname, "../ci/cargo-test-with-one-retry.sh");const helper = resolve(__dirname, "../ci/cargo-test-target-shard.py");const paired = resolve(__dirname, "../ci/cargo-test-paired-shards.py");const plan = (metadata: unknown, n: number) => JSON.parse(execFileSync("python3", ["-B", "-c",  "import importlib.util,json,sys; s=importlib.util.spec_from_file_location('shards',sys.argv[1]); m=importlib.util.module_from_spec(s); s.loader.exec_module(m); print(json.dumps(m.plan(json.load(sys.stdin),'probe',int(sys.argv[2]),4)))",  helper, String(n)], { input: JSON.stringify(metadata), encoding: "utf8" }));// RULE: Restrict compilation, never coverage. All enabled integration targets// have a complete pair of case partitions; units keep the global hash. Unknown// target layouts retain the original Cargo selection rather than omitting it.it("covers discovered targets, default features and unit partitions without a file list", () => {  const target = (name: string, kind: string[], extra = {}) => ({ name, kind, test: true, ...extra });  const pkg = { name: "probe", features: { default: ["host"], host: ["dep:server"] }, targets: [    target("probe", ["staticlib", "rlib"]), target("cli", ["bin"]),    target("not-a-unit-test", ["bin"], { test: false }),    target("one", ["test"]), target("host", ["test"], { "required-features": ["host"] }),  ] };  pkg.targets.push(target("discovered-later", ["test"]));  const plans = [1, 2, 3, 4].map(n => plan({ packages: [pkg] }, n));  for (const [index, phases] of plans.entries()) {    const units = phases.find((args: string[]) => args.includes("--lib"));    expect(new Set(units.slice(0, -2))).toEqual(new Set(["--lib", "--bin", "cli"]));    expect(units.slice(-2)).toEqual(["--partition", `hash:${index + 1}/4`]);  }  for (const name of ["one", "host", "discovered-later"]) {    const parts = plans.flatMap(phases => phases.filter((args: string[]) => args.includes(name))      .map((args: string[]) => args.at(-1)));    expect(parts.sort(), name).toEqual(["hash:1/2", "hash:2/2"]);  }  pkg.targets.push(target("special", ["example"]));  expect(plan({ packages: [pkg] }, 1)).toBeNull();  pkg.targets = [target("future", ["unknown-cargo-kind"], { test: false })];  expect(plan({ packages: [pkg] }, 1)).toBeNull();  pkg.targets = [target("opt-in", ["test"], { "required-features": ["extra"] })];  expect(plan({ packages: [pkg] }, 1)).toBeNull();  pkg.targets = [target("only-integration", ["test"])];  const sparse = [1, 2, 3, 4].map(n => plan({ packages: [pkg] }, n));  expect(sparse).toEqual([null, null, null, null]);  pkg.targets = [];  expect(plan({ packages: [pkg] }, 1)).toBeNull();});it("never mixes partition schemes after a metadata failure and leaves feature suites unchanged", () => {  const root = mkdtempSync(join(tmpdir(), "cotton-target-metadata-"));  try {    const calls = join(root, "calls");    writeFileSync(join(root, "cargo"), '#!/bin/sh\nif [ "$1" = metadata ]; then exit 9; fi\nprintf "%s\\n" "$*" >> "$COTTON_TEST_CALLS"\n', { mode: 0o755 });    const args = ["nextest", "run", "--profile", "fast", "--no-fail-fast", "--partition", "hash:1/4", "-p", "probe"];    const env = { ...process.env, PATH: root + ":" + process.env.PATH,      COTTON_TEST_CALLS: calls, COTTON_PARTITION_BUILD_TARGETS: "1" };    const failed = spawnSync("bash", [wrapper, ...args], { env, encoding: "utf8" });    expect(failed.status).not.toBe(0);    expect(existsSync(calls)).toBe(false);    const featureArgs = [...args, "--no-default-features"];    const legacy = spawnSync("bash", [wrapper, ...featureArgs], { env, encoding: "utf8" });    expect(legacy.status, legacy.stderr).toBe(0);    expect(readFileSync(calls, "utf8").trim()).toBe(featureArgs.join(" "));  } finally { rmSync(root, { recursive: true, force: true }); }});// This executes real Cargo/Nextest: an unassigned broken binary must not be// compiled, then every fast case (including a newly discovered target) runs// once across the shards. The nightly case panics if profile filtering breaks.it("builds only its integration targets while executing the entire fast suite once", (ctx) => {  requires(ctx, { probe: () => spawnSync("cargo", ["nextest", "--version"]).status === 0,    reason: "Cargo Nextest is required for the target-selection execution proof" });  const root = mkdtempSync(join(tmpdir(), "cotton-target-shards-"));  try {    mkdirSync(join(root, "src"));    mkdirSync(join(root, "tests"));    mkdirSync(join(root, ".config"));    const manifest = '[package]\nname="probe"\nversion="0.0.0"\nedition="2021"\n';    writeFileSync(join(root, "Cargo.toml"), manifest + '[features]\ndefault=["host"]\nhost=[]\n[[bin]]\nname="disabled"\npath="extra_bin.rs"\ntest=false\n');    const record = 'fn record(s: &str) { use std::io::Write; let path=std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().join("probe"); let out=std::process::Command::new(path).output().unwrap(); assert!(out.status.success()); assert_eq!(out.stdout,format!("{}\\n",std::env::var("COTTON_TEST_BINARY_MARKER").unwrap()).as_bytes()); let mut f=std::fs::OpenOptions::new().create(true).append(true).open(std::env::var("COTTON_TEST_EXECUTIONS").unwrap()).unwrap(); f.write_all(format!("{s}\\n").as_bytes()).unwrap(); }\n';    const units = Array.from({ length: 64 }, (_, i) => `unit_${i}`);    writeFileSync(join(root, "src/lib.rs"), record + units.map(name => `#[test] fn ${name}(){record("${name}");}`).join("\n") + '\n#[test] fn heavy_nightly(){panic!("nightly must stay excluded");}\n');    writeFileSync(join(root, "src/main.rs"), record + 'fn main(){println!("probe-main");}\n#[test] fn bin_case(){record("bin_case");}\n');    writeFileSync(join(root, "extra_bin.rs"), record + 'fn main(){}\n#[test] fn disabled_case(){record("disabled_case");}\n');    mkdirSync(join(root, "examples"));    writeFileSync(join(root, "examples/demo.rs"), record + 'fn main(){}\n#[test] fn example_case(){record("example_case");}\n');    writeFileSync(join(root, "tests/one.rs"), record + '#[test] fn one_case(){let out=std::process::Command::new(env!("CARGO_BIN_EXE_probe")).output().unwrap();assert!(out.status.success());assert_eq!(out.stdout,format!("{}\\n",std::env::var("COTTON_TEST_BINARY_MARKER").unwrap()).as_bytes());record("one_case");}\n');    writeFileSync(join(root, "tests/poison.rs"), 'compile_error!("an unassigned integration must not compile");\n');    writeFileSync(join(root, ".config/nextest.toml"), '[profile.fast]\ndefault-filter="not test(heavy_nightly)"\n');    const executions = join(root, "executions");    const env = { ...process.env, CARGO_TARGET_DIR: join(root, "target"), CARGO_BUILD_JOBS: "2",      COTTON_PARTITION_BUILD_TARGETS: "1", COTTON_TEST_EXECUTIONS: executions, COTTON_TEST_BINARY_MARKER: "probe-main", NEXTEST_TEST_THREADS: "2" };    const run = (part: number, expected = 0, selected = true, total = 4) => {      const out = spawnSync("bash", [wrapper, "nextest", "run", "--profile", "fast", "--no-fail-fast", "--partition", `hash:${part}/${total}`, "-p", "probe"],        { cwd: root, env: { ...env, COTTON_PARTITION_BUILD_TARGETS: selected ? "1" : "0" }, encoding: "utf8" });      expect(out.status, out.stdout + out.stderr).toBe(expected);    };    // The second integration target belongs to the other pair of jobs.    run(1);    writeFileSync(executions, "");    writeFileSync(join(root, "tests/poison.rs"), record + '#[test] fn poison_case(){record("poison_case");}\n');    writeFileSync(join(root, "tests/later.rs"), record + '#[test] fn later_case(){record("later_case");}\n');    writeFileSync(join(root, "tests/host_case.rs"), record + '#[test] fn host_case(){record("host_case");}\n');    writeFileSync(join(root, "Cargo.toml"), readFileSync(join(root, "Cargo.toml"), "utf8") + '[[test]]\nname="host_case"\nrequired-features=["host"]\n');    run(1, 0, false, 1);    const baseline = readFileSync(executions, "utf8").trim().split("\n").sort();    expect(baseline).toEqual([...units, "bin_case", "one_case", "poison_case", "later_case", "host_case"].sort());    writeFileSync(executions, "");    // A unit must observe the freshly rebuilt real executable, not the old    // baseline binary already present in the warm target.    writeFileSync(join(root, "src/main.rs"), readFileSync(join(root, "src/main.rs"), "utf8").replace('println!("probe-main")', 'println!("probe-main-new")'));    env.COTTON_TEST_BINARY_MARKER = "probe-main-new";    let failedPhaseOwner = 0;    for (const part of [1, 2, 3, 4]) {      run(part);      if (!failedPhaseOwner && readFileSync(executions, "utf8").split("\n").includes("poison_case")) failedPhaseOwner = part;    }    expect(readFileSync(executions, "utf8").trim().split("\n").sort())      .toEqual(baseline);    // Two sibling case partitions may share one compile lease. Their entire    // fast inventory must still match the original unpartitioned execution.    writeFileSync(executions, "");    for (const part of [1, 2]) {      const out = spawnSync("python3", [paired, "nextest", "run", "--profile", "fast", "--no-fail-fast", "--partition", `hash:${part}/2`, "-p", "probe"],        { cwd: root, env, encoding: "utf8" });      expect(out.status, out.stdout + out.stderr).toBe(0);    }    expect(readFileSync(executions, "utf8").trim().split("\n").sort()).toEqual(baseline);    // A failed integration remains red even when the following unit phase    // passes, and the retry wrapper never executes the failed test again.    writeFileSync(join(root, "tests/poison.rs"), record + '#[test] fn poison_case(){record("poison_case");panic!("synthetic real failure");}\n');    writeFileSync(executions, "");    run(failedPhaseOwner, 100);    expect(readFileSync(executions, "utf8").split("\n").filter(name => name === "poison_case"))      .toEqual(["poison_case"]);    // Cargo's original default selection also builds non-test examples.    // Restricting test targets must retain that compilation check.    writeFileSync(join(root, "tests/poison.rs"), record + '#[test] fn poison_case(){record("poison_case");}\n');    writeFileSync(join(root, "examples/demo.rs"), 'compile_error!("non-test examples must still compile"); fn main(){}\n');    run(1, 101);    // Target selection must not turn an entirely empty fast suite green.    rmSync(join(root, "tests"), { recursive: true });    mkdirSync(join(root, "tests"));    for (const name of ["night_one", "night_two"]) {      writeFileSync(join(root, `tests/${name}.rs`), '#[test] fn heavy_nightly(){}\n');    }    rmSync(join(root, "src/main.rs"));    rmSync(join(root, "examples"), { recursive: true });    mkdirSync(join(root, "examples"));    writeFileSync(join(root, "examples/demo.rs"), 'fn main(){}\n');    writeFileSync(join(root, "Cargo.toml"), manifest);    writeFileSync(join(root, "src/lib.rs"), '#[test] fn heavy_nightly(){}\n');    run(1, 4);  } finally { rmSync(root, { recursive: true, force: true }); }});