Skip to main content

xtask/
tiers.rs

1//! The test-tier probe (crate-hygiene track, C4b, #2940).
2//!
3//! Every test in the workspace belongs to exactly one tier (unit, integration,
4//! system), selected by the `default-filter` of the `ci-unit`, `ci-integration`
5//! and `ci-system` profiles in `.config/nextest.toml`. [`check_partition`]
6//! takes the full test list and each tier's list and fails when a test is in
7//! none or in more than one. A tier that selects nothing, or an empty full
8//! list, also fails: a probe that parsed nothing must not read as a pass (the
9//! lesson of A4b's review).
10//!
11//! [`probe`] gets the lists from `cargo nextest list`, so the filtersets are
12//! evaluated by nextest itself, not re-implemented here. It needs `cargo-nextest`
13//! and built test binaries, so CI runs it in the `test` job, where both exist.
14//! [`check_profiles`] is the static half (no build, no nextest): the three tier
15//! profiles exist, inherit `ci`, and carry a filter.
16
17use std::collections::BTreeSet;
18use std::path::Path;
19use std::process::Command;
20
21/// The tiers, cheapest first: the order C4c runs them in.
22pub const TIERS: [&str; 3] = ["unit", "integration", "system"];
23
24/// The profile the Linux `test` job runs: everything but the system tier.
25pub const LOWER_PROFILE: &str = "ci-lower";
26
27/// The tests a profile selects in `cargo nextest list --message-format json`
28/// output, one `<binary-id> <test name>` string each. Anything that is not that document
29/// is an error, never an empty list.
30pub fn parse_list(json: &str) -> Result<BTreeSet<String>, String> {
31    let doc: serde_json::Value =
32        serde_json::from_str(json).map_err(|e| format!("not JSON: {e}"))?;
33    let suites = doc
34        .get("rust-suites")
35        .and_then(|s| s.as_object())
36        .ok_or("no `rust-suites` object: not nextest list output")?;
37    let mut out = BTreeSet::new();
38    for (binary, suite) in suites {
39        let cases = suite
40            .get("testcases")
41            .and_then(|c| c.as_object())
42            .ok_or_else(|| format!("suite `{binary}` has no `testcases` object"))?;
43        // `list` reports every test, filtered out or not, and marks the ones the
44        // profile's `default-filter` selects. A test with no mark counts as
45        // selected, so a format change makes tiers overlap (a loud failure)
46        // rather than empty (a quiet pass).
47        out.extend(
48            cases
49                .iter()
50                .filter(|(_, case)| {
51                    case.pointer("/filter-match/status")
52                        .and_then(|v| v.as_str())
53                        != Some("mismatch")
54                })
55                .map(|(name, _)| format!("{binary} {name}")),
56        );
57    }
58    Ok(out)
59}
60
61/// Checks that `tiers` partition `all`. Returns each tier's size, or every
62/// problem found.
63pub fn check_partition(
64    all: &BTreeSet<String>,
65    tiers: &[(&str, BTreeSet<String>)],
66) -> Result<Vec<(String, usize)>, Vec<String>> {
67    let mut problems = Vec::new();
68    if all.is_empty() {
69        problems.push("the full test list is empty: nothing was listed".to_string());
70    }
71    for (name, set) in tiers {
72        if set.is_empty() {
73            problems.push(format!("tier `{name}` selects no test"));
74        }
75    }
76    for test in all {
77        let in_tiers: Vec<&str> = tiers
78            .iter()
79            .filter(|(_, set)| set.contains(test))
80            .map(|(name, _)| *name)
81            .collect();
82        match in_tiers.len() {
83            1 => {}
84            0 => problems.push(format!("in no tier: {test}")),
85            _ => problems.push(format!(
86                "in {} tiers ({}): {test}",
87                in_tiers.len(),
88                in_tiers.join(", ")
89            )),
90        }
91    }
92    for (name, set) in tiers {
93        for test in set.difference(all) {
94            problems.push(format!(
95                "tier `{name}` selects a test the full list lacks: {test}"
96            ));
97        }
98    }
99    if problems.is_empty() {
100        Ok(tiers
101            .iter()
102            .map(|(n, s)| (n.to_string(), s.len()))
103            .collect())
104    } else {
105        Err(problems)
106    }
107}
108
109/// `lower` (the `ci-lower` profile) must be exactly the unit and integration
110/// tiers together: the Linux job that runs it then leaves nothing out and runs
111/// nothing twice with the system job.
112pub fn check_lower(
113    lower: &BTreeSet<String>,
114    unit: &BTreeSet<String>,
115    integration: &BTreeSet<String>,
116) -> Result<(), Vec<String>> {
117    let want: BTreeSet<&String> = unit.union(integration).collect();
118    let got: BTreeSet<&String> = lower.iter().collect();
119    let mut problems = Vec::new();
120    for t in want.difference(&got) {
121        problems.push(format!(
122            "{LOWER_PROFILE} omits the unit/integration test `{t}`"
123        ));
124    }
125    for t in got.difference(&want) {
126        problems.push(format!(
127            "{LOWER_PROFILE} selects `{t}`, which is not unit or integration"
128        ));
129    }
130    if problems.is_empty() {
131        Ok(())
132    } else {
133        Err(problems)
134    }
135}
136
137/// The static half: each tier profile exists in `nextest_toml`, inherits `ci`
138/// and has a non-empty `default-filter`.
139pub fn check_profiles(nextest_toml: &str) -> Result<(), Vec<String>> {
140    let doc: toml::Table = nextest_toml
141        .parse()
142        .map_err(|e| vec![format!(".config/nextest.toml does not parse: {e}")])?;
143    let profiles = doc
144        .get("profile")
145        .and_then(|p| p.as_table())
146        .ok_or_else(|| vec![".config/nextest.toml has no [profile.*] tables".to_string()])?;
147    let mut problems = Vec::new();
148    let names = TIERS
149        .iter()
150        .map(|t| format!("ci-{t}"))
151        .chain([LOWER_PROFILE.to_string()]);
152    for name in names {
153        let Some(profile) = profiles.get(&name).and_then(|p| p.as_table()) else {
154            problems.push(format!("[profile.{name}] is missing"));
155            continue;
156        };
157        if profile.get("inherits").and_then(|v| v.as_str()) != Some("ci") {
158            problems.push(format!("[profile.{name}] must `inherits = \"ci\"`"));
159        }
160        let filter = profile
161            .get("default-filter")
162            .and_then(|v| v.as_str())
163            .unwrap_or("");
164        if filter.trim().is_empty() {
165            problems.push(format!("[profile.{name}] has no `default-filter`"));
166        }
167    }
168    if problems.is_empty() {
169        Ok(())
170    } else {
171        Err(problems)
172    }
173}
174
175fn list(root: &Path, profile: &str) -> Result<BTreeSet<String>, String> {
176    let out = Command::new("cargo")
177        .args([
178            "nextest",
179            "list",
180            "--workspace",
181            "--locked",
182            "--profile",
183            profile,
184        ])
185        .args(["--message-format", "json"])
186        .current_dir(root)
187        .output()
188        .map_err(|e| {
189            format!("cannot run `cargo nextest list` (is cargo-nextest installed?): {e}")
190        })?;
191    if !out.status.success() {
192        return Err(format!(
193            "`cargo nextest list --profile {profile}` failed:\n{}",
194            String::from_utf8_lossy(&out.stderr)
195        ));
196    }
197    parse_list(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("profile {profile}: {e}"))
198}
199
200/// Lists the whole suite (`ci`) and each tier, and checks they partition it.
201pub fn probe(root: &Path) -> Result<String, Vec<String>> {
202    let all = list(root, "ci").map_err(|e| vec![e])?;
203    let mut sets = Vec::new();
204    for tier in TIERS {
205        sets.push((
206            tier,
207            list(root, &format!("ci-{tier}")).map_err(|e| vec![e])?,
208        ));
209    }
210    let sizes = check_partition(&all, &sets)?;
211    let lower = list(root, LOWER_PROFILE).map_err(|e| vec![e])?;
212    check_lower(&lower, &sets[0].1, &sets[1].1)?;
213    let total: usize = sizes.iter().map(|(_, n)| n).sum();
214    let parts: Vec<String> = sizes.iter().map(|(t, n)| format!("{t} {n}")).collect();
215    Ok(format!(
216        "{total} tests, each in exactly one tier ({})",
217        parts.join(", ")
218    ))
219}