mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
- apps/vectorcraft-web: egui_extras moves to the wasm32 dependencies. Its only use is src/web.rs, which builds only for wasm32, so cargo reported it unused on native builds. - apps/vectorcraft: drop the socket2 dev-dependency. Its loopback tests left control_server in #8800 and nothing uses it now. - xtask: the doc-test steps (`cargo xtask ci shard` and the workspace doctests) leave out packages whose only library target is a cdylib, dylib or staticlib. Cargo printed "doc tests are not supported for crate type(s) `cdylib`" for vectorcraft-thumbnail-handler. Packages without a library stay selected, so the shard keeps its features. Warnings on the build host, before and after (cache warm shard `cargo test -p vectorcraft-mcp -p vectorcraft -p vectorcraft-cli -p vectorcraft-web -p xtask --lib --bins --no-run` on a fresh build, and `cargo test -p vectorcraft-thumbnail-handler --doc`): 4 before, 1 after. The one left is `vectorcraft-testkit` in apps/vectorcraft-cli: only the integration tests use it, and the warm step builds only library and binary tests.
590 lines
28 KiB
Rust
590 lines
28 KiB
Rust
//! The gate's shards (`cargo xtask ci shard`, with `GATE_SHARD` of `GATE_SHARDS` set by the shared
|
||
//! gate workflow): which workspace crates each shard tests, and the checks that keep the split
|
||
//! complete.
|
||
//!
|
||
//! Each test shard builds and runs the tests of its own crates and what they depend on. The last
|
||
//! shard runs the `cargo xtask ci` steps that are not tests. [`GROUPS`] names the crates of the
|
||
//! first shards; every other workspace member goes to the [`Group::Rest`] shard, so a new crate is
|
||
//! tested without a change here. [`check`] fails when a named crate is not a workspace member or
|
||
//! is named twice, when a group is empty, and when a crate's features in its shard differ from
|
||
//! its features in `cargo test --workspace`. Cargo resolves features over the packages a command
|
||
//! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard
|
||
//! without that crate, and the tests behind it do not build.
|
||
//!
|
||
//! A [`Split`] runs the tests of its crates on several shards in a row ([`Group::Part`]). Each
|
||
//! part builds the same tests and runs its share of them: the tests its `pinned` list names, and
|
||
//! every other test of the crates by nextest's counted partition (`--partition count:<k>/<n>`
|
||
//! 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.
|
||
|
||
use std::collections::{BTreeMap, BTreeSet};
|
||
|
||
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 tests of every workspace member no other group names.
|
||
Rest,
|
||
/// The `cargo xtask ci` steps that are not tests.
|
||
Checks,
|
||
}
|
||
|
||
/// Crates whose tests run on several shards, one [`Group::Part`] each.
|
||
#[derive(Debug, PartialEq, Eq)]
|
||
pub struct Split {
|
||
/// The workspace crates (package names).
|
||
pub crates: &'static [&'static str],
|
||
/// For each part, the full names of the tests it runs outside the counted partition (the
|
||
/// slowest ones, spread so that no part waits on all of them). Its length is the part count.
|
||
pub pinned: &'static [&'static [&'static str]],
|
||
}
|
||
|
||
impl Split {
|
||
/// How many shards the split runs on.
|
||
pub fn parts(&self) -> usize {
|
||
self.pinned.len()
|
||
}
|
||
}
|
||
|
||
/// vectorcraft-ui-egui's tests, on two shards. The pinned tests took 18 to 44 s each in CI
|
||
/// run 46267439238.
|
||
pub static UI_EGUI: Split = Split {
|
||
crates: &["vectorcraft-ui-egui"],
|
||
pinned: &[
|
||
&[
|
||
"panels::actions::tests_edits::every_listed_menu_item_runs_from_the_menu_what_its_step_holds",
|
||
"dialogs::revolve::tests::a_3d_row_sets_its_param_previews_and_applies_in_one_step",
|
||
"shortcuts::tests::alt_chords_type_special_characters_while_editing_text",
|
||
"menus::tests::help_f1_opens_discover_without_a_document",
|
||
],
|
||
&[
|
||
"palette::tests::the_palette_leaves_out_the_commands_a_pick_cannot_run",
|
||
"chrome::tests::the_control_bar_leaves_members_out_in_its_priority_order",
|
||
],
|
||
],
|
||
};
|
||
|
||
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length.
|
||
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::Rest,
|
||
Group::Checks,
|
||
];
|
||
|
||
/// A workspace member, as `cargo metadata` gives it.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub struct Member {
|
||
pub name: String,
|
||
/// The package id, which `-p` takes where the name would be ambiguous: craft-libs builds
|
||
/// against this repo's geom and pathops by git, so the graph holds a second copy of each.
|
||
pub id: String,
|
||
pub version: String,
|
||
/// Whether `cargo test --doc` can select this package without a warning: it has no library
|
||
/// target, or one of `lib`, `rlib` or `proc-macro` kind. Cargo warns for a selected package
|
||
/// whose library is only a `cdylib`, `dylib` or `staticlib`.
|
||
pub doctests: bool,
|
||
}
|
||
|
||
/// 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<Member>, Option<Part>),
|
||
Checks,
|
||
}
|
||
|
||
/// Part `index` (1-based) of `split`.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct Part {
|
||
pub split: &'static Split,
|
||
pub index: usize,
|
||
}
|
||
|
||
impl Part {
|
||
/// The arguments `cargo nextest run` takes after the package and target selection, once for
|
||
/// each run this part makes: the counted share (`--partition count:<k>/<n>`, with every
|
||
/// pinned test filtered out when the split pins any), then the tests this part pins.
|
||
/// The counted run passes `--no-tests=pass`. The pinned run keeps nextest's default and
|
||
/// fails when no tests match.
|
||
pub fn runs(&self) -> Vec<Vec<String>> {
|
||
let all: Vec<&str> = self.split.pinned.iter().flat_map(|p| p.iter().copied()).collect();
|
||
let mut counted = vec!["--partition".to_owned(), format!("count:{}/{}", self.index, self.split.parts()), "--no-tests=pass".to_owned()];
|
||
if !all.is_empty() {
|
||
counted.extend(["-E".to_owned(), format!("not ({})", exact(&all))]);
|
||
}
|
||
let mut runs = vec![counted];
|
||
let own = self.split.pinned[self.index - 1];
|
||
if !own.is_empty() {
|
||
runs.push(vec!["-E".to_owned(), exact(own)]);
|
||
}
|
||
runs
|
||
}
|
||
|
||
/// The tests this part pins whose full names are absent from
|
||
/// `cargo nextest list --message-format json` output. Invalid listings return an error.
|
||
pub fn missing_pins(&self, list: &str) -> Result<Vec<&'static str>, String> {
|
||
let list: Value = serde_json::from_str(list).map_err(|e| format!("invalid JSON listing: {e}"))?;
|
||
let suites = list.get("rust-suites").and_then(Value::as_object).ok_or("JSON listing has no `rust-suites` map")?;
|
||
let mut listed = BTreeSet::new();
|
||
for (binary, suite) in suites {
|
||
let tests =
|
||
suite.get("testcases").and_then(Value::as_object).ok_or_else(|| format!("JSON listing has no `testcases` map for `{binary}`"))?;
|
||
listed.extend(tests.keys().map(String::as_str));
|
||
}
|
||
Ok(self.split.pinned[self.index - 1].iter().copied().filter(|p| !listed.contains(p)).collect())
|
||
}
|
||
|
||
/// Whether this part runs the doctests and the i18n report.
|
||
pub fn is_first(&self) -> bool {
|
||
self.index == 1
|
||
}
|
||
}
|
||
|
||
/// A filterset that matches each of `names` exactly.
|
||
fn exact(names: &[&str]) -> String {
|
||
names.iter().map(|n| format!("test(={n})")).collect::<Vec<_>>().join(" | ")
|
||
}
|
||
|
||
/// The workspace members of `cargo metadata --no-deps` output, in its order.
|
||
pub fn members(meta: &Value) -> Result<Vec<Member>, String> {
|
||
let ids: BTreeSet<&str> = meta["workspace_members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||
let members: Vec<Member> = meta["packages"]
|
||
.as_array()
|
||
.into_iter()
|
||
.flatten()
|
||
.filter(|p| p["id"].as_str().is_some_and(|id| ids.contains(id)))
|
||
.map(|p| {
|
||
let field = |key: &str| p[key].as_str().map(str::to_owned).ok_or_else(|| format!("cargo metadata: a workspace package has no `{key}`"));
|
||
Ok(Member { name: field("name")?, id: field("id")?, version: field("version")?, doctests: has_doctests(p) })
|
||
})
|
||
.collect::<Result<_, String>>()?;
|
||
if members.is_empty() {
|
||
return Err("cargo metadata lists no workspace members".into());
|
||
}
|
||
Ok(members)
|
||
}
|
||
|
||
/// [`Member::doctests`] for the `cargo metadata` package `p`.
|
||
fn has_doctests(p: &Value) -> bool {
|
||
let kinds = |t: &Value| t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>();
|
||
let libraries: Vec<Vec<String>> = p["targets"]
|
||
.as_array()
|
||
.into_iter()
|
||
.flatten()
|
||
.map(kinds)
|
||
.filter(|k| k.iter().any(|k| matches!(k.as_str(), "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro")))
|
||
.collect();
|
||
libraries.is_empty() || libraries.iter().flatten().any(|k| matches!(k.as_str(), "lib" | "rlib" | "proc-macro"))
|
||
}
|
||
|
||
/// The crates of `crates` that `cargo test --doc` can select (see [`Member::doctests`]).
|
||
pub fn with_doctests(crates: &[Member]) -> Vec<Member> {
|
||
crates.iter().filter(|m| m.doctests).cloned().collect()
|
||
}
|
||
|
||
/// 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.
|
||
pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String> {
|
||
const WHERE: &str = "xtask/src/shards.rs › GROUPS";
|
||
let mut named: BTreeMap<&str, usize> = BTreeMap::new();
|
||
for (i, g) in groups.iter().enumerate() {
|
||
let names = match g {
|
||
Group::Crates(names) => *names,
|
||
Group::Part(split, k) => {
|
||
let n = split.parts();
|
||
if n < 2 {
|
||
return Err(format!("shard {} is a part of a split with {n} part(s), not 2 or more ({WHERE})", i + 1));
|
||
}
|
||
// Part 1 of the split is shard `first` (0-based) when this shard is part k.
|
||
let in_order = (1..=n).contains(k)
|
||
&& (i + 1).checked_sub(*k).is_some_and(|first| {
|
||
(1..=n).all(|p| matches!(groups.get(first + p - 1), Some(Group::Part(s, q)) if *s == *split && *q == p))
|
||
});
|
||
if !in_order {
|
||
return Err(format!("shard {} is part {k} of a split whose {n} parts are not shards 1 to {n} in a row ({WHERE})", i + 1));
|
||
}
|
||
if *k > 1 {
|
||
continue;
|
||
}
|
||
let mut pinned = BTreeSet::new();
|
||
for name in split.pinned.iter().flat_map(|p| p.iter()) {
|
||
if !pinned.insert(*name) {
|
||
return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1));
|
||
}
|
||
}
|
||
split.crates
|
||
}
|
||
Group::Rest | Group::Checks => continue,
|
||
};
|
||
if 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));
|
||
}
|
||
}
|
||
}
|
||
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})"));
|
||
}
|
||
let pick = |f: &dyn Fn(&Member) -> bool| members.iter().filter(|m| f(m)).cloned().collect::<Vec<_>>();
|
||
groups
|
||
.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::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))
|
||
}
|
||
Group::Checks => Ok(Shard::Checks),
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// The features `cargo tree -e normal,dev,build --prefix none -f '{p}|{f}'` shows for each of
|
||
/// `members`, by name; a crate the tree holds twice (once for the host, say) has two entries.
|
||
/// Other copies of a member's name (craft-libs' git copies of geom and pathops) are not members.
|
||
pub fn tree_features(tree: &str, members: &[Member]) -> BTreeMap<String, BTreeSet<String>> {
|
||
let mut found: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||
for line in tree.lines() {
|
||
let line = line.trim_end();
|
||
let line = line.strip_suffix(" (*)").unwrap_or(line);
|
||
let Some((package, features)) = line.split_once('|') else { continue };
|
||
let Some(m) =
|
||
members.iter().find(|m| package.strip_prefix(&format!("{} v{} (", m.name, m.version)).is_some_and(|source| !source.contains("://")))
|
||
else {
|
||
continue;
|
||
};
|
||
let mut features: Vec<&str> = features.split(',').map(str::trim).filter(|f| !f.is_empty()).collect();
|
||
features.sort_unstable();
|
||
found.entry(m.name.clone()).or_default().insert(features.join(","));
|
||
}
|
||
found
|
||
}
|
||
|
||
/// One line for each crate of `shard` whose features in `alone` (the shard's tree) differ from
|
||
/// `workspace` (the whole workspace's tree).
|
||
pub fn feature_differences(
|
||
shard: usize,
|
||
crates: &[Member],
|
||
workspace: &BTreeMap<String, BTreeSet<String>>,
|
||
alone: &BTreeMap<String, BTreeSet<String>>,
|
||
) -> Vec<String> {
|
||
let show = |set: Option<&BTreeSet<String>>| match set {
|
||
None => "absent".to_owned(),
|
||
Some(set) => set.iter().map(|f| format!("[{f}]")).collect::<Vec<_>>().join(" "),
|
||
};
|
||
crates
|
||
.iter()
|
||
.filter(|m| workspace.get(&m.name) != alone.get(&m.name))
|
||
.map(|m| {
|
||
format!("{}: features {} in shard {shard}, {} with the whole workspace", m.name, show(alone.get(&m.name)), show(workspace.get(&m.name)))
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// `cargo tree` with the features of each package, for `select` (`--workspace` or `-p` ids).
|
||
fn tree(select: &[String]) -> Result<String, String> {
|
||
let mut c = crate::cargo();
|
||
// Without `--color never`, CARGO_TERM_COLOR=always (as the gate sets it) colors the ` (*)` marks.
|
||
c.args(["tree", "--color", "never", "-e", "normal,dev,build", "--prefix", "none", "-f", "{p}|{f}"]).args(select);
|
||
let out = c.output().map_err(|e| format!("cargo tree: failed to spawn: {e}"))?;
|
||
if !out.status.success() {
|
||
return Err(format!("cargo tree {}: exited with {}:\n{}", select.join(" "), out.status, String::from_utf8_lossy(&out.stderr)));
|
||
}
|
||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||
}
|
||
|
||
/// `-p <id>` for each crate.
|
||
pub fn select(crates: &[Member]) -> Vec<String> {
|
||
crates.iter().flat_map(|m| ["-p".to_owned(), m.id.clone()]).collect()
|
||
}
|
||
|
||
/// The package names of `crates`, for messages.
|
||
pub fn names(crates: &[Member]) -> String {
|
||
crates.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ")
|
||
}
|
||
|
||
/// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`].
|
||
pub fn check() -> Result<Vec<Shard>, String> {
|
||
let members = members(&crate::metadata()?)?;
|
||
let shards = assign(GROUPS, &members)?;
|
||
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));
|
||
}
|
||
}
|
||
if !differences.is_empty() {
|
||
return Err(format!(
|
||
"{} crate(s) build with other features in their shard than in `cargo test --workspace`, so some of their tests \
|
||
would build differently or not at all (turn the feature on in the crate's own dev-dependencies, or move the crate \
|
||
to the shard of the crate that turns it on):\n {}",
|
||
differences.len(),
|
||
differences.join("\n ")
|
||
));
|
||
}
|
||
Ok(shards)
|
||
}
|
||
|
||
/// `cargo xtask shards`: prints each shard's crates after [`check`], and returns the shards.
|
||
pub fn run() -> Result<Vec<Shard>, String> {
|
||
let shards = check()?;
|
||
for (i, shard) in shards.iter().enumerate() {
|
||
match shard {
|
||
Shard::Tests(crates, 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))
|
||
}
|
||
Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()),
|
||
}
|
||
}
|
||
println!("OK: every workspace member is tested on one shard, with the features `cargo test --workspace` gives it.");
|
||
Ok(shards)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
fn m(name: &str) -> Member {
|
||
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
|
||
}
|
||
|
||
#[test]
|
||
fn the_doc_tests_leave_out_only_packages_whose_library_cargo_cannot_doc_test() {
|
||
let package = |kinds: &[&str]| serde_json::json!({ "targets": [{ "kind": kinds }, { "kind": ["bin"] }] });
|
||
assert!(has_doctests(&package(&["lib"])));
|
||
assert!(has_doctests(&package(&["rlib"])));
|
||
assert!(has_doctests(&package(&["proc-macro"])));
|
||
assert!(has_doctests(&package(&["cdylib", "rlib"])));
|
||
assert!(has_doctests(&package(&["bin"])));
|
||
assert!(has_doctests(&serde_json::json!({ "targets": [] })));
|
||
assert!(!has_doctests(&package(&["cdylib"])));
|
||
assert!(!has_doctests(&package(&["dylib"])));
|
||
assert!(!has_doctests(&package(&["staticlib"])));
|
||
let mut cdylib = m("cdylib");
|
||
cdylib.doctests = false;
|
||
assert_eq!(with_doctests(&[m("a"), cdylib, m("b")]).iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["a", "b"]);
|
||
}
|
||
|
||
fn crates(shard: &Shard) -> Vec<&str> {
|
||
match shard {
|
||
Shard::Tests(c, _) => c.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
|
||
/// runs a share of the same tests, so it is counted with part 1.
|
||
fn owners(shard: &Shard) -> Vec<&str> {
|
||
match shard {
|
||
Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(),
|
||
_ => crates(shard),
|
||
}
|
||
}
|
||
|
||
/// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with
|
||
/// `args` from [`Part::runs`] runs, as nextest selects them: the `-E` filterset (`test(=…)`
|
||
/// terms joined by `|`, or `not (…)` of them) first, then `--partition count:<k>/<n>`, which
|
||
/// keeps the i-th (0-based) test the filter left in each binary when `i % n` is `k - 1`.
|
||
fn selected<'a>(args: &[String], tests: &[(&'a str, &'a str)]) -> Vec<(&'a str, &'a str)> {
|
||
let value = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].as_str());
|
||
let filtered: Vec<(&str, &str)> = match value("-E") {
|
||
None => tests.to_vec(),
|
||
Some(expr) => {
|
||
let (negated, body) = expr.strip_prefix("not (").and_then(|e| e.strip_suffix(')')).map_or((false, expr), |b| (true, b));
|
||
let names: Vec<&str> = body.split(" | ").map(|t| t.strip_prefix("test(=").and_then(|t| t.strip_suffix(')')).unwrap()).collect();
|
||
tests.iter().copied().filter(|(_, t)| names.contains(t) != negated).collect()
|
||
}
|
||
};
|
||
match value("--partition") {
|
||
None => filtered,
|
||
Some(p) => {
|
||
let (k, n) = p.strip_prefix("count:").and_then(|p| p.split_once('/')).unwrap();
|
||
let (k, n): (usize, usize) = (k.parse().unwrap(), n.parse().unwrap());
|
||
let mut counts = BTreeMap::new();
|
||
filtered
|
||
.into_iter()
|
||
.filter(|(binary, _)| {
|
||
let count = counts.entry(*binary).or_insert(0);
|
||
let selected = *count % n == k - 1;
|
||
*count += 1;
|
||
selected
|
||
})
|
||
.collect()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The tests each part of `split` runs, over all of its runs.
|
||
fn share<'a>(split: &'static Split, tests: &[(&'a str, &'a str)]) -> Vec<Vec<(&'a str, &'a str)>> {
|
||
(1..=split.parts()).map(|index| Part { split, index }.runs().iter().flat_map(|args| selected(args, tests)).collect()).collect()
|
||
}
|
||
|
||
static SPLIT: Split = Split { crates: &["a"], pinned: &[&["a::slow1", "a::slow3"], &["a::slow2"]] };
|
||
|
||
#[test]
|
||
fn a_split_runs_on_its_parts_in_a_row() {
|
||
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<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]);
|
||
assert_eq!(shards[1], Shard::Tests(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();
|
||
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"));
|
||
const DOUBLE: Split = Split { crates: &["a"], pinned: &[&["a::t"], &["a::t"]] };
|
||
assert!(assign(&[Group::Part(&DOUBLE, 1), Group::Part(&DOUBLE, 2), Group::Rest], &ws).unwrap_err().contains("pinned to two parts"));
|
||
}
|
||
|
||
#[test]
|
||
fn every_test_of_a_split_runs_on_exactly_one_part() {
|
||
let tests = [
|
||
("a::lib", "a::t1"),
|
||
("a::lib", "a::slow1"),
|
||
("a::lib", "a::t2"),
|
||
("a::lib", "a::t3"),
|
||
("a::bin/a", "a::slow2"),
|
||
("a::bin/a", "a::t4"),
|
||
("a::bin/a", "a::t5"),
|
||
("a::bin/a", "a::slow3"),
|
||
];
|
||
let parts = share(&SPLIT, &tests);
|
||
assert_eq!(
|
||
parts,
|
||
[
|
||
vec![("a::lib", "a::t1"), ("a::lib", "a::t3"), ("a::bin/a", "a::t4"), ("a::lib", "a::slow1"), ("a::bin/a", "a::slow3")],
|
||
vec![("a::lib", "a::t2"), ("a::bin/a", "a::t5"), ("a::bin/a", "a::slow2")],
|
||
]
|
||
);
|
||
let mut all = parts.concat();
|
||
all.sort_unstable();
|
||
let mut want = tests.to_vec();
|
||
want.sort_unstable();
|
||
assert_eq!(all, want);
|
||
let (one, two) = (Part { split: &SPLIT, index: 1 }, Part { split: &SPLIT, index: 2 });
|
||
assert_eq!(
|
||
one.runs(),
|
||
[
|
||
vec![
|
||
"--partition".to_owned(),
|
||
"count:1/2".to_owned(),
|
||
"--no-tests=pass".to_owned(),
|
||
"-E".to_owned(),
|
||
"not (test(=a::slow1) | test(=a::slow3) | test(=a::slow2))".to_owned(),
|
||
],
|
||
vec!["-E".to_owned(), "test(=a::slow1) | test(=a::slow3)".to_owned()],
|
||
]
|
||
);
|
||
assert!(one.is_first() && !two.is_first());
|
||
let list = r#"{"rust-suites":{"a::lib":{"testcases":{"a::t1":{},"a::slow1":{}}},"a::bin/a":{"testcases":{"a::slow2":{}}}}}"#;
|
||
assert_eq!(one.missing_pins(list).unwrap(), ["a::slow3"]);
|
||
assert!(two.missing_pins(list).unwrap().is_empty());
|
||
assert!(one.missing_pins("invalid JSON").is_err());
|
||
assert!(one.missing_pins("{}").is_err());
|
||
assert!(one.missing_pins(r#"{"rust-suites":{"a::lib":{}}}"#).is_err());
|
||
// A split that pins nothing passes no filterset, which nextest would reject as `not ()`.
|
||
static BARE: Split = Split { crates: &["a"], pinned: &[&[], &[]] };
|
||
assert_eq!(Part { split: &BARE, index: 2 }.runs(), [vec!["--partition".to_owned(), "count:2/2".to_owned(), "--no-tests=pass".to_owned()]]);
|
||
assert_eq!(share(&BARE, &tests).concat().len(), tests.len());
|
||
}
|
||
|
||
#[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();
|
||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]);
|
||
assert_eq!(shards[2], Shard::Checks);
|
||
}
|
||
|
||
#[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();
|
||
assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}");
|
||
let unknown = assign(&[Group::Crates(&["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::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates"));
|
||
}
|
||
|
||
#[test]
|
||
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 all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect();
|
||
all.sort_unstable();
|
||
assert_eq!(tested, all);
|
||
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn the_workspace_doc_tests_skip_the_cdylib_thumbnail_handler() {
|
||
let ws = members(&crate::metadata().unwrap()).unwrap();
|
||
let doctests = |name: &str| ws.iter().find(|m| m.name == name).map(|m| m.doctests);
|
||
assert_eq!(doctests("vectorcraft-thumbnail-handler"), Some(false));
|
||
assert_eq!(doctests("vectorcraft-geom"), Some(true));
|
||
assert_eq!(doctests("vectorcraft-cli"), Some(true));
|
||
}
|
||
|
||
#[test]
|
||
fn a_feature_only_another_shard_turns_on_is_a_difference() {
|
||
let ws = [m("lib"), m("geom")];
|
||
let workspace = "\
|
||
lib v0.1.0 (/w/lib)|default,synth
|
||
geom v0.1.0 (/w/geom)|
|
||
geom v0.18.0 (https://github.com/x/y?rev=1#1)|old
|
||
lib v0.1.0 (/w/lib)|default,synth (*)
|
||
";
|
||
let alone = "\
|
||
lib v0.1.0 (/w/lib)|default
|
||
geom v0.1.0 (/w/geom)|
|
||
";
|
||
let workspace = tree_features(workspace, &ws);
|
||
assert_eq!(workspace["lib"], BTreeSet::from(["default,synth".to_owned()]));
|
||
assert_eq!(workspace["geom"], BTreeSet::from([String::new()]));
|
||
let alone = tree_features(alone, &ws);
|
||
assert_eq!(feature_differences(4, &ws, &workspace, &alone), ["lib: features [default] in shard 4, [default,synth] with the whole workspace"]);
|
||
assert!(feature_differences(4, &ws, &workspace, &workspace).is_empty());
|
||
assert_eq!(
|
||
feature_differences(4, &[m("lib")], &workspace, &BTreeMap::new()),
|
||
["lib: features absent in shard 4, [default,synth] with the whole workspace"]
|
||
);
|
||
}
|
||
}
|