diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b2bbebd5c..53a9be4e4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,19 +9,23 @@ on: branches: [main] schedule: - cron: "37 3 * * *" + # `labeled` so adding the `full-ci` label starts a run of all six shards. pull_request: + types: [opened, synchronize, reopened, labeled] workflow_dispatch: permissions: contents: read -# A newer push to a PR branch cancels its older run; every push to main runs to the end. +# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding +# any label other than `full-ci` gets a group of its own, so it never cancels a real run. concurrency: - group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: gate: + if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7e9f7787ff..40f38d85f2 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -276,23 +276,21 @@ fn has_nextest() -> bool { /// The workspace's unit and integration tests, without examples (clippy still checks those). /// nextest runs each test in its own process, in parallel across all test binaries. fn cmd_test() -> Result<(), String> { - test_packages(&["--workspace".to_owned()], "--workspace", None) + test_packages(&["--workspace".to_owned()], "--workspace", shards::Targets::All, None) } -/// The test targets that [`test_packages`] runs and `ci warm` builds. -const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; - -/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; -/// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. -/// A part runs its counted share, then its pinned tests, each with nextest's default thread count. -/// Every run finishes before the first error is returned. -fn test_packages(select: &[String], shown: &str, part: Option) -> Result<(), String> { +/// [`cmd_test`] for the `targets` of the packages `select` picks (`--workspace` or `-p` ids), +/// shown as `shown`; with `part`, only that part's share of their tests (xtask/src/shards.rs), +/// which needs nextest. A part runs its counted share, then its pinned tests, each with +/// nextest's default thread count. Every run finishes before the first error is returned. +fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option) -> Result<(), String> { + let (listed, targets) = (targets.shown(), targets.args()); if let Some(part) = part { if !has_nextest() { return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); } let mut c = cargo(); - c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(TARGETS); + c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets); let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; if !out.status.success() { return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); @@ -306,9 +304,9 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let command = |args: Vec| { let mut c = cargo(); - c.args(["nextest", "run"]).args(select).args(TARGETS).args(&args); + c.args(["nextest", "run"]).args(select).args(targets).args(&args); let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::>().join(" "); - (c, format!("cargo nextest run {shown} --lib --bins --tests {quoted}")) + (c, format!("cargo nextest run {shown} {listed} {quoted}")) }; let mut result = Ok(()); for args in part.runs() { @@ -319,12 +317,12 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> } let mut c = cargo(); if has_nextest() { - c.args(["nextest", "run"]).args(select).args(TARGETS); - run(c, &format!("cargo nextest run {shown} --lib --bins --tests")) + c.args(["nextest", "run"]).args(select).args(targets); + run(c, &format!("cargo nextest run {shown} {listed}")) } else { eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)"); - c.arg("test").args(select).args(TARGETS); - run(c, &format!("cargo test {shown} --lib --bins --tests")) + c.arg("test").args(select).args(targets); + run(c, &format!("cargo test {shown} {listed}")) } } @@ -380,22 +378,33 @@ fn cmd_ci_shard() -> Result<(), String> { let checked = shards::run()?; let mut steps: Vec = Vec::new(); match &checked[shard - 1] { - shards::Shard::Tests(crates, part) => { - let names = shards::names(crates); + shards::Shard::Tests(runs, part) => { let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); - eprintln!("ci shard {shard}/{count}: the tests of {names}{share}"); - let select = shards::select(crates); - let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); + eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs)); + let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); let part = *part; - let (s, w) = (select.clone(), shown.clone()); - steps.push(("test", Box::new(move || test_packages(&s, &w, part)))); + let tests: Vec<(Vec, String, shards::Targets)> = + runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect(); + // Each run finishes before the first error is returned. + steps.push(( + "test", + Box::new(move || { + let mut result = Ok(()); + for (s, w, t) in &tests { + result = result.and(test_packages(s, w, *t, part)); + } + result + }), + )); // The doctests and the i18n report run once, on a split's first part. let first = part.is_none_or(|p| p.is_first()); if first { - let c = crates.clone(); + let c = shards::unit_crates(runs); steps.push(("doctests", Box::new(move || doctest_packages(&c)))); } - if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { + let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")); + if let Some(r) = all.filter(|_| first) { + let (select, shown) = (shards::select(&r.crates), shown(&r.crates)); steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); } } @@ -407,13 +416,11 @@ fn cmd_ci_shard() -> Result<(), String> { run_steps(&steps) } -/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration -/// tests without running them, then builds what the checks shard builds, so one dependency-cache -/// entry holds the dependencies of every shard with the features that shard builds them with (cargo -/// resolves features over the packages each command selects). The test builds select the same -/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the -/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that -/// only an integration test uses. +/// `cargo xtask ci warm`: for each run of each test shard, builds the test targets it runs without +/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the +/// dependencies of every shard with the features that shard builds them with (cargo resolves +/// features over the packages each command selects). The test builds select the same crates and +/// targets as the test shards' runs, so the cache also holds the test executables the shards run. /// /// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that /// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build @@ -434,14 +441,16 @@ fn cmd_ci_warm() -> Result<(), String> { let (tests, checks) = shards::warm_plan(&checked, only); let mut steps: Vec = Vec::new(); for i in tests { - if let shards::Shard::Tests(crates, _) = checked[i].clone() { - steps.push(( - "build tests", - Box::new(move || { - let (c, what) = warm_tests(&crates); - cache_units::run(c, &what) - }), - )); + if let shards::Shard::Tests(runs, _) = checked[i].clone() { + for r in runs { + steps.push(( + "build tests", + Box::new(move || { + let (c, what) = warm_tests(&r); + cache_units::run(c, &what) + }), + )); + } } } if checks { @@ -477,11 +486,11 @@ fn push_warm_checks(steps: &mut Vec) { steps.push(("wasm", Box::new(cmd_wasm))); } -/// The command `ci warm` builds one test shard's tests with, and its description. -fn warm_tests(crates: &[shards::Member]) -> (Command, String) { +/// The command `ci warm` builds the tests of one run of a test shard with, and its description. +fn warm_tests(r: &shards::Run) -> (Command, String) { let mut c = cargo(); - c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run"); - (c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates))) + c.arg("test").args(shards::select(&r.crates)).args(r.targets.args()).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", r.targets.shown(), shards::names(&r.crates))) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed @@ -634,13 +643,14 @@ mod tests { #[test] fn warm_builds_the_test_targets_the_shards_run() { - let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }]; - let (c, what) = warm_tests(&crates); - let args: Vec = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); - assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); - for target in TARGETS { - assert!(args.iter().any(|a| a == target), "ci warm does not build {target}"); - } - assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)"); + let a = shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }; + let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let all = shards::Run::all(vec![a.clone()]); + assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); + assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --tests --no-run (a)"); + let units = shards::Run { targets: shards::Targets::Units, crates: vec![a.clone()] }; + assert_eq!(args(&units), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]); + let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![a] }; + assert_eq!(args(&integration), ["test", "-p", "path+file:///w/a#0.1.0", "--test", "*", "--no-run"]); } } diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index f28a881fd4..009256ccd4 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -17,6 +17,11 @@ //! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n //! report run on part 1. A part runs its counted share and then its pinned tests, each with //! nextest's default thread count, and runs both even when the first fails. +//! +//! A [`Group::Targets`] shard can run a crate's library and binary tests ([`Targets::Units`]) while +//! another shard runs its integration tests ([`Targets::Integration`]), so a shard that already +//! builds that crate's library takes those tests without building the library's test harness. Each +//! list of a shard is its own cargo command, and its doctests run with its library tests. use std::collections::{BTreeMap, BTreeSet}; @@ -25,16 +30,49 @@ use serde_json::Value; /// What one shard runs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { - /// The tests of these workspace crates (package names). - Crates(&'static [&'static str]), /// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards. Part(&'static Split, usize), + /// The given test targets of each list of workspace crates (package names). A crate whose + /// [`Targets::Units`] run on one shard has its [`Targets::Integration`] run on another. + Targets(&'static [(Targets, &'static [&'static str])]), /// The tests of every workspace member no other group names. Rest, /// The `cargo xtask ci` steps that are not tests. Checks, } +/// The test targets a shard builds and runs for a crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Targets { + /// The library, binary and integration tests. + All, + /// The library and binary tests. + Units, + /// The integration tests (`tests/`). + Integration, +} + +impl Targets { + /// The target selection `cargo test` and `cargo nextest run` take. + pub fn args(self) -> &'static [&'static str] { + match self { + Targets::All => &["--lib", "--bins", "--tests"], + Targets::Units => &["--lib", "--bins"], + // `--tests` would also take the library's and binaries' test harnesses (every target with `test = true`). + Targets::Integration => &["--test", "*"], + } + } + + /// [`Targets::args`] as a shell would take them, for messages. + pub fn shown(self) -> &'static str { + match self { + Targets::All => "--lib --bins --tests", + Targets::Units => "--lib --bins", + Targets::Integration => "--test '*'", + } + } +} + /// Crates whose tests run on several shards, one [`Group::Part`] each. #[derive(Debug, PartialEq, Eq)] pub struct Split { @@ -71,12 +109,16 @@ pub static UI_EGUI: Split = Split { }; /// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its -/// `shard-members` names each shard's crates. +/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on +/// shard 4, which already builds the engine library for the app crates. pub const GROUPS: &[Group] = &[ Group::Part(&UI_EGUI, 1), Group::Part(&UI_EGUI, 2), - Group::Crates(&["vectorcraft-engine"]), - Group::Crates(&["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]), + Group::Targets(&[ + (Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), + (Targets::Integration, &["vectorcraft-engine"]), + ]), Group::Rest, Group::Checks, ]; @@ -98,10 +140,29 @@ pub struct Member { /// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Shard { - Tests(Vec, Option), + Tests(Vec, Option), Checks, } +/// One test run of a shard: the given targets of these crates. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Run { + pub targets: Targets, + pub crates: Vec, +} + +impl Run { + /// A run of every test target of `crates`. + pub fn all(crates: Vec) -> Run { + Run { targets: Targets::All, crates } + } +} + +/// The crates of `runs` whose library is tested there, which run their doctests on that shard. +pub fn unit_crates(runs: &[Run]) -> Vec { + runs.iter().filter(|r| r.targets != Targets::Integration).flat_map(|r| r.crates.iter().cloned()).collect() +} + /// Part `index` (1-based) of `split`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Part { @@ -192,14 +253,15 @@ pub fn with_doctests(crates: &[Member]) -> Vec { } /// Each group of `groups` with its crates: a named crate must be a workspace member and named -/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's -/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice. +/// once, or with its [`Targets::Units`] on one shard and its [`Targets::Integration`] on another; +/// there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's parts 1 +/// to n must be consecutive shards, with at least two parts, and no test pinned twice. pub fn assign(groups: &[Group], members: &[Member]) -> Result, String> { const WHERE: &str = "xtask/src/shards.rs › GROUPS"; - let mut named: BTreeMap<&str, usize> = BTreeMap::new(); + let mut named: BTreeMap<&str, Vec<(usize, Targets)>> = BTreeMap::new(); for (i, g) in groups.iter().enumerate() { - let names = match g { - Group::Crates(names) => *names, + let lists: Vec<(Targets, &[&str])> = match g { + Group::Targets(lists) => lists.to_vec(), Group::Part(split, k) => { let n = split.parts(); if n < 2 { @@ -222,22 +284,39 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1)); } } - split.crates + vec![(Targets::All, split.crates)] } Group::Rest | Group::Checks => continue, }; - if names.is_empty() { + if lists.iter().all(|(_, names)| names.is_empty()) { return Err(format!("shard {} names no crates ({WHERE})", i + 1)); } - for name in names { - if !members.iter().any(|m| m.name == *name) { - return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); - } - if let Some(first) = named.insert(name, i) { - return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)); + for (targets, names) in lists { + for name in names { + if !members.iter().any(|m| m.name == *name) { + return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); + } + let entries = named.entry(name).or_default(); + // The one allowed second entry: the other half of a crate split into units and integration tests. + let halves = + |a: Targets, b: Targets| matches!((a, b), (Targets::Units, Targets::Integration) | (Targets::Integration, Targets::Units)); + match entries.as_slice() { + [] => {} + [(first, t)] if halves(*t, targets) && *first != i => {} + [(first, _), ..] => return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)), + } + entries.push((i, targets)); } } } + for (name, entries) in &named { + if let [(i, t)] = entries.as_slice() + && *t != Targets::All + { + let other = if *t == Targets::Units { "integration" } else { "library and binary" }; + return Err(format!("shard {} runs part of `{name}`'s tests, and no shard runs its {other} tests ({WHERE})", i + 1)); + } + } let rests = groups.iter().filter(|g| **g == Group::Rest).count(); if rests != 1 { return Err(format!("{rests} shards take the remaining crates, not 1 ({WHERE})")); @@ -247,14 +326,23 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String .iter() .enumerate() .map(|(i, g)| match g { - Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())), None)), - Group::Part(split, index) => Ok(Shard::Tests(pick(&|m| split.crates.contains(&m.name.as_str())), Some(Part { split, index: *index }))), + Group::Targets(lists) => Ok(Shard::Tests( + lists + .iter() + .filter(|(_, names)| !names.is_empty()) + .map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) }) + .collect(), + None, + )), + Group::Part(split, index) => { + Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index }))) + } Group::Rest => { let rest = pick(&|m| !named.contains_key(m.name.as_str())); if rest.is_empty() { return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1)); } - Ok(Shard::Tests(rest, None)) + Ok(Shard::Tests(vec![Run::all(rest)], None)) } Group::Checks => Ok(Shard::Checks), }) @@ -325,6 +413,17 @@ pub fn names(crates: &[Member]) -> String { crates.iter().map(|m| m.name.as_str()).collect::>().join(", ") } +/// The crates of `runs` for messages, each run's targets after its crates unless it runs all of them. +pub fn describe(runs: &[Run]) -> String { + runs.iter() + .map(|r| match r.targets { + Targets::All => names(&r.crates), + t => format!("{} ({})", names(&r.crates), t.shown()), + }) + .collect::>() + .join(", ") +} + /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result, String> { let members = members(&crate::metadata()?)?; @@ -332,9 +431,12 @@ pub fn check() -> Result, String> { let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); let mut differences = Vec::new(); for (i, shard) in shards.iter().enumerate() { - if let Shard::Tests(crates, _) = shard { - let alone = tree_features(&tree(&select(crates))?, &members); - differences.extend(feature_differences(i + 1, crates, &workspace, &alone)); + // Each run is its own cargo command, so cargo resolves features over that run's crates. + if let Shard::Tests(runs, _) = shard { + for r in runs { + let alone = tree_features(&tree(&select(&r.crates))?, &members); + differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone)); + } } } if !differences.is_empty() { @@ -354,9 +456,9 @@ pub fn run() -> Result, String> { let shards = check()?; for (i, shard) in shards.iter().enumerate() { match shard { - Shard::Tests(crates, part) => { + Shard::Tests(runs, part) => { let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); - println!("shard {}/{}: tests of {} crate(s): {}{share}", i + 1, shards.len(), crates.len(), names(crates)) + println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs)) } Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()), } @@ -441,7 +543,7 @@ mod tests { // builds nothing), and the legs together, like a full warm, build every crate's tests // once and the checks. let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap(); - let mut owned: Vec<&str> = real.iter().flat_map(owners).collect(); + let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect(); owned.sort_unstable(); let (mut legs, mut leg_checks) = (Vec::new(), 0); for i in 0..GROUPS.len() { @@ -489,17 +591,18 @@ mod tests { fn crates(shard: &Shard) -> Vec<&str> { match shard { - Shard::Tests(c, _) => c.iter().map(|m| m.name.as_str()).collect(), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(), Shard::Checks => Vec::new(), } } - /// The crates of each shard that runs a crate's tests from the start: a part after the first + /// Each crate a shard tests from the start, with the targets it runs: a part after the first /// runs a share of the same tests, so it is counted with part 1. - fn owners(shard: &Shard) -> Vec<&str> { + fn owners(shard: &Shard) -> Vec<(&str, Targets)> { match shard { Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(), - _ => crates(shard), + Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(), + Shard::Checks => Vec::new(), } } @@ -548,12 +651,12 @@ mod tests { let ws = [m("a"), m("b")]; let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]); - assert_eq!(shards[1], Shard::Tests(vec![m("a")], Some(Part { split: &SPLIT, index: 2 }))); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 }))); let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err(); assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}"); let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err(); assert!(missing.contains("shard 1 is part 2"), "{missing}"); - let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}"); const ONE: Split = Split { crates: &["a"], pinned: &[&[]] }; assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more")); @@ -616,26 +719,61 @@ mod tests { #[test] fn the_rest_shard_takes_every_crate_no_group_names() { let ws = [m("a"), m("b"), m("c"), m("d")]; - let shards = assign(&[Group::Crates(&["c"]), Group::Rest, Group::Checks], &ws).unwrap(); + let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap(); assert_eq!(shards.iter().map(crates).collect::>(), [vec!["c"], vec!["a", "b", "d"], vec![]]); assert_eq!(shards[2], Shard::Checks); } + /// Every test target of `a`. + const ALL_A: Group = Group::Targets(&[(Targets::All, &["a"])]); + const UNITS: (Targets, &[&str]) = (Targets::Units, &["a"]); + const INTEGRATION: (Targets, &[&str]) = (Targets::Integration, &["a"]); + + #[test] + fn a_crate_s_units_and_integration_tests_run_on_two_shards() { + let ws = [m("a"), m("b"), m("c")]; + let shards = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None)); + assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None)); + assert_eq!(crates(&shards[2]), ["c"]); + assert_eq!( + unit_crates(match &shards[1] { + Shard::Tests(r, _) => r, + Shard::Checks => panic!("shard 2 is a test shard"), + }), + [m("b")] + ); + let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(half.contains("no shard runs its integration tests"), "{half}"); + let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(other_half.contains("no shard runs its library and binary tests"), "{other_half}"); + let with_all = assign(&[ALL_A, Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(with_all.contains("`a` is in shard 1 and shard 2"), "{with_all}"); + let same_shard = assign(&[Group::Targets(&[UNITS, INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(same_shard.contains("`a` is in shard 1 and shard 1"), "{same_shard}"); + let units_twice = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); + assert!(units_twice.contains("`a` is in shard 1 and shard 2"), "{units_twice}"); + let third = + assign(&[Group::Targets(&[UNITS]), Group::Targets(&[INTEGRATION]), Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); + assert!(third.contains("`a` is in shard 1 and shard 3"), "{third}"); + } + #[test] fn a_crate_named_twice_or_unknown_fails() { let ws = [m("a"), m("b")]; - let twice = assign(&[Group::Crates(&["a"]), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + let twice = assign(&[ALL_A, ALL_A, Group::Rest], &ws).unwrap_err(); assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}"); - let unknown = assign(&[Group::Crates(&["z"]), Group::Rest], &ws).unwrap_err(); + let unknown = assign(&[Group::Targets(&[(Targets::All, &["z"])]), Group::Rest], &ws).unwrap_err(); assert!(unknown.contains("`z`, which is not a workspace member"), "{unknown}"); } #[test] fn empty_groups_and_a_missing_or_second_rest_fail() { let ws = [m("a"), m("b")]; - assert!(assign(&[Group::Crates(&[]), Group::Rest], &ws).unwrap_err().contains("names no crates")); - assert!(assign(&[Group::Crates(&["a", "b"]), Group::Rest], &ws).unwrap_err().contains("there are none")); - assert!(assign(&[Group::Crates(&["a"])], &ws).unwrap_err().contains("0 shards take the remaining crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &[])]), Group::Rest], &ws).unwrap_err().contains("names no crates")); + assert!(assign(&[Group::Targets(&[(Targets::All, &["a", "b"])]), Group::Rest], &ws).unwrap_err().contains("there are none")); + assert!(assign(&[ALL_A], &ws).unwrap_err().contains("0 shards take the remaining crates")); assert!(assign(&[Group::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates")); } @@ -643,11 +781,22 @@ mod tests { fn every_workspace_member_is_tested_on_exactly_one_shard() { let ws = members(&crate::metadata().unwrap()).unwrap(); let shards = assign(GROUPS, &ws).unwrap(); - let mut tested: Vec<&str> = shards.iter().flat_map(owners).collect(); - tested.sort_unstable(); + let mut tested: BTreeMap<&str, Vec> = BTreeMap::new(); + for (name, targets) in shards.iter().flat_map(owners) { + tested.entry(name).or_default().push(targets); + } + for targets in tested.values_mut() { + targets.sort_unstable(); + } let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect(); all.sort_unstable(); - assert_eq!(tested, all); + assert_eq!(tested.keys().copied().collect::>(), all); + for (name, targets) in &tested { + assert!( + *targets == [Targets::All] || *targets == [Targets::Units, Targets::Integration], + "`{name}` runs {targets:?}, not each test target once" + ); + } assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1); } @@ -699,13 +848,44 @@ geom v0.1.0 (/w/geom)| let expected: Vec = GROUPS .iter() .map(|g| match g { - Group::Crates(crates) => crates.join(" "), Group::Part(split, _) => split.crates.join(" "), + // The selection names each crate on one line only, so a shard that runs a crate's + // integration tests leaves it off its line and relies on a crate there that + // depends on it (checked below). + Group::Targets(lists) => { + lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::>().join(" ") + } Group::Rest => "(rest)".to_owned(), Group::Checks => "(always)".to_owned(), }) .collect(); assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + let meta = crate::metadata().unwrap(); + let deps: BTreeMap<&str, Vec<&str>> = meta["packages"] + .as_array() + .unwrap() + .iter() + .map(|p| (p["name"].as_str().unwrap(), p["dependencies"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect())) + .collect(); + let reaches = |from: &str, to: &str| { + let (mut seen, mut stack) = (BTreeSet::new(), vec![from]); + while let Some(c) = stack.pop() { + if c == to { + return true; + } + if seen.insert(c) { + stack.extend(deps.get(c).into_iter().flatten().copied()); + } + } + false + }; + for g in GROUPS { + let Group::Targets(lists) = g else { continue }; + let named: Vec<&str> = lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect(); + for crate_ in lists.iter().filter(|(t, _)| *t == Targets::Integration).flat_map(|(_, c)| c.iter().copied()) { + assert!(named.iter().any(|n| reaches(n, crate_)), "no crate on the shard of `{crate_}`'s integration tests depends on it"); + } + } assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]); assert!(shard_members("test-shards: 6\n").is_empty()); }