From 5a731c36f95cf9a3567c390f0d3a30287c31e8a0 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 20 Nov 2026 14:45:55 -0800 Subject: [PATCH 01/14] perf(testkit): run conformance tests concurrently within each CI row Signed-off-by: Matthew Grossman --- .github/workflows/e2e-docker-test.yml | 1 + .github/workflows/e2e-kubernetes-test.yml | 1 + .github/workflows/e2e-podman-test.yml | 2 + .github/workflows/e2e-suites.yml | 16 ++- .github/workflows/e2e-vm-test.yml | 1 + TESTING.md | 10 ++ e2e/support/conformance.sh | 6 +- tests/runner/src/execute.rs | 8 +- tests/runner/src/main.rs | 27 ++++ tests/suites/conformance/README.md | 7 ++ tests/testkit/README.md | 9 +- tests/testkit/testkit/src/program/capture.rs | 22 ++-- tests/testkit/testkit/src/program/mod.rs | 23 +++- .../testkit/testkit/src/program/supervisor.rs | 117 ++++++++++++------ tests/testkit/testkit/tests/program.rs | 55 ++++++-- 15 files changed, 228 insertions(+), 77 deletions(-) diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 172e1b8a6a..95ce46f5ce 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,5 +107,6 @@ jobs: - name: Run tests env: + OPENSHELL_CONFORMANCE_TEST_THREADS: "4" OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index e70e19e361..35c204111f 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,6 +163,7 @@ jobs: - name: Run Kubernetes E2E env: + OPENSHELL_CONFORMANCE_TEST_THREADS: "4" AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index f2e7baf0ce..a4ee37d359 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -83,6 +83,8 @@ jobs: run: echo "${{ secrets.GITHUB_TOKEN }}" | podman login ghcr.io -u "${GITHUB_ACTOR}" --password-stdin - name: Run tests + env: + OPENSHELL_CONFORMANCE_TEST_THREADS: "4" run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index a2fade9dcc..5d2d1e2262 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -93,12 +93,12 @@ jobs: # package runs every package in the workspace; each driver suite is a # workspace of its own. rows='[ - {"environment":"ubuntu-docker-rootful","installer":"deb","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"ubuntu-docker-rootful","installer":"deb-external-docker-driver","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","external_driver":true}, - {"environment":"fedora-podman-rootful","installer":"rpm","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootless","installer":"rpm","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"ubuntu-k3s","installer":"k3s","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04"}, - {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful","installer":"deb","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","test_threads":4}, + {"environment":"ubuntu-docker-rootful","installer":"deb-external-docker-driver","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","external_driver":true,"test_threads":4}, + {"environment":"fedora-podman-rootful","installer":"rpm","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","test_threads":4}, + {"environment":"fedora-podman-rootless","installer":"rpm","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","test_threads":4}, + {"environment":"ubuntu-k3s","installer":"k3s","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04","test_threads":4}, + {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04","test_threads":4}, {"environment":"ubuntu-docker-rootful-cdi","installer":"deb","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, @@ -252,6 +252,7 @@ jobs: PACKAGE: ${{ matrix.package }} GATEWAY: ${{ matrix.gateway }} DISRUPTION: ${{ matrix.disruption }} + TEST_THREADS: ${{ matrix.test_threads }} run: | # The tests this environment can't pass yet; the runner passes the # variable on to the guest. @@ -270,6 +271,9 @@ jobs: chmod +x "${program}" "${program}" list > /dev/null selection=(--program "${program}") + if [ -n "${TEST_THREADS}" ]; then + selection+=(--test-threads "${TEST_THREADS}") + fi else if [ "${PREBUILT}" = "true" ]; then selection=(--bundle artifacts/prebuilt-bundle) diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index 82d86058b8..9a04b2e405 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,6 +64,7 @@ jobs: - name: Run tests env: + OPENSHELL_CONFORMANCE_TEST_THREADS: "4" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index f29510b0af..e7f4878cfc 100644 --- a/TESTING.md +++ b/TESTING.md @@ -203,6 +203,11 @@ re-locks a workspace from the root lockfile. Add new testkit workspaces to #### What a conformance test may assert +Conformance tests must work concurrently on a shared gateway. Use +`Context::name` (or testkit's sandbox builder) for gateway resource names, +use test-unique selector values, and scope assertions and cleanup to +resources the test owns. Do not change gateway-wide settings or routes. + Conformance tests run on every compute driver, so they check the public contract and nothing a driver is free to change. @@ -255,6 +260,8 @@ nextest filterset. The runner runs the program's `ready` and `run` commands in the guest and still writes `junit.xml` and `nextest.log` (the program's output) to the results directory. Branch E2E builds `openshell-conformance` once and passes it to every conformance row this way. +With `--program`, `--test-threads N` runs up to N tests concurrently in the +guest; the default is one. `openshell-test-runner build --family --out ` builds a family's test bundle for the guest without booting a VM, and `run --bundle ` runs @@ -512,6 +519,9 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. +Set `OPENSHELL_CONFORMANCE_TEST_THREADS` to run conformance tests concurrently +in these wrappers; it defaults to one. Direct runs use +`openshell-conformance run --test-threads N`. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index e9c076206c..fd51c752c2 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -84,7 +84,11 @@ e2e_run_openshell_conformance() { # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - "${program}" run --junit "${junit}" + local args=(--junit "${junit}") + if [[ -n "${OPENSHELL_CONFORMANCE_TEST_THREADS:-}" ]]; then + args+=(--test-threads "${OPENSHELL_CONFORMANCE_TEST_THREADS}") + fi + "${program}" run "${args[@]}" } if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index a1b6d5a237..6ffef26527 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -139,6 +139,8 @@ pub struct Run<'a> { /// Narrowing the tests in the bundle: nextest filtersets (`-E`) for a /// nextest bundle, parts of test names for a program bundle. pub filters: &'a [String], + /// Concurrency override for a prebuilt program. + pub test_threads: Option, /// Where `junit.xml`, `nextest.log` and, after a failure, the guest's /// `diagnostics/` go. pub results: &'a Path, @@ -405,6 +407,7 @@ async fn run_selected( let archive = format!("{guest}/tests.tar.zst"); let extract = format!("{guest}/extract"); let config = format!("{guest}/nextest.toml"); + let test_threads = run.test_threads.map(|count| count.to_string()); let mut tests = vec!["env"]; tests.extend(env.iter().map(String::as_str)); match kind { @@ -436,10 +439,11 @@ async fn run_selected( tests.extend(["-E", filter]); } } - // The program runs its tests one at a time, and writes the report - // where `collect_results` looks for it. Kind::Program => { tests.extend([program.as_str(), "run", "--junit", &junit]); + if let Some(count) = &test_threads { + tests.extend(["--test-threads", count]); + } // `run` takes name filters as arguments, after `--` so that one // starting with a dash isn't read as an option. if !filters.is_empty() { diff --git a/tests/runner/src/main.rs b/tests/runner/src/main.rs index d2fbefbe7c..83dc96fe12 100644 --- a/tests/runner/src/main.rs +++ b/tests/runner/src/main.rs @@ -8,6 +8,7 @@ //! provides the guest cross-compilation toolchain, QEMU, Ansible, and the //! tmachine configuration. +use std::num::NonZeroUsize; use std::path::{Path, PathBuf}; use std::process::ExitCode; @@ -84,6 +85,9 @@ struct RunArgs { /// the guest's architecture (a `*-unknown-linux-musl` build). #[arg(long, value_name = "PATH", conflicts_with = "packages")] program: Option, + /// Maximum number of tests the prebuilt program runs at once [default: 1]. + #[arg(long, value_name = "N", requires = "program")] + test_threads: Option, /// The gateway name the installer registers with the CLI. The packaged /// installers register `openshell`. #[arg(long, default_value = "openshell")] @@ -181,6 +185,7 @@ async fn run(args: RunArgs) -> Result { gateway: &args.gateway, bundle: &bundle, filters: &filters, + test_threads: args.test_threads, results: &results, keep: args.keep, disruption, @@ -257,6 +262,28 @@ fn repo_root() -> Result { mod tests { use super::*; + #[test] + fn test_threads_requires_a_program_and_a_positive_count() { + let args = [ + "runner", + "run", + "--environment", + "ubuntu-k3s", + "--installer", + "k3s", + "--family", + "conformance", + "--test-threads", + ]; + assert!(Cli::try_parse_from(args.into_iter().chain(["4"])).is_err()); + assert!(Cli::try_parse_from(args.into_iter().chain(["0", "--program", "p"])).is_err()); + let cli = Cli::try_parse_from(args.into_iter().chain(["4", "--program", "p"])).unwrap(); + let Command::Run(run) = cli.command else { + panic!("not run") + }; + assert_eq!(run.test_threads.map(NonZeroUsize::get), Some(4)); + } + #[test] fn family_is_a_path_under_tests_suites() { let root = Path::new("/repo"); diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index 3827ab597e..84a84392c1 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -68,6 +68,9 @@ Feature and driver suites are not part of it. The and exit codes. `tasks/scripts/check-conformance-program.sh` checks that it lists the same tests as nextest. +`run --test-threads 4` runs up to four tests at once on the same gateway. +The default is one. + ### Marking a test unsupported in CI When a test can't pass in one environment yet, for example because of a driver @@ -92,6 +95,10 @@ Add a `#[testkit::test]` function to a suite, or for a new area, a new file in `src/` and a `mod` line for it in `src/lib.rs`. `openshell-conformance` includes every test in the crate. +Tests must be safe to run concurrently on a shared gateway. Use test-unique +names, selectors, and host fixtures; assert on test-owned resources, not +gateway-wide counts. Do not change gateway-wide settings or routes. + ## What a test may assert These tests run on every compute driver, so they check the public contract and diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 953ebfd9dd..1b700ead43 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -229,21 +229,24 @@ program for the conformance suite; see |---|---| | `list [FILTER]...` | Prints each test's name and description. Ignored tests are included and marked. | | `ready [--timeout SECS]` | Waits for the gateway, like `testkit-ready` (default 60 seconds). Exits 2 if it is not ready in time. | -| `run [FILTER]...` | Runs the tests one at a time, each in its own process. Unix only. | +| `run [FILTER]...` | Runs each test in its own process. Unix only. | A filter selects tests whose name contains it. `run` also takes: - `--include-ignored`: runs ignored tests too, instead of reporting them as skipped. +- `--test-threads N` (default 1): runs up to N tests at once. - `--timeout SECS` (default 900): a test that runs longer gets SIGTERM, then SIGKILL after `--grace SECS` (default 10). - `--junit PATH`: writes a JUnit report with one test suite per family. Each test runs in its own process group. When the test's process exits, `run` kills anything left in the group, such as CLI processes the test started. -Interrupting `run` stops the current test the same way and runs no more +It prints each completed test's output as one block on stderr, keeping up to +the last 4 MiB of each stream for the console and JUnit. +Interrupting `run` stops the active tests the same way and runs no more tests; a second interrupt skips the grace period. If `run` itself is killed -with SIGKILL, the current test's process group keeps running. In a container +with SIGKILL, active test process groups keep running. In a container where `run` is PID 1, start it under an init, for example with `docker run --init`. diff --git a/tests/testkit/testkit/src/program/capture.rs b/tests/testkit/testkit/src/program/capture.rs index 329c22ac68..17cc446909 100644 --- a/tests/testkit/testkit/src/program/capture.rs +++ b/tests/testkit/testkit/src/program/capture.rs @@ -1,16 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Copying a test's output to the console while keeping it for the report. +//! Draining a test's output while keeping its tail for the console and report. use std::collections::VecDeque; -use std::io::{self, Read, Write}; +use std::io::{self, Read}; use std::sync::{Arc, Mutex, PoisonError}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; -/// How much of each stream is kept for the report. Output beyond this is -/// still shown; the report keeps the end, where failures are. +/// How much of each stream is kept. Keep the end, where failures are. const KEPT_BYTES: usize = 4 << 20; /// How long to wait for a stream to close after the test's process group is @@ -30,11 +29,8 @@ struct Kept { } impl Capture { - /// Copy `stream` to `console` on a thread, keeping a copy. - pub fn start( - mut stream: impl Read + Send + 'static, - mut console: impl Write + Send + 'static, - ) -> Self { + /// Drain `stream` on a thread so the test can keep writing. + pub fn start(mut stream: impl Read + Send + 'static) -> Self { let kept = Arc::new(Mutex::new(Kept::default())); let thread = std::thread::spawn({ let kept = Arc::clone(&kept); @@ -47,11 +43,9 @@ impl Capture { Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, Err(_) => return, }; - let chunk = &buffer[..read]; - let _ = console.write_all(chunk).and_then(|()| console.flush()); kept.lock() .unwrap_or_else(PoisonError::into_inner) - .push(chunk); + .push(&buffer[..read]); } } }); @@ -91,8 +85,8 @@ mod tests { use super::{Capture, KEPT_BYTES, Kept}; #[test] - fn copies_and_keeps_the_stream() { - let capture = Capture::start(&b"one\ntwo\n"[..], std::io::sink()); + fn keeps_the_stream() { + let capture = Capture::start(&b"one\ntwo\n"[..]); assert_eq!(capture.finish(), b"one\ntwo\n"); } diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index eb1db6c4d3..1c30ef91f9 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -16,8 +16,9 @@ //! //! - `list [FILTER]...` prints each test's name and description. //! - `ready [--timeout SECS]` waits for the gateway, as `testkit-ready` does. -//! - `run [FILTER]...` runs tests one at a time, each in its own process with -//! a timeout, and can write a `JUnit` report. Unix only. +//! - `run [FILTER]...` runs tests in separate processes with a timeout and +//! optional `JUnit` report. Use `--test-threads N` to run tests in parallel. +//! Unix only. //! //! Any other arguments are libtest's, so the program also works as a //! `harness = false` test target under `cargo test` and nextest: it answers @@ -42,6 +43,7 @@ mod unsupported; pub(crate) use unsupported::Unsupported; use std::ffi::OsString; +use std::num::NonZeroUsize; use std::path::PathBuf; use std::process::ExitCode; use std::time::Duration; @@ -130,7 +132,7 @@ enum Command { #[arg(long, default_value = "60", value_name = "SECS", value_parser = seconds)] timeout: Duration, }, - /// Run tests one at a time, each in its own process. Exits 1 if a test + /// Run tests, each in its own process. Exits 1 if a test /// failed and 2 if tests could not run. Run { /// Run tests whose name contains any of these (all if none). @@ -138,6 +140,9 @@ enum Command { /// Run ignored tests too. #[arg(long)] include_ignored: bool, + /// Maximum number of tests to run at once. + #[arg(long, default_value = "1", value_name = "N")] + test_threads: NonZeroUsize, /// Stop a test that runs longer than this, in seconds. Longer than /// testkit's own step timeouts, so those report first. #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] @@ -177,6 +182,7 @@ fn command( Command::Run { filters, include_ignored, + test_threads, timeout, grace, junit, @@ -188,6 +194,7 @@ fn command( include_ignored, unsupported, }, + test_threads, timeout, grace, junit, @@ -200,6 +207,7 @@ fn run( program: &str, tests: &'static [Test], selection: Selection, + test_threads: NonZeroUsize, timeout: Duration, grace: Duration, junit: Option, @@ -213,6 +221,7 @@ fn run( }; let options = supervisor::Options { selection, + test_threads, timeout, grace, junit, @@ -226,6 +235,7 @@ fn run( program: &str, _tests: &'static [Test], _selection: Selection, + _test_threads: NonZeroUsize, _timeout: Duration, _grace: Duration, _junit: Option, @@ -379,6 +389,8 @@ mod tests { "smoke", "life", "--include-ignored", + "--test-threads", + "4", "--timeout", "1.5", "--junit", @@ -388,6 +400,7 @@ mod tests { let Command::Run { filters, include_ignored, + test_threads, timeout, grace, junit, @@ -397,6 +410,7 @@ mod tests { }; assert_eq!(filters, ["smoke", "life"]); assert!(include_ignored); + assert_eq!(test_threads.get(), 4); assert_eq!(timeout, Duration::from_millis(1500)); assert_eq!(grace, Duration::from_secs(10)); assert_eq!(junit.unwrap().to_str(), Some("out/junit.xml")); @@ -410,6 +424,9 @@ mod tests { #[test] fn rejects_bad_limits() { + for bad in ["0", "-1", "1.5"] { + assert!(Cli::try_parse_from(["p", "run", "--test-threads", bad]).is_err()); + } for bad in ["0", "-1", "soon", "inf", "NaN"] { assert!( Cli::try_parse_from(["p", "run", "--timeout", bad]).is_err(), diff --git a/tests/testkit/testkit/src/program/supervisor.rs b/tests/testkit/testkit/src/program/supervisor.rs index 087438bcdc..c69f46cfb7 100644 --- a/tests/testkit/testkit/src/program/supervisor.rs +++ b/tests/testkit/testkit/src/program/supervisor.rs @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! `run`: run the selected tests one at a time, each in a new process. +//! `run`: run the selected tests with bounded concurrency, each in a new process. //! //! The program starts itself once per test as ` --exact --nocapture`, //! the same interface nextest uses, in a new process group. A test that runs //! past its timeout gets `SIGTERM`, a grace period, then `SIGKILL`. Output is -//! shown as it comes and kept for the `JUnit` report. +//! buffered for each test and shown when it ends. //! //! A test stopped this way does not run its cleanup: testkit tests do not //! handle `SIGTERM` yet, so sandboxes named `test--*` can be left @@ -14,8 +14,12 @@ use std::borrow::Cow; use std::fmt::Write as _; +use std::io::{self, Write as _}; +use std::num::NonZeroUsize; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, ExitStatus, Stdio}; +use std::sync::{Mutex, mpsc}; +use std::thread; use std::time::{Duration, Instant}; use super::capture::Capture; @@ -28,6 +32,7 @@ const LIBTEST_FAILED: i32 = 101; pub struct Options { pub selection: Selection, + pub test_threads: NonZeroUsize, pub timeout: Duration, pub grace: Duration, pub junit: Option, @@ -96,8 +101,9 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit return ExitCode::from(ERROR_EXIT); } let skipped = selected.len() - to_run; + let workers = options.test_threads.get().min(to_run); eprintln!( - "{program}: running {to_run} test{} one at a time{}", + "{program}: running {to_run} test{} (up to {workers} at once){}", plural(to_run), if skipped > 0 { format!(", skipping {skipped} ignored or unsupported") @@ -109,42 +115,54 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit let started = Instant::now(); let selected_count = selected.len(); let mut runs = Vec::with_capacity(selected_count); - let mut position = 0; + let mut pending = Vec::with_capacity(to_run); for (test, disposition) in selected { - // A stop signal that arrives between tests still ends the run. - if process::stop_requested() { - break; - } - let skip = match disposition { - Disposition::Run => None, - Disposition::Skip => Some(Outcome::Skipped), - Disposition::Unsupported(issue) => Some(Outcome::Unsupported(issue)), + let outcome = match disposition { + Disposition::Run => { + pending.push(test); + continue; + } + Disposition::Skip => Outcome::Skipped, + Disposition::Unsupported(issue) => Outcome::Unsupported(issue), }; - if let Some(outcome) = skip { - runs.push(TestRun { - test, - outcome, - duration: None, - stdout: Vec::new(), - stderr: Vec::new(), + runs.push(TestRun { + test, + outcome, + duration: None, + stdout: Vec::new(), + stderr: Vec::new(), + }); + } + + let pending = Mutex::new(pending.into_iter()); + thread::scope(|scope| { + let (send, recv) = mpsc::channel(); + for _ in 0..workers { + let (pending, send) = (&pending, send.clone()); + scope.spawn(move || { + loop { + let test = { + let mut pending = pending.lock().expect("test queue"); + if process::stop_requested() { + break; + } + pending.next() + }; + let Some(test) = test else { break }; + if send.send(run_one(exe, test, options)).is_err() { + break; + } + } }); - continue; } - position += 1; - let name = test.name(); - eprintln!("==> [{position}/{to_run}] {name}"); - let run = run_one(exe, test, options); - let elapsed = run.duration.unwrap_or_default(); - match run.outcome.message() { - None => eprintln!("<== {} {name} ({elapsed:.1?})", run.outcome.label()), - Some(message) => eprintln!( - "<== {} {name} ({elapsed:.1?}): {message}", - run.outcome.label() - ), + drop(send); + for (index, run) in recv.into_iter().enumerate() { + print_run(&run, index + 1, to_run); + runs.push(run); } - runs.push(run); - } + }); + runs.sort_by_cached_key(|run| run.test.name()); let not_run = selected_count - runs.len(); let mut status = summarize(program, &runs, not_run, started.elapsed()); if let Some(path) = &options.junit { @@ -159,6 +177,29 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit ExitCode::from(status) } +fn print_run(run: &TestRun<'_>, position: usize, to_run: usize) { + let name = run.test.name(); + // Use one stream so collectors cannot reorder stdout and stderr blocks. + let mut log = io::stderr().lock(); + let _ = writeln!(log, "==> [{position}/{to_run}] {name}"); + write_output(&mut log, &run.stdout); + write_output(&mut log, &run.stderr); + let elapsed = run.duration.unwrap_or_default(); + let label = run.outcome.label(); + match run.outcome.message() { + None => writeln!(log, "<== {label} {name} ({elapsed:.1?})"), + Some(message) => writeln!(log, "<== {label} {name} ({elapsed:.1?}): {message}"), + } + .ok(); +} + +fn write_output(mut stream: impl io::Write, bytes: &[u8]) { + let _ = stream.write_all(bytes); + if !bytes.is_empty() && !bytes.ends_with(b"\n") { + let _ = stream.write_all(b"\n"); + } +} + fn run_one<'a>(exe: &Path, test: &'a Test, options: &Options) -> TestRun<'a> { let name = test.name(); let mut command = Command::new(exe); @@ -186,14 +227,8 @@ fn run_one<'a>(exe: &Path, test: &'a Test, options: &Options) -> TestRun<'a> { }; } }; - let stdout = child - .stdout - .take() - .map(|stream| Capture::start(stream, std::io::stdout())); - let stderr = child - .stderr - .take() - .map(|stream| Capture::start(stream, std::io::stderr())); + let stdout = child.stdout.take().map(Capture::start); + let stderr = child.stderr.take().map(Capture::start); let ended = process::wait(&mut child, options.timeout, options.grace); let duration = started.elapsed(); let outcome = match ended { diff --git a/tests/testkit/testkit/tests/program.rs b/tests/testkit/testkit/tests/program.rs index 6f03ffbec7..0e230d9a28 100644 --- a/tests/testkit/testkit/tests/program.rs +++ b/tests/testkit/testkit/tests/program.rs @@ -89,7 +89,24 @@ mod unix { std::fs::write(pid_file, helper.id().to_string()).expect("write pid"); } - pub static FIXTURES: [Test; 7] = [ + fn overlap(name: &str, peer: &str) { + let dir = PathBuf::from(std::env::var_os("FIXTURE_OVERLAP_DIR").expect("fixture dir")); + println!("{name}: stdout"); + std::fs::write(dir.join(name), std::process::id().to_string()).expect("write pid"); + let deadline = Instant::now() + Duration::from_secs(5); + while !dir.join(peer).exists() { + assert!( + Instant::now() < deadline, + "{peer} did not start in parallel" + ); + std::thread::sleep(Duration::from_millis(10)); + } + eprintln!("{name}: stderr"); + } + + pub static FIXTURES: [Test; 9] = [ + fixture("overlap_a", || Box::pin(async { overlap("a", "b") })), + fixture("overlap_b", || Box::pin(async { overlap("b", "a") })), fixture("passes", || { Box::pin(async { println!("passes: stdout"); @@ -137,7 +154,8 @@ mod unix { }, ]; - pub static CHECKS: [Test; 14] = [ + pub static CHECKS: [Test; 15] = [ + check("run_in_parallel", || Box::pin(async { run_in_parallel() })), check("nextest_interface", || { Box::pin(async { nextest_interface() }) }), @@ -224,7 +242,8 @@ mod unix { stdout(&list), "fixture::fails: test\nfixture::hangs: test\nfixture::ignored: test\n\ fixture::ignores_sigterm: test\nfixture::interrupts_after_exit: test\n\ - fixture::leaves_a_helper: test\nfixture::passes: test\n" + fixture::leaves_a_helper: test\nfixture::overlap_a: test\n\ + fixture::overlap_b: test\nfixture::passes: test\n" ); let ignored = output(program( "fixtures", @@ -281,8 +300,8 @@ mod unix { &["run", "passes", "fails", "ignored", "--junit", &junit_arg], )); assert_eq!(run.status.code(), Some(1)); - // Test output is passed through. - assert!(stdout(&run).contains("passes: stdout")); + // Both child streams are printed together on stderr. + assert!(stderr(&run).contains("passes: stdout")); assert!(stderr(&run).contains("passes: stderr")); assert!(stderr(&run).contains("1 passed, 1 failed, 1 skipped")); assert!(stderr(&run).contains("FAIL fixture::fails: test failed")); @@ -303,6 +322,28 @@ mod unix { } } + fn run_in_parallel() { + let dir = tempfile::tempdir().expect("temp dir"); + let mut command = program("fixtures", &["run", "overlap_", "--test-threads", "2"]); + command.env("FIXTURE_OVERLAP_DIR", dir.path()); + let run = output(command); + assert!(run.status.success()); + assert_ne!( + read_pid(&dir.path().join("a")), + read_pid(&dir.path().join("b")) + ); + let log = stderr(&run); + for name in ["a", "b"] { + let suffix = format!("] fixture::overlap_{name}\n"); + let (_, block) = log.split_once(&suffix).expect("test header"); + let end = format!("<== PASS fixture::overlap_{name}"); + let (block, _) = block.split_once(&end).expect("test result"); + assert!(block.contains(&format!("{name}: stdout"))); + assert!(block.contains(&format!("{name}: stderr"))); + assert!(!block.contains("==>"), "{block}"); + } + } + fn run_exit_codes() { let pass = output(program("fixtures", &["run", "passes"])); assert_eq!(pass.status.code(), Some(0)); @@ -469,7 +510,7 @@ mod unix { assert_eq!(run.status.code(), Some(2)); assert!(stderr(&run).contains("<== PASS fixture::interrupts_after_exit")); assert!(stderr(&run).contains("interrupted; 1 later test did not run")); - assert!(!stdout(&run).contains("passes: stdout")); + assert!(!stderr(&run).contains("passes: stdout")); let xml = std::fs::read_to_string(path).expect("junit report"); assert!(!xml.contains("fixture::passes"), "{xml}"); } @@ -560,7 +601,7 @@ mod unix { // A forced run refuses. let forced = with(&["run", "fails", "--include-ignored"]); assert_eq!(forced.status.code(), Some(1)); - assert!(stdout(&forced).contains("remove the entry from OPENSHELL_TEST_UNSUPPORTED")); + assert!(stderr(&forced).contains("remove the entry from OPENSHELL_TEST_UNSUPPORTED")); assert!(!stderr(&forced).contains("fixture failure")); // Selecting only unsupported tests leaves nothing to run. let none = with(&["run", "fails"]); From 6ef8bf7549d1fb707c6a18055ce51bbf154691df Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 20 Nov 2026 14:54:26 -0800 Subject: [PATCH 02/14] perf(e2e): schedule prebuilt conformance with nextest Signed-off-by: Matthew Grossman --- TESTING.md | 13 +- e2e/support/conformance.sh | 33 ++++- tasks/scripts/check-conformance-program.sh | 21 +++- tests/runner/src/bundle.rs | 24 +++- tests/runner/src/execute.rs | 95 +++++++------- tests/suites/conformance/README.md | 5 +- tests/suites/conformance/src/main.rs | 2 +- tests/testkit/README.md | 22 +++- tests/testkit/testkit/src/program/capture.rs | 22 ++-- tests/testkit/testkit/src/program/mod.rs | 60 +++++---- tests/testkit/testkit/src/program/nextest.rs | 71 +++++++++++ .../testkit/testkit/src/program/supervisor.rs | 117 ++++++------------ tests/testkit/testkit/src/registry.rs | 2 +- tests/testkit/testkit/tests/program.rs | 55 ++------ 14 files changed, 308 insertions(+), 234 deletions(-) create mode 100644 tests/testkit/testkit/src/program/nextest.rs diff --git a/TESTING.md b/TESTING.md index e7f4878cfc..92bbbf61e8 100644 --- a/TESTING.md +++ b/TESTING.md @@ -256,9 +256,9 @@ prebuilt testkit program, such as a static `openshell-conformance` for the guest's architecture, instead of building the family's tests; it can't be combined with `--package`. With it, `--filter` (repeatable) takes parts of test names, as the program does, such as `--filter policy_advisor::`, rather than a -nextest filterset. The runner runs the program's `ready` -and `run` commands in the guest and still writes `junit.xml` and `nextest.log` -(the program's output) to the results directory. Branch E2E builds +nextest filterset. The runner runs the program's `ready` command in the +guest, then uses nextest to run the prebuilt binary. It writes `junit.xml` +and `nextest.log` to the results directory. Branch E2E builds `openshell-conformance` once and passes it to every conformance row this way. With `--program`, `--test-threads N` runs up to N tests concurrently in the guest; the default is one. @@ -519,9 +519,10 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -Set `OPENSHELL_CONFORMANCE_TEST_THREADS` to run conformance tests concurrently -in these wrappers; it defaults to one. Direct runs use -`openshell-conformance run --test-threads N`. +Set `OPENSHELL_CONFORMANCE_TEST_THREADS` to make these wrappers run the +conformance program with nextest and the given number of workers. CI uses +four. When unset, the wrappers use the serial `openshell-conformance run` +command, which does not require nextest. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index fd51c752c2..ca389a4faa 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -84,13 +84,40 @@ e2e_run_openshell_conformance() { # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - local args=(--junit "${junit}") if [[ -n "${OPENSHELL_CONFORMANCE_TEST_THREADS:-}" ]]; then - args+=(--test-threads "${OPENSHELL_CONFORMANCE_TEST_THREADS}") + e2e_nextest_conformance "${program}" "${junit}" + else + "${program}" run --junit "${junit}" fi - "${program}" run "${args[@]}" } +e2e_nextest_conformance() ( + local program=$1 junit=$2 + local work status=0 + work="$(mktemp -d)" || return + trap 'rm -rf "${work}"' EXIT + "${program}" nextest-metadata "${work}" || return + cat > "${work}/nextest.toml" <<'EOF' +[profile.openshell] +slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } + +[profile.openshell.junit] +path = "junit.xml" +store-success-output = true +EOF + cargo-nextest nextest run \ + --cargo-metadata "${work}/cargo-metadata.json" \ + --binaries-metadata "${work}/binaries-metadata.json" \ + --config-file "${work}/nextest.toml" --profile openshell \ + --test-threads "${OPENSHELL_CONFORMANCE_TEST_THREADS}" \ + --no-tests fail --no-fail-fast --success-output immediate \ + --failure-output immediate || status=$? + if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then + mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return + fi + return "${status}" +) + if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then e2e_run_openshell_conformance fi diff --git a/tasks/scripts/check-conformance-program.sh b/tasks/scripts/check-conformance-program.sh index 198a25e090..3840b1aa38 100755 --- a/tasks/scripts/check-conformance-program.sh +++ b/tasks/scripts/check-conformance-program.sh @@ -14,8 +14,11 @@ manifest="${root}/tests/suites/conformance/Cargo.toml" work="$(mktemp -d)" trap 'rm -rf "${work}"' EXIT -cargo run --quiet --locked --manifest-path "${manifest}" --bin openshell-conformance -- list \ - | awk '{print $1}' | sort > "${work}/program" +messages="$(cargo build --locked --manifest-path "${manifest}" --bin openshell-conformance --message-format json)" +program="$(jq -r 'select(.reason == "compiler-artifact" and .executable != null) | .executable' <<< "${messages}")" +cp "${program}" "${work}/test-program" +program="${work}/test-program" +"${program}" list | awk '{print $1}' | sort > "${work}/program" # --run-ignored all: the program lists ignored tests too, so nextest must as well. cargo nextest list --locked --color never --run-ignored all --manifest-path "${manifest}" --message-format oneline \ | awk '{print $2}' | sort > "${work}/nextest" @@ -32,6 +35,18 @@ if [[ ! -s "${work}/program" ]]; then echo "error: openshell-conformance lists no tests" >&2 exit 1 fi +# Check the same inventory from a renamed, prebuilt binary without a checkout +# or Cargo on PATH. Metadata must retain the Cargo binary ID. +"${program}" nextest-metadata "${work}/metadata" +nextest="$(command -v cargo-nextest)" +( + cd "${work}/metadata" + PATH=/usr/bin:/bin "${nextest}" nextest list --color never --run-ignored all \ + --cargo-metadata cargo-metadata.json --binaries-metadata binaries-metadata.json \ + --message-format oneline +) > "${work}/prebuilt" +grep -q '^conformance::bin/openshell-conformance ' "${work}/prebuilt" +awk '{print $2}' "${work}/prebuilt" | sort | diff -u "${work}/program" - # unsupported.yaml must pass the program's own checks (known tests, https # issues, no duplicates) for every environment it names, and name only # environments that exist. @@ -51,6 +66,6 @@ while IFS= read -r environment; do exit 1 fi OPENSHELL_TEST_UNSUPPORTED="$("${root}/tasks/scripts/conformance-unsupported.sh" "${environment}")" \ - cargo run --quiet --locked --manifest-path "${manifest}" --bin openshell-conformance -- list > /dev/null + "${program}" list > /dev/null done < <(yq -r '.[].environments[]' "${unsupported_file}" | sort -u) echo "openshell-conformance lists the same $(wc -l < "${work}/program" | tr -d ' ') tests as nextest" diff --git a/tests/runner/src/bundle.rs b/tests/runner/src/bundle.rs index 4f953f6a8e..44caac0032 100644 --- a/tests/runner/src/bundle.rs +++ b/tests/runner/src/bundle.rs @@ -76,7 +76,7 @@ struct Manifest { pub enum Kind { /// A nextest archive, run with `cargo-nextest`. Nextest, - /// A prebuilt testkit program (`list`, `ready` and `run`), run directly. + /// A prebuilt testkit program, run by nextest without a Cargo build. Program, } @@ -93,7 +93,7 @@ impl Bundle { } } -/// A bundle holding only `program`, a testkit program already built for the +/// A bundle holding `program`, a testkit program already built for the /// guest target. `program` must be a static binary, as the guest's libc is /// not known. pub fn program(program: &Path) -> Result { @@ -105,9 +105,22 @@ pub fn program(program: &Path) -> Result { let dir = tempfile::tempdir().context("create bundle directory")?; std::fs::copy(program, dir.path().join(PROGRAM_BINARY)) .with_context(|| format!("copy {}", program.display()))?; + std::fs::write(dir.path().join(CONFIG), program_config())?; Ok(Bundle(dir, Kind::Program)) } +fn program_config() -> String { + format!( + r#"[profile.{PROFILE}] +slow-timeout = {{ period = "900s", terminate-after = 1, grace-period = "{GRACE_PERIOD_SECS}s" }} + +[profile.{PROFILE}.junit] +path = "junit.xml" +store-success-output = true +"# + ) +} + /// The Rust target for guests. tmachine only boots guests of the host's /// architecture, and static musl binaries don't depend on the guest's libc. fn guest_target() -> Result<&'static str> { @@ -362,17 +375,18 @@ mod tests { } #[test] - fn program_bundle_holds_only_the_program() { + fn program_bundle_holds_the_program_and_nextest_config() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("openshell-conformance"); std::fs::write(&path, b"binary").unwrap(); let bundle = program(&path).unwrap(); assert_eq!(bundle.kind(), Kind::Program); - let names: Vec<_> = std::fs::read_dir(bundle.path()) + let mut names: Vec<_> = std::fs::read_dir(bundle.path()) .unwrap() .map(|entry| entry.unwrap().file_name()) .collect(); - assert_eq!(names, [PROGRAM_BINARY]); + names.sort(); + assert_eq!(names, [CONFIG, PROGRAM_BINARY]); assert!(program(&dir.path().join("missing")).is_err()); } diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index 6ffef26527..d005cc4f93 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -25,16 +25,15 @@ use crate::disruption::Disruption; use crate::test_env; const GUEST_DIR: &str = "/var/tmp/openshell-tests"; -/// The test log's name, in the guest directory and in the results. A program -/// bundle's log keeps the name, so consumers of the results see one layout. +/// The test log's name, in the guest directory and in the results. const NEXTEST_LOG: &str = "nextest.log"; /// How long the gateway has to become healthy after the environment is up. // Matches the installers' own wait: an HA k3s gateway booted from a cached // disk can take minutes to report healthy. const READY_TIMEOUT_SECS: u64 = 300; /// How long the test run may take in total. Individual tests are bounded by -/// the nextest profile's slow-timeout, or by a program's own `run --timeout` -/// default; this catches a run that stops making progress some other way. +/// the nextest profile's slow-timeout; this catches a run that stops making +/// progress some other way. const RUN_TIMEOUT: Duration = Duration::from_mins(45); /// Slack beyond the readiness check's own timeout for SSH and process start. const READY_SLACK: Duration = Duration::from_mins(1); @@ -43,9 +42,6 @@ const READY_SLACK: Duration = Duration::from_mins(1); const NEXTEST_TEST_FAILED: i32 = 100; /// nextest's exit code when `--no-tests fail` found no tests to run. const NEXTEST_NO_TESTS_RUN: i32 = 4; -/// A testkit program's exit code when a test failed. It exits 2 when tests -/// could not run. -const PROGRAM_TEST_FAILED: i32 = 1; /// How much of the end of the nextest log to print after a failure. nextest /// ends its output with a summary that names the failed tests. const LOG_TAIL_LINES: usize = 40; @@ -103,18 +99,6 @@ impl Status { )), } } - - /// The status of a testkit program's `run` that exited with `status`. - fn of_program(status: ExitStatus, log: &Path) -> Self { - match status.code() { - Some(0) => Self::Passed, - Some(PROGRAM_TEST_FAILED) => Self::Failed, - _ => Self::Error(format!( - "the test program exited with {status}; see {}", - log.display() - )), - } - } } impl fmt::Display for Status { @@ -403,19 +387,34 @@ async fn run_selected( let guest = GUEST_DIR; let kind = run.bundle.kind(); let program = format!("{guest}/{PROGRAM_BINARY}"); - let junit = format!("{guest}/junit.xml"); let archive = format!("{guest}/tests.tar.zst"); let extract = format!("{guest}/extract"); let config = format!("{guest}/nextest.toml"); - let test_threads = run.test_threads.map(|count| count.to_string()); + let test_threads = run + .test_threads + .map_or(1, std::num::NonZeroUsize::get) + .to_string(); + let metadata = format!("{guest}/metadata"); + let cargo_metadata = format!("{metadata}/cargo-metadata.json"); + let binaries_metadata = format!("{metadata}/binaries-metadata.json"); let mut tests = vec!["env"]; tests.extend(env.iter().map(String::as_str)); + tests.extend([ + "cargo-nextest", + "nextest", + "run", + "--config-file", + &config, + "--profile", + PROFILE, + "--test-threads", + &test_threads, + "--no-tests", + "fail", + ]); match kind { Kind::Nextest => { tests.extend([ - "cargo-nextest", - "nextest", - "run", "--archive-file", &archive, "--workspace-remap", @@ -423,29 +422,31 @@ async fn run_selected( "--extract-to", &extract, "--extract-overwrite", - "--config-file", - &config, - "--profile", - PROFILE, "--no-capture", - // Tests share one gateway and the guest has 4 GiB; run them - // serially whatever --no-capture implies. - "--test-threads", - "1", - "--no-tests", - "fail", ]); for filter in filters { tests.extend(["-E", filter]); } } Kind::Program => { - tests.extend([program.as_str(), "run", "--junit", &junit]); - if let Some(count) = &test_threads { - tests.extend(["--test-threads", count]); - } - // `run` takes name filters as arguments, after `--` so that one - // starting with a dash isn't read as an option. + checked( + "write nextest metadata", + session + .exec(&[&program, "nextest-metadata", &metadata]) + .await?, + )?; + tests.extend([ + "--cargo-metadata", + &cargo_metadata, + "--binaries-metadata", + &binaries_metadata, + "--no-fail-fast", + "--success-output", + "immediate", + "--failure-output", + "immediate", + ]); + // Nextest's positional filters, like the program's, match substrings. if !filters.is_empty() { tests.push("--"); tests.extend(filters.iter().map(String::as_str)); @@ -466,10 +467,7 @@ async fn run_selected( command.extend(tests); let output = session.exec_timeout(&command, RUN_TIMEOUT).await?; let log = run.results.join(NEXTEST_LOG); - Ok(match kind { - Kind::Nextest => Status::of_nextest(output.status, &log), - Kind::Program => Status::of_program(output.status, &log), - }) + Ok(Status::of_nextest(output.status, &log)) } /// Copy the nextest log and the JUnit report out of the guest, whether or not @@ -629,15 +627,6 @@ mod tests { assert!(matches!(status(1), Status::Error(_))); } - #[test] - fn status_follows_the_program_exit_code() { - let status = |code| Status::of_program(ExitStatus::from_raw(code << 8), Path::new("log")); - assert_eq!(status(0), Status::Passed); - assert_eq!(status(PROGRAM_TEST_FAILED), Status::Failed); - // Exit 2: tests could not run. - assert!(matches!(status(2), Status::Error(_))); - } - #[test] fn k3s_diagnostics_keep_everything_the_old_playbook_collected() { for wanted in [ diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index 84a84392c1..fab7139b18 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -68,8 +68,9 @@ Feature and driver suites are not part of it. The and exit codes. `tasks/scripts/check-conformance-program.sh` checks that it lists the same tests as nextest. -`run --test-threads 4` runs up to four tests at once on the same gateway. -The default is one. +`run` is serial. To run a prebuilt binary in parallel without Cargo or a +checkout, use `nextest-metadata` and the [nextest command in the testkit +README](../../testkit/README.md#test-programs). ### Marking a test unsupported in CI diff --git a/tests/suites/conformance/src/main.rs b/tests/suites/conformance/src/main.rs index 7b4e899c60..8334cfd3e1 100644 --- a/tests/suites/conformance/src/main.rs +++ b/tests/suites/conformance/src/main.rs @@ -14,5 +14,5 @@ use std::process::ExitCode; use conformance as _; fn main() -> ExitCode { - testkit::main() + testkit::program::main_for(env!("CARGO_PKG_NAME"), env!("CARGO_BIN_NAME")) } diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 1b700ead43..b91b7698ee 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -229,24 +229,22 @@ program for the conformance suite; see |---|---| | `list [FILTER]...` | Prints each test's name and description. Ignored tests are included and marked. | | `ready [--timeout SECS]` | Waits for the gateway, like `testkit-ready` (default 60 seconds). Exits 2 if it is not ready in time. | -| `run [FILTER]...` | Runs each test in its own process. Unix only. | +| `run [FILTER]...` | Runs the tests one at a time, each in its own process. Unix only. | +| `nextest-metadata DIR` | Writes a stub manifest and JSON metadata describing the prebuilt executable. | A filter selects tests whose name contains it. `run` also takes: - `--include-ignored`: runs ignored tests too, instead of reporting them as skipped. -- `--test-threads N` (default 1): runs up to N tests at once. - `--timeout SECS` (default 900): a test that runs longer gets SIGTERM, then SIGKILL after `--grace SECS` (default 10). - `--junit PATH`: writes a JUnit report with one test suite per family. Each test runs in its own process group. When the test's process exits, `run` kills anything left in the group, such as CLI processes the test started. -It prints each completed test's output as one block on stderr, keeping up to -the last 4 MiB of each stream for the console and JUnit. -Interrupting `run` stops the active tests the same way and runs no more +Interrupting `run` stops the current test the same way and runs no more tests; a second interrupt skips the grace period. If `run` itself is killed -with SIGKILL, active test process groups keep running. In a container +with SIGKILL, the current test's process group keeps running. In a container where `run` is PID 1, start it under an init, for example with `docker run --init`. @@ -262,6 +260,18 @@ test target with `harness = false` therefore also runs under `cargo test` and nextest. In that mode tests run in one process, one at a time unless `--test-threads` says otherwise. +To run a prebuilt program with nextest (no Cargo or checkout required), write +metadata to a fresh directory on the machine where the program will run: + +```shell +openshell-conformance nextest-metadata metadata +cargo-nextest nextest run --cargo-metadata metadata/cargo-metadata.json \ + --binaries-metadata metadata/binaries-metadata.json --test-threads 4 +``` + +The metadata refers to the binary's absolute path. Regenerate it if the +binary moves. + A test's name is its module path without the crate name, then its function name, as in nextest. Its family, which groups tests in the JUnit report, is the first directory under the last `suites` directory in the crate's path: diff --git a/tests/testkit/testkit/src/program/capture.rs b/tests/testkit/testkit/src/program/capture.rs index 17cc446909..329c22ac68 100644 --- a/tests/testkit/testkit/src/program/capture.rs +++ b/tests/testkit/testkit/src/program/capture.rs @@ -1,15 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Draining a test's output while keeping its tail for the console and report. +//! Copying a test's output to the console while keeping it for the report. use std::collections::VecDeque; -use std::io::{self, Read}; +use std::io::{self, Read, Write}; use std::sync::{Arc, Mutex, PoisonError}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; -/// How much of each stream is kept. Keep the end, where failures are. +/// How much of each stream is kept for the report. Output beyond this is +/// still shown; the report keeps the end, where failures are. const KEPT_BYTES: usize = 4 << 20; /// How long to wait for a stream to close after the test's process group is @@ -29,8 +30,11 @@ struct Kept { } impl Capture { - /// Drain `stream` on a thread so the test can keep writing. - pub fn start(mut stream: impl Read + Send + 'static) -> Self { + /// Copy `stream` to `console` on a thread, keeping a copy. + pub fn start( + mut stream: impl Read + Send + 'static, + mut console: impl Write + Send + 'static, + ) -> Self { let kept = Arc::new(Mutex::new(Kept::default())); let thread = std::thread::spawn({ let kept = Arc::clone(&kept); @@ -43,9 +47,11 @@ impl Capture { Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, Err(_) => return, }; + let chunk = &buffer[..read]; + let _ = console.write_all(chunk).and_then(|()| console.flush()); kept.lock() .unwrap_or_else(PoisonError::into_inner) - .push(&buffer[..read]); + .push(chunk); } } }); @@ -85,8 +91,8 @@ mod tests { use super::{Capture, KEPT_BYTES, Kept}; #[test] - fn keeps_the_stream() { - let capture = Capture::start(&b"one\ntwo\n"[..]); + fn copies_and_keeps_the_stream() { + let capture = Capture::start(&b"one\ntwo\n"[..], std::io::sink()); assert_eq!(capture.finish(), b"one\ntwo\n"); } diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index 1c30ef91f9..dedd5d2e12 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -12,13 +12,14 @@ //! } //! ``` //! -//! It has three subcommands: +//! Its subcommands: //! //! - `list [FILTER]...` prints each test's name and description. //! - `ready [--timeout SECS]` waits for the gateway, as `testkit-ready` does. -//! - `run [FILTER]...` runs tests in separate processes with a timeout and -//! optional `JUnit` report. Use `--test-threads N` to run tests in parallel. -//! Unix only. +//! - `run [FILTER]...` runs tests one at a time, each in its own process with +//! a timeout, and can write a `JUnit` report. Unix only. +//! - `nextest-metadata DIR` describes the executable to nextest, so it can +//! run the prebuilt program without Cargo. //! //! Any other arguments are libtest's, so the program also works as a //! `harness = false` test target under `cargo test` and nextest: it answers @@ -34,6 +35,7 @@ mod capture; #[cfg(unix)] mod junit; +mod nextest; #[cfg(unix)] mod process; #[cfg(unix)] @@ -43,7 +45,6 @@ mod unsupported; pub(crate) use unsupported::Unsupported; use std::ffi::OsString; -use std::num::NonZeroUsize; use std::path::PathBuf; use std::process::ExitCode; use std::time::Duration; @@ -64,9 +65,19 @@ pub fn main() -> ExitCode { main_with(&TESTS) } +/// Run a suite program with the package and binary names it has under Cargo. +/// These names are used by `nextest-metadata`, even if the executable is renamed. +pub fn main_for(package: &str, binary: &str) -> ExitCode { + dispatch(&TESTS, Some((package, binary))) +} + /// [`main`] over `tests` instead of every registered test. #[doc(hidden)] pub fn main_with(tests: &'static [Test]) -> ExitCode { + dispatch(tests, None) +} + +fn dispatch(tests: &'static [Test], identity: Option<(&str, &str)>) -> ExitCode { let args: Vec = std::env::args_os().collect(); let program = program_name(&args); // A suite crate that the program never names is not linked, and its @@ -98,7 +109,7 @@ pub fn main_with(tests: &'static [Test]) -> ExitCode { return ExitCode::from(if error.use_stderr() { ERROR_EXIT } else { 0 }); } }; - command(&program, tests, unsupported, cli.command) + command(&program, tests, unsupported, cli.command, identity) } else { libtest(tests, unsupported, args) } @@ -120,6 +131,11 @@ struct Cli { #[derive(Subcommand)] enum Command { + /// Write metadata to run the prebuilt executable with cargo-nextest. + NextestMetadata { + #[arg(value_name = "DIR")] + dir: PathBuf, + }, /// Print each test's name and description, including ignored tests. List { /// Show tests whose name contains any of these (all if none). @@ -132,7 +148,7 @@ enum Command { #[arg(long, default_value = "60", value_name = "SECS", value_parser = seconds)] timeout: Duration, }, - /// Run tests, each in its own process. Exits 1 if a test + /// Run tests one at a time, each in its own process. Exits 1 if a test /// failed and 2 if tests could not run. Run { /// Run tests whose name contains any of these (all if none). @@ -140,9 +156,6 @@ enum Command { /// Run ignored tests too. #[arg(long)] include_ignored: bool, - /// Maximum number of tests to run at once. - #[arg(long, default_value = "1", value_name = "N")] - test_threads: NonZeroUsize, /// Stop a test that runs longer than this, in seconds. Longer than /// testkit's own step timeouts, so those report first. #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] @@ -172,8 +185,23 @@ fn command( tests: &'static [Test], unsupported: Unsupported, command: Command, + identity: Option<(&str, &str)>, ) -> ExitCode { match command { + Command::NextestMetadata { dir } => { + let package = tests[0].package(); + let (package, binary) = identity.unwrap_or((package, program)); + match nextest::write(&dir, package, binary) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!( + "{program}: write nextest metadata to {}: {error}", + dir.display() + ); + ExitCode::from(ERROR_EXIT) + } + } + } Command::List { filters } => { list(tests, &unsupported, filters); ExitCode::SUCCESS @@ -182,7 +210,6 @@ fn command( Command::Run { filters, include_ignored, - test_threads, timeout, grace, junit, @@ -194,7 +221,6 @@ fn command( include_ignored, unsupported, }, - test_threads, timeout, grace, junit, @@ -207,7 +233,6 @@ fn run( program: &str, tests: &'static [Test], selection: Selection, - test_threads: NonZeroUsize, timeout: Duration, grace: Duration, junit: Option, @@ -221,7 +246,6 @@ fn run( }; let options = supervisor::Options { selection, - test_threads, timeout, grace, junit, @@ -235,7 +259,6 @@ fn run( program: &str, _tests: &'static [Test], _selection: Selection, - _test_threads: NonZeroUsize, _timeout: Duration, _grace: Duration, _junit: Option, @@ -389,8 +412,6 @@ mod tests { "smoke", "life", "--include-ignored", - "--test-threads", - "4", "--timeout", "1.5", "--junit", @@ -400,7 +421,6 @@ mod tests { let Command::Run { filters, include_ignored, - test_threads, timeout, grace, junit, @@ -410,7 +430,6 @@ mod tests { }; assert_eq!(filters, ["smoke", "life"]); assert!(include_ignored); - assert_eq!(test_threads.get(), 4); assert_eq!(timeout, Duration::from_millis(1500)); assert_eq!(grace, Duration::from_secs(10)); assert_eq!(junit.unwrap().to_str(), Some("out/junit.xml")); @@ -424,9 +443,6 @@ mod tests { #[test] fn rejects_bad_limits() { - for bad in ["0", "-1", "1.5"] { - assert!(Cli::try_parse_from(["p", "run", "--test-threads", bad]).is_err()); - } for bad in ["0", "-1", "soon", "inf", "NaN"] { assert!( Cli::try_parse_from(["p", "run", "--timeout", bad]).is_err(), diff --git a/tests/testkit/testkit/src/program/nextest.rs b/tests/testkit/testkit/src/program/nextest.rs new file mode 100644 index 0000000000..ccca4a9c97 --- /dev/null +++ b/tests/testkit/testkit/src/program/nextest.rs @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The Cargo and binary metadata nextest reads instead of building the suite. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write as _}; +use std::path::Path; + +use serde_json::json; + +pub fn write(dir: &Path, package: &str, binary: &str) -> io::Result<()> { + let exe = std::env::current_exe()?; + fs::create_dir_all(dir)?; + let dir = dir.canonicalize()?; + let manifest = dir.join("Cargo.toml"); + let target = dir.join("target"); + let package_id = format!("{package} 0.0.0"); + let binary_id = format!("{package}::bin/{binary}"); + + // The manifest identifies the workspace. Nextest reads the JSON rather + // than invoking Cargo, and the only test target is the running binary. + let cargo = json!({ + "packages": [{ + "name": package, "version": "0.0.0", "id": package_id, + "manifest_path": manifest, + "authors": [], "categories": [], "keywords": [], + "dependencies": [], "features": {}, + "targets": [{ + "name": binary, "kind": ["bin"], "crate_types": ["bin"], + "src_path": exe, "edition": "2024", "test": true + }], + "edition": "2024" + }], + "workspace_members": [package_id], + "workspace_default_members": [package_id], + "target_directory": target, + "workspace_root": dir, + "version": 1 + }); + // Omitting platforms lets nextest use its own native target when rustc + // isn't installed. The executable is already runnable on this machine. + let binaries = json!({ + "rust-build-meta": { + "target-directory": target, + "base-output-directories": [], + "non-test-binaries": {}, + "linked-paths": [] + }, + "rust-binaries": { + binary_id.clone(): { + "binary-id": binary_id, "binary-name": binary, + "package-id": package_id, "kind": "bin", + "binary-path": exe, "build-platform": "target" + } + } + }); + let create = |name| { + OpenOptions::new() + .write(true) + .create_new(true) + .open(dir.join(name)) + }; + writeln!( + create("Cargo.toml")?, + "[package]\nname = {package:?}\nversion = \"0.0.0\"" + )?; + serde_json::to_writer(create("cargo-metadata.json")?, &cargo)?; + serde_json::to_writer(create("binaries-metadata.json")?, &binaries)?; + Ok(()) +} diff --git a/tests/testkit/testkit/src/program/supervisor.rs b/tests/testkit/testkit/src/program/supervisor.rs index c69f46cfb7..087438bcdc 100644 --- a/tests/testkit/testkit/src/program/supervisor.rs +++ b/tests/testkit/testkit/src/program/supervisor.rs @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! `run`: run the selected tests with bounded concurrency, each in a new process. +//! `run`: run the selected tests one at a time, each in a new process. //! //! The program starts itself once per test as ` --exact --nocapture`, //! the same interface nextest uses, in a new process group. A test that runs //! past its timeout gets `SIGTERM`, a grace period, then `SIGKILL`. Output is -//! buffered for each test and shown when it ends. +//! shown as it comes and kept for the `JUnit` report. //! //! A test stopped this way does not run its cleanup: testkit tests do not //! handle `SIGTERM` yet, so sandboxes named `test--*` can be left @@ -14,12 +14,8 @@ use std::borrow::Cow; use std::fmt::Write as _; -use std::io::{self, Write as _}; -use std::num::NonZeroUsize; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, ExitStatus, Stdio}; -use std::sync::{Mutex, mpsc}; -use std::thread; use std::time::{Duration, Instant}; use super::capture::Capture; @@ -32,7 +28,6 @@ const LIBTEST_FAILED: i32 = 101; pub struct Options { pub selection: Selection, - pub test_threads: NonZeroUsize, pub timeout: Duration, pub grace: Duration, pub junit: Option, @@ -101,9 +96,8 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit return ExitCode::from(ERROR_EXIT); } let skipped = selected.len() - to_run; - let workers = options.test_threads.get().min(to_run); eprintln!( - "{program}: running {to_run} test{} (up to {workers} at once){}", + "{program}: running {to_run} test{} one at a time{}", plural(to_run), if skipped > 0 { format!(", skipping {skipped} ignored or unsupported") @@ -115,54 +109,42 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit let started = Instant::now(); let selected_count = selected.len(); let mut runs = Vec::with_capacity(selected_count); - let mut pending = Vec::with_capacity(to_run); + let mut position = 0; for (test, disposition) in selected { - let outcome = match disposition { - Disposition::Run => { - pending.push(test); - continue; - } - Disposition::Skip => Outcome::Skipped, - Disposition::Unsupported(issue) => Outcome::Unsupported(issue), + // A stop signal that arrives between tests still ends the run. + if process::stop_requested() { + break; + } + let skip = match disposition { + Disposition::Run => None, + Disposition::Skip => Some(Outcome::Skipped), + Disposition::Unsupported(issue) => Some(Outcome::Unsupported(issue)), }; - runs.push(TestRun { - test, - outcome, - duration: None, - stdout: Vec::new(), - stderr: Vec::new(), - }); - } - - let pending = Mutex::new(pending.into_iter()); - thread::scope(|scope| { - let (send, recv) = mpsc::channel(); - for _ in 0..workers { - let (pending, send) = (&pending, send.clone()); - scope.spawn(move || { - loop { - let test = { - let mut pending = pending.lock().expect("test queue"); - if process::stop_requested() { - break; - } - pending.next() - }; - let Some(test) = test else { break }; - if send.send(run_one(exe, test, options)).is_err() { - break; - } - } + if let Some(outcome) = skip { + runs.push(TestRun { + test, + outcome, + duration: None, + stdout: Vec::new(), + stderr: Vec::new(), }); + continue; } - drop(send); - for (index, run) in recv.into_iter().enumerate() { - print_run(&run, index + 1, to_run); - runs.push(run); + position += 1; + let name = test.name(); + eprintln!("==> [{position}/{to_run}] {name}"); + let run = run_one(exe, test, options); + let elapsed = run.duration.unwrap_or_default(); + match run.outcome.message() { + None => eprintln!("<== {} {name} ({elapsed:.1?})", run.outcome.label()), + Some(message) => eprintln!( + "<== {} {name} ({elapsed:.1?}): {message}", + run.outcome.label() + ), } - }); + runs.push(run); + } - runs.sort_by_cached_key(|run| run.test.name()); let not_run = selected_count - runs.len(); let mut status = summarize(program, &runs, not_run, started.elapsed()); if let Some(path) = &options.junit { @@ -177,29 +159,6 @@ pub fn run(program: &str, exe: &Path, tests: &[Test], options: &Options) -> Exit ExitCode::from(status) } -fn print_run(run: &TestRun<'_>, position: usize, to_run: usize) { - let name = run.test.name(); - // Use one stream so collectors cannot reorder stdout and stderr blocks. - let mut log = io::stderr().lock(); - let _ = writeln!(log, "==> [{position}/{to_run}] {name}"); - write_output(&mut log, &run.stdout); - write_output(&mut log, &run.stderr); - let elapsed = run.duration.unwrap_or_default(); - let label = run.outcome.label(); - match run.outcome.message() { - None => writeln!(log, "<== {label} {name} ({elapsed:.1?})"), - Some(message) => writeln!(log, "<== {label} {name} ({elapsed:.1?}): {message}"), - } - .ok(); -} - -fn write_output(mut stream: impl io::Write, bytes: &[u8]) { - let _ = stream.write_all(bytes); - if !bytes.is_empty() && !bytes.ends_with(b"\n") { - let _ = stream.write_all(b"\n"); - } -} - fn run_one<'a>(exe: &Path, test: &'a Test, options: &Options) -> TestRun<'a> { let name = test.name(); let mut command = Command::new(exe); @@ -227,8 +186,14 @@ fn run_one<'a>(exe: &Path, test: &'a Test, options: &Options) -> TestRun<'a> { }; } }; - let stdout = child.stdout.take().map(Capture::start); - let stderr = child.stderr.take().map(Capture::start); + let stdout = child + .stdout + .take() + .map(|stream| Capture::start(stream, std::io::stdout())); + let stderr = child + .stderr + .take() + .map(|stream| Capture::start(stream, std::io::stderr())); let ended = process::wait(&mut child, options.timeout, options.grace); let duration = started.elapsed(); let outcome = match ended { diff --git a/tests/testkit/testkit/src/registry.rs b/tests/testkit/testkit/src/registry.rs index b5c6252306..a4e9e6431d 100644 --- a/tests/testkit/testkit/src/registry.rs +++ b/tests/testkit/testkit/src/registry.rs @@ -59,7 +59,7 @@ impl Test { /// Names a test cannot have at the top level: the program would read them as /// its own subcommands, so nextest could not run the test by name. -pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run"]; +pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run", "nextest-metadata"]; /// Check the tests can be told apart by name. pub fn validate(tests: &[Test]) -> Result<(), String> { diff --git a/tests/testkit/testkit/tests/program.rs b/tests/testkit/testkit/tests/program.rs index 0e230d9a28..6f03ffbec7 100644 --- a/tests/testkit/testkit/tests/program.rs +++ b/tests/testkit/testkit/tests/program.rs @@ -89,24 +89,7 @@ mod unix { std::fs::write(pid_file, helper.id().to_string()).expect("write pid"); } - fn overlap(name: &str, peer: &str) { - let dir = PathBuf::from(std::env::var_os("FIXTURE_OVERLAP_DIR").expect("fixture dir")); - println!("{name}: stdout"); - std::fs::write(dir.join(name), std::process::id().to_string()).expect("write pid"); - let deadline = Instant::now() + Duration::from_secs(5); - while !dir.join(peer).exists() { - assert!( - Instant::now() < deadline, - "{peer} did not start in parallel" - ); - std::thread::sleep(Duration::from_millis(10)); - } - eprintln!("{name}: stderr"); - } - - pub static FIXTURES: [Test; 9] = [ - fixture("overlap_a", || Box::pin(async { overlap("a", "b") })), - fixture("overlap_b", || Box::pin(async { overlap("b", "a") })), + pub static FIXTURES: [Test; 7] = [ fixture("passes", || { Box::pin(async { println!("passes: stdout"); @@ -154,8 +137,7 @@ mod unix { }, ]; - pub static CHECKS: [Test; 15] = [ - check("run_in_parallel", || Box::pin(async { run_in_parallel() })), + pub static CHECKS: [Test; 14] = [ check("nextest_interface", || { Box::pin(async { nextest_interface() }) }), @@ -242,8 +224,7 @@ mod unix { stdout(&list), "fixture::fails: test\nfixture::hangs: test\nfixture::ignored: test\n\ fixture::ignores_sigterm: test\nfixture::interrupts_after_exit: test\n\ - fixture::leaves_a_helper: test\nfixture::overlap_a: test\n\ - fixture::overlap_b: test\nfixture::passes: test\n" + fixture::leaves_a_helper: test\nfixture::passes: test\n" ); let ignored = output(program( "fixtures", @@ -300,8 +281,8 @@ mod unix { &["run", "passes", "fails", "ignored", "--junit", &junit_arg], )); assert_eq!(run.status.code(), Some(1)); - // Both child streams are printed together on stderr. - assert!(stderr(&run).contains("passes: stdout")); + // Test output is passed through. + assert!(stdout(&run).contains("passes: stdout")); assert!(stderr(&run).contains("passes: stderr")); assert!(stderr(&run).contains("1 passed, 1 failed, 1 skipped")); assert!(stderr(&run).contains("FAIL fixture::fails: test failed")); @@ -322,28 +303,6 @@ mod unix { } } - fn run_in_parallel() { - let dir = tempfile::tempdir().expect("temp dir"); - let mut command = program("fixtures", &["run", "overlap_", "--test-threads", "2"]); - command.env("FIXTURE_OVERLAP_DIR", dir.path()); - let run = output(command); - assert!(run.status.success()); - assert_ne!( - read_pid(&dir.path().join("a")), - read_pid(&dir.path().join("b")) - ); - let log = stderr(&run); - for name in ["a", "b"] { - let suffix = format!("] fixture::overlap_{name}\n"); - let (_, block) = log.split_once(&suffix).expect("test header"); - let end = format!("<== PASS fixture::overlap_{name}"); - let (block, _) = block.split_once(&end).expect("test result"); - assert!(block.contains(&format!("{name}: stdout"))); - assert!(block.contains(&format!("{name}: stderr"))); - assert!(!block.contains("==>"), "{block}"); - } - } - fn run_exit_codes() { let pass = output(program("fixtures", &["run", "passes"])); assert_eq!(pass.status.code(), Some(0)); @@ -510,7 +469,7 @@ mod unix { assert_eq!(run.status.code(), Some(2)); assert!(stderr(&run).contains("<== PASS fixture::interrupts_after_exit")); assert!(stderr(&run).contains("interrupted; 1 later test did not run")); - assert!(!stderr(&run).contains("passes: stdout")); + assert!(!stdout(&run).contains("passes: stdout")); let xml = std::fs::read_to_string(path).expect("junit report"); assert!(!xml.contains("fixture::passes"), "{xml}"); } @@ -601,7 +560,7 @@ mod unix { // A forced run refuses. let forced = with(&["run", "fails", "--include-ignored"]); assert_eq!(forced.status.code(), Some(1)); - assert!(stderr(&forced).contains("remove the entry from OPENSHELL_TEST_UNSUPPORTED")); + assert!(stdout(&forced).contains("remove the entry from OPENSHELL_TEST_UNSUPPORTED")); assert!(!stderr(&forced).contains("fixture failure")); // Selecting only unsupported tests leaves nothing to run. let none = with(&["run", "fails"]); From 6d71041568568fe3bf40af986b6c9c925ce76974 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 20 Nov 2026 15:08:30 -0800 Subject: [PATCH 03/14] refactor(testkit): share E2E runner configuration across suites Signed-off-by: Matthew Grossman --- .github/actions/setup-e2e-cli/action.yml | 6 +-- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-kubernetes-test.yml | 2 +- .github/workflows/e2e-podman-test.yml | 2 +- .github/workflows/e2e-vm-test.yml | 2 +- TESTING.md | 10 ++--- e2e/rust/e2e-kubernetes.sh | 2 +- e2e/support/conformance.sh | 50 +++++------------------ e2e/support/testkit.sh | 36 ++++++++++++++++ 9 files changed, 60 insertions(+), 52 deletions(-) create mode 100644 e2e/support/testkit.sh diff --git a/.github/actions/setup-e2e-cli/action.yml b/.github/actions/setup-e2e-cli/action.yml index 6bc2a78ec2..d134a38cbd 100644 --- a/.github/actions/setup-e2e-cli/action.yml +++ b/.github/actions/setup-e2e-cli/action.yml @@ -3,7 +3,7 @@ description: Download architecture-matched prebuilt OpenShell host CLIs for E2E inputs: conformance: - description: Also download the prebuilt openshell-conformance program and set OPENSHELL_CONFORMANCE_BIN + description: Also download the prebuilt openshell-conformance program and set OPENSHELL_TESTKIT_BIN required: false default: "false" @@ -18,7 +18,7 @@ runs: - name: Configure prebuilt CLI shell: bash - run: | + run: | # zizmor: ignore[github-env] persists only a fixed path under the trusted workspace cli="$GITHUB_WORKSPACE/.e2e/prebuilt-cli/openshell" chmod +x "$cli" "$cli" --version @@ -38,4 +38,4 @@ runs: program="$GITHUB_WORKSPACE/.e2e/prebuilt-conformance/openshell-conformance" chmod +x "$program" "$program" list - echo "OPENSHELL_CONFORMANCE_BIN=$program" >> "$GITHUB_ENV" + echo "OPENSHELL_TESTKIT_BIN=$program" >> "$GITHUB_ENV" diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 95ce46f5ce..2719727154 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,6 +107,6 @@ jobs: - name: Run tests env: - OPENSHELL_CONFORMANCE_TEST_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: "4" OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index 35c204111f..a5beaa542f 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,7 +163,7 @@ jobs: - name: Run Kubernetes E2E env: - OPENSHELL_CONFORMANCE_TEST_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: "4" AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index a4ee37d359..43b7a755b0 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -84,7 +84,7 @@ jobs: - name: Run tests env: - OPENSHELL_CONFORMANCE_TEST_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: "4" run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index 9a04b2e405..4e81bcac70 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,7 +64,7 @@ jobs: - name: Run tests env: - OPENSHELL_CONFORMANCE_TEST_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: "4" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index 92bbbf61e8..5a96331369 100644 --- a/TESTING.md +++ b/TESTING.md @@ -496,7 +496,7 @@ Suites: lifecycle, the CLI, persistent workspaces, file transfer, the policy advisor, and credential gating. Driver E2E runs it with `openshell-conformance` against the lane's gateway and writes a JUnit report - under `results/`; set `OPENSHELL_CONFORMANCE_BIN` to use a prebuilt program, + under `results/`; set `OPENSHELL_TESTKIT_BIN` to use a prebuilt program, as Branch E2E does with the static build it makes once per architecture. The Docker and Podman runners build `openshell/e2e-python:dev` for it; the Kubernetes and VM runners set `OPENSHELL_TEST_PYTHON_IMAGE` to a pullable @@ -519,10 +519,10 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -Set `OPENSHELL_CONFORMANCE_TEST_THREADS` to make these wrappers run the -conformance program with nextest and the given number of workers. CI uses -four. When unset, the wrappers use the serial `openshell-conformance run` -command, which does not require nextest. +Set `OPENSHELL_TESTKIT_THREADS` to run the testkit program with nextest and +the given number of workers. CI uses four. When unset, the wrappers use +the serial `openshell-conformance run` command, which does not require +nextest. Set `OPENSHELL_TESTKIT_JUNIT` to override the report path. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/rust/e2e-kubernetes.sh b/e2e/rust/e2e-kubernetes.sh index 6a9bd6a901..18228426c0 100755 --- a/e2e/rust/e2e-kubernetes.sh +++ b/e2e/rust/e2e-kubernetes.sh @@ -83,7 +83,7 @@ run_conformance() { return 0 fi - OPENSHELL_CONFORMANCE_JUNIT="${OPENSHELL_CONFORMANCE_JUNIT:-${ROOT}/results/${OPENSHELL_E2E_REPORT_NAME:-e2e-kubernetes}-conformance.xml}" \ + OPENSHELL_TESTKIT_JUNIT="${OPENSHELL_TESTKIT_JUNIT:-${ROOT}/results/${OPENSHELL_E2E_REPORT_NAME:-e2e-kubernetes}-conformance.xml}" \ OPENSHELL_TEST_PYTHON_IMAGE="${OPENSHELL_TEST_PYTHON_IMAGE:-${E2E_PULLABLE_PYTHON_IMAGE}}" \ e2e_run_openshell_conformance "Kubernetes" } diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index ca389a4faa..f92e32fc35 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -5,6 +5,9 @@ # Shared helpers for running conformance suites against an already # configured e2e gateway. +# shellcheck source=e2e/support/testkit.sh +source "$(dirname "${BASH_SOURCE[0]}")/testkit.sh" + e2e_require_openshell_bin() { if [ -z "${OPENSHELL_BIN:-}" ]; then echo "ERROR: OPENSHELL_BIN must point to the openshell CLI under test" >&2 @@ -29,17 +32,17 @@ e2e_require_openshell_bin() { # shellcheck disable=SC2034 # Used by the scripts that source this file. E2E_PULLABLE_PYTHON_IMAGE="ghcr.io/astral-sh/uv:0.12.17-python3.12-trixie-slim@sha256:9a59bb7206905ccaae4f7dab222fbac47c125a21e5fc16f43f427cd6c940ade3" -# Print the path of the openshell-conformance program: OPENSHELL_CONFORMANCE_BIN +# Print the path of the openshell-conformance program: OPENSHELL_TESTKIT_BIN # if set, else a debug build from this checkout. e2e_openshell_conformance_bin() { local root=$1 - if [ -n "${OPENSHELL_CONFORMANCE_BIN:-}" ]; then - if [ ! -x "${OPENSHELL_CONFORMANCE_BIN}" ]; then - echo "ERROR: openshell-conformance is not executable: ${OPENSHELL_CONFORMANCE_BIN}" >&2 + if [ -n "${OPENSHELL_TESTKIT_BIN:-}" ]; then + if [ ! -x "${OPENSHELL_TESTKIT_BIN}" ]; then + echo "ERROR: testkit program is not executable: ${OPENSHELL_TESTKIT_BIN}" >&2 return 2 fi - echo "${OPENSHELL_CONFORMANCE_BIN}" + echo "${OPENSHELL_TESTKIT_BIN}" return fi @@ -61,7 +64,7 @@ e2e_openshell_conformance_bin() { } # Run the conformance suite with openshell-conformance. The JUnit report goes -# to OPENSHELL_CONFORMANCE_JUNIT, else results/conformance-.xml. +# to OPENSHELL_TESTKIT_JUNIT, else results/conformance-.xml. e2e_run_openshell_conformance() { local gateway_label=${1:-OpenShell} local root program junit @@ -69,7 +72,7 @@ e2e_run_openshell_conformance() { e2e_require_openshell_bin || return program="$(e2e_openshell_conformance_bin "${root}")" || return - junit="${OPENSHELL_CONFORMANCE_JUNIT:-${root}/results/conformance-$(echo "${gateway_label}" | tr '[:upper:]' '[:lower:]').xml}" + junit="${OPENSHELL_TESTKIT_JUNIT:-${root}/results/conformance-$(echo "${gateway_label}" | tr '[:upper:]' '[:lower:]').xml}" mkdir -p "$(dirname "${junit}")" || return # The tests this lane can't pass yet, from tests/suites/conformance/unsupported.yaml. @@ -84,40 +87,9 @@ e2e_run_openshell_conformance() { # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - if [[ -n "${OPENSHELL_CONFORMANCE_TEST_THREADS:-}" ]]; then - e2e_nextest_conformance "${program}" "${junit}" - else - "${program}" run --junit "${junit}" - fi + e2e_run_testkit "${program}" "${junit}" } -e2e_nextest_conformance() ( - local program=$1 junit=$2 - local work status=0 - work="$(mktemp -d)" || return - trap 'rm -rf "${work}"' EXIT - "${program}" nextest-metadata "${work}" || return - cat > "${work}/nextest.toml" <<'EOF' -[profile.openshell] -slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } - -[profile.openshell.junit] -path = "junit.xml" -store-success-output = true -EOF - cargo-nextest nextest run \ - --cargo-metadata "${work}/cargo-metadata.json" \ - --binaries-metadata "${work}/binaries-metadata.json" \ - --config-file "${work}/nextest.toml" --profile openshell \ - --test-threads "${OPENSHELL_CONFORMANCE_TEST_THREADS}" \ - --no-tests fail --no-fail-fast --success-output immediate \ - --failure-output immediate || status=$? - if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then - mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return - fi - return "${status}" -) - if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then e2e_run_openshell_conformance fi diff --git a/e2e/support/testkit.sh b/e2e/support/testkit.sh new file mode 100644 index 0000000000..8a29d96bb0 --- /dev/null +++ b/e2e/support/testkit.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Run a testkit program, optionally using nextest for parallel execution. +e2e_run_testkit() ( + local program=$1 junit=$2 + if [[ -z "${OPENSHELL_TESTKIT_THREADS:-}" ]]; then + "${program}" run --junit "${junit}" + return $? + fi + + local work status=0 + work="$(mktemp -d)" || return + trap 'rm -rf "${work}"' EXIT + "${program}" nextest-metadata "${work}" || return + cat > "${work}/nextest.toml" <<'EOF' +[profile.openshell] +slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } + +[profile.openshell.junit] +path = "junit.xml" +store-success-output = true +EOF + cargo-nextest nextest run \ + --cargo-metadata "${work}/cargo-metadata.json" \ + --binaries-metadata "${work}/binaries-metadata.json" \ + --config-file "${work}/nextest.toml" --profile openshell \ + --test-threads "${OPENSHELL_TESTKIT_THREADS}" \ + --no-tests fail --no-fail-fast --success-output immediate \ + --failure-output immediate || status=$? + if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then + mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return + fi + return "${status}" +) From 3b7b37204212d27372fd534435806bdd2c2acf89 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 20 Nov 2026 16:09:29 -0800 Subject: [PATCH 04/14] refactor(e2e): always use nextest in conformance wrappers Signed-off-by: Matthew Grossman --- TESTING.md | 7 +++---- e2e/support/conformance.sh | 33 ++++++++++++++++++++++++++------- e2e/support/testkit.sh | 36 ------------------------------------ 3 files changed, 29 insertions(+), 47 deletions(-) delete mode 100644 e2e/support/testkit.sh diff --git a/TESTING.md b/TESTING.md index 4471018ab4..27a33fe4e7 100644 --- a/TESTING.md +++ b/TESTING.md @@ -522,10 +522,9 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -Set `OPENSHELL_TESTKIT_THREADS` to run the testkit program with nextest and -the given number of workers. CI uses four. When unset, the wrappers use -the serial `openshell-conformance run` command, which does not require -nextest. +The wrappers use nextest. Set `OPENSHELL_TESTKIT_THREADS` to change the +worker count from the default of one. For a standalone run without nextest, +invoke `openshell-conformance run` directly. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index f614d96fd6..559bd343fd 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -5,9 +5,6 @@ # Shared helpers for running conformance suites against an already # configured e2e gateway. -# shellcheck source=e2e/support/testkit.sh -source "$(dirname "${BASH_SOURCE[0]}")/testkit.sh" - e2e_require_openshell_bin() { if [ -z "${OPENSHELL_BIN:-}" ]; then echo "ERROR: OPENSHELL_BIN must point to the openshell CLI under test" >&2 @@ -63,9 +60,9 @@ e2e_openshell_conformance_bin() { echo "${program}" } -# Run the conformance suite with openshell-conformance. The JUnit report goes +# Run the conformance suite with nextest. The JUnit report goes # to OPENSHELL_CONFORMANCE_JUNIT, else results/conformance-.xml. -e2e_run_openshell_conformance() { +e2e_run_openshell_conformance() ( local gateway_label=${1:-OpenShell} local root program junit root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -87,8 +84,30 @@ e2e_run_openshell_conformance() { # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - e2e_run_testkit "${program}" "${junit}" -} + local work status=0 + work="$(mktemp -d)" || return + trap 'rm -rf "${work}"' EXIT + "${program}" nextest-metadata "${work}" || return + cat > "${work}/nextest.toml" <<'EOF' +[profile.openshell] +slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } + +[profile.openshell.junit] +path = "junit.xml" +store-success-output = true +EOF + cargo-nextest nextest run \ + --cargo-metadata "${work}/cargo-metadata.json" \ + --binaries-metadata "${work}/binaries-metadata.json" \ + --config-file "${work}/nextest.toml" --profile openshell \ + --test-threads "${OPENSHELL_TESTKIT_THREADS:-1}" \ + --no-tests fail --no-fail-fast --success-output immediate \ + --failure-output immediate || status=$? + if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then + mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return + fi + return "${status}" +) if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then e2e_run_openshell_conformance diff --git a/e2e/support/testkit.sh b/e2e/support/testkit.sh deleted file mode 100644 index 8a29d96bb0..0000000000 --- a/e2e/support/testkit.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Run a testkit program, optionally using nextest for parallel execution. -e2e_run_testkit() ( - local program=$1 junit=$2 - if [[ -z "${OPENSHELL_TESTKIT_THREADS:-}" ]]; then - "${program}" run --junit "${junit}" - return $? - fi - - local work status=0 - work="$(mktemp -d)" || return - trap 'rm -rf "${work}"' EXIT - "${program}" nextest-metadata "${work}" || return - cat > "${work}/nextest.toml" <<'EOF' -[profile.openshell] -slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } - -[profile.openshell.junit] -path = "junit.xml" -store-success-output = true -EOF - cargo-nextest nextest run \ - --cargo-metadata "${work}/cargo-metadata.json" \ - --binaries-metadata "${work}/binaries-metadata.json" \ - --config-file "${work}/nextest.toml" --profile openshell \ - --test-threads "${OPENSHELL_TESTKIT_THREADS}" \ - --no-tests fail --no-fail-fast --success-output immediate \ - --failure-output immediate || status=$? - if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then - mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return - fi - return "${status}" -) From 7dc9bb5fef5dd8bc842e25211d22a08b73fed4eb Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 08:56:03 -0800 Subject: [PATCH 05/14] perf(e2e): bundle nextest in openshell-conformance Signed-off-by: Matthew Grossman --- .github/workflows/branch-e2e.yml | 15 +- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-kubernetes-test.yml | 2 +- .github/workflows/e2e-podman-test.yml | 2 +- .github/workflows/e2e-vm-test.yml | 1 - TESTING.md | 14 +- e2e/support/conformance.sh | 32 +-- tasks/scripts/check-conformance-program.sh | 16 -- tests/runner/src/bundle.rs | 24 +- tests/runner/src/execute.rs | 88 ++++---- tests/runner/src/main.rs | 3 +- tests/suites/conformance/Cargo.lock | 2 + tests/suites/conformance/Cargo.toml | 5 + tests/suites/conformance/README.md | 18 ++ tests/suites/conformance/build.rs | 11 + tests/suites/conformance/package.sh | 80 +++++++ tests/suites/conformance/src/bundled.rs | 223 +++++++++++++++++++ tests/suites/conformance/src/main.rs | 9 +- tests/testkit/README.md | 13 -- tests/testkit/testkit/src/program/mod.rs | 37 +-- tests/testkit/testkit/src/program/nextest.rs | 71 ------ tests/testkit/testkit/src/registry.rs | 2 +- 22 files changed, 430 insertions(+), 240 deletions(-) create mode 100644 tests/suites/conformance/build.rs create mode 100644 tests/suites/conformance/package.sh create mode 100644 tests/suites/conformance/src/bundled.rs delete mode 100644 tests/testkit/testkit/src/program/nextest.rs diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 2fbfdc62a3..6456521076 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -212,18 +212,23 @@ jobs: CARGO_TARGET_DIR: ${{ github.workspace }}/target TRIPLE: ${{ matrix.triple }} run: | - cargo build --release --locked --target "$TRIPLE" \ - --manifest-path tests/suites/conformance/Cargo.toml \ - --bin openshell-conformance - binary="target/$TRIPLE/release/openshell-conformance" + bash tests/suites/conformance/package.sh "$TRIPLE" "artifacts/conformance/$TRIPLE" + binary="artifacts/conformance/$TRIPLE/openshell-conformance" # The program must run on any lane host. tasks/scripts/verify-static-binary.sh "$binary" # Fails if the program has no tests linked. "$binary" list + # Exercise the packaged scheduler, not just the discovery interface. + PATH=/usr/bin:/bin "$binary" run --help | grep -- --test-threads + status=0 + PATH=/usr/bin:/bin "$binary" run -- __conformance_smoke_no_match__ >"$RUNNER_TEMP/conformance-smoke.log" 2>&1 || status=$? + cat "$RUNNER_TEMP/conformance-smoke.log" + test "$status" = 2 + grep -F 'no tests to run' "$RUNNER_TEMP/conformance-smoke.log" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: openshell-conformance-${{ matrix.triple }} - path: target/${{ matrix.triple }}/release/openshell-conformance + path: artifacts/conformance/${{ matrix.triple }}/openshell-conformance compression-level: 0 retention-days: 5 if-no-files-found: error diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 2719727154..4d64132e50 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,6 +107,6 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index a5beaa542f..f9f3e911c5 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,7 +163,7 @@ jobs: - name: Run Kubernetes E2E env: - OPENSHELL_TESTKIT_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index 43b7a755b0..9ea928abe9 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -84,7 +84,7 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_THREADS: "4" + OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index 4e81bcac70..82d86058b8 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,7 +64,6 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_THREADS: "4" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index 27a33fe4e7..2c4e4ca8ba 100644 --- a/TESTING.md +++ b/TESTING.md @@ -256,13 +256,14 @@ prebuilt testkit program, such as a static `openshell-conformance` for the guest's architecture, instead of building the family's tests; it can't be combined with `--package`. With it, `--filter` (repeatable) takes parts of test names, as the program does, such as `--filter policy_advisor::`, rather than a -nextest filterset. The runner runs the program's `ready` command in the -guest, then uses nextest to run the prebuilt binary. It writes `junit.xml` +nextest filterset. The runner invokes the program's `ready` and `run` +commands in the guest. It writes `junit.xml` and `nextest.log` to the results directory. Branch E2E builds `openshell-conformance` once and passes it to every conformance row this way. `--test-threads N` runs up to N tests concurrently in the guest, whether the runner builds the suite or uses `--bundle` or `--program`. The default -is one. CI rows can opt in with `test_threads`. +is one. With `--program`, the binary must support `run --test-threads`. +CI rows can opt in with `test_threads`. `openshell-test-runner build --family --out ` builds a family's test bundle for the guest without booting a VM, and `run --bundle ` runs @@ -522,9 +523,10 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -The wrappers use nextest. Set `OPENSHELL_TESTKIT_THREADS` to change the -worker count from the default of one. For a standalone run without nextest, -invoke `openshell-conformance run` directly. +Branch E2E packages `openshell-conformance` with nextest, so `run` can +schedule tests without an installed nextest. Set `OPENSHELL_TESTKIT_THREADS` +to change the worker count when using that artifact. Plain Cargo builds +support the same `run` command, but are serial. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index 559bd343fd..d4abd8914b 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -60,9 +60,9 @@ e2e_openshell_conformance_bin() { echo "${program}" } -# Run the conformance suite with nextest. The JUnit report goes +# Run the conformance suite with openshell-conformance. The JUnit report goes # to OPENSHELL_CONFORMANCE_JUNIT, else results/conformance-.xml. -e2e_run_openshell_conformance() ( +e2e_run_openshell_conformance() { local gateway_label=${1:-OpenShell} local root program junit root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -84,30 +84,12 @@ e2e_run_openshell_conformance() ( # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - local work status=0 - work="$(mktemp -d)" || return - trap 'rm -rf "${work}"' EXIT - "${program}" nextest-metadata "${work}" || return - cat > "${work}/nextest.toml" <<'EOF' -[profile.openshell] -slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } - -[profile.openshell.junit] -path = "junit.xml" -store-success-output = true -EOF - cargo-nextest nextest run \ - --cargo-metadata "${work}/cargo-metadata.json" \ - --binaries-metadata "${work}/binaries-metadata.json" \ - --config-file "${work}/nextest.toml" --profile openshell \ - --test-threads "${OPENSHELL_TESTKIT_THREADS:-1}" \ - --no-tests fail --no-fail-fast --success-output immediate \ - --failure-output immediate || status=$? - if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then - mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return + local args=(--junit "${junit}") + if [[ -n "${OPENSHELL_TESTKIT_THREADS:-}" ]]; then + args+=(--test-threads "${OPENSHELL_TESTKIT_THREADS}") fi - return "${status}" -) + "${program}" run "${args[@]}" +} if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then e2e_run_openshell_conformance diff --git a/tasks/scripts/check-conformance-program.sh b/tasks/scripts/check-conformance-program.sh index ca8edaa8f6..5d2ccdfaf0 100755 --- a/tasks/scripts/check-conformance-program.sh +++ b/tasks/scripts/check-conformance-program.sh @@ -96,22 +96,6 @@ if [[ ! -s "${work}/nextest" ]] || ! diff -u "${work}/nextest" "${work}/program" fi echo "openshell-conformance lists the same $(wc -l < "${work}/program" | tr -d ' ') tests as nextest" -# Check the same inventory from a renamed prebuilt binary without Cargo on PATH. -messages="$(cargo build --locked --manifest-path "${conformance}" --bin openshell-conformance --message-format json)" -program="$(jq -r 'select(.reason == "compiler-artifact" and .executable != null) | .executable' <<< "${messages}")" -cp "${program}" "${work}/test-program" -"${work}/test-program" nextest-metadata "${work}/metadata" -nextest="$(command -v cargo-nextest)" -( - cd "${work}/metadata" - PATH=/usr/bin:/bin OPENSHELL_TEST_UNSUPPORTED="${unsupported}" \ - "${nextest}" nextest list --color never --run-ignored all \ - --cargo-metadata cargo-metadata.json --binaries-metadata binaries-metadata.json \ - --message-format oneline -) > "${work}/prebuilt" -grep -q '^conformance::bin/openshell-conformance ' "${work}/prebuilt" -awk '{print $2}' "${work}/prebuilt" | sort | diff -u "${work}/program" - - if [[ -n "${unsupported}" ]]; then for manifest in "${manifests[@]}"; do OPENSHELL_TEST_UNSUPPORTED="${unsupported}" \ diff --git a/tests/runner/src/bundle.rs b/tests/runner/src/bundle.rs index 44caac0032..4f953f6a8e 100644 --- a/tests/runner/src/bundle.rs +++ b/tests/runner/src/bundle.rs @@ -76,7 +76,7 @@ struct Manifest { pub enum Kind { /// A nextest archive, run with `cargo-nextest`. Nextest, - /// A prebuilt testkit program, run by nextest without a Cargo build. + /// A prebuilt testkit program (`list`, `ready` and `run`), run directly. Program, } @@ -93,7 +93,7 @@ impl Bundle { } } -/// A bundle holding `program`, a testkit program already built for the +/// A bundle holding only `program`, a testkit program already built for the /// guest target. `program` must be a static binary, as the guest's libc is /// not known. pub fn program(program: &Path) -> Result { @@ -105,22 +105,9 @@ pub fn program(program: &Path) -> Result { let dir = tempfile::tempdir().context("create bundle directory")?; std::fs::copy(program, dir.path().join(PROGRAM_BINARY)) .with_context(|| format!("copy {}", program.display()))?; - std::fs::write(dir.path().join(CONFIG), program_config())?; Ok(Bundle(dir, Kind::Program)) } -fn program_config() -> String { - format!( - r#"[profile.{PROFILE}] -slow-timeout = {{ period = "900s", terminate-after = 1, grace-period = "{GRACE_PERIOD_SECS}s" }} - -[profile.{PROFILE}.junit] -path = "junit.xml" -store-success-output = true -"# - ) -} - /// The Rust target for guests. tmachine only boots guests of the host's /// architecture, and static musl binaries don't depend on the guest's libc. fn guest_target() -> Result<&'static str> { @@ -375,18 +362,17 @@ mod tests { } #[test] - fn program_bundle_holds_the_program_and_nextest_config() { + fn program_bundle_holds_only_the_program() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("openshell-conformance"); std::fs::write(&path, b"binary").unwrap(); let bundle = program(&path).unwrap(); assert_eq!(bundle.kind(), Kind::Program); - let mut names: Vec<_> = std::fs::read_dir(bundle.path()) + let names: Vec<_> = std::fs::read_dir(bundle.path()) .unwrap() .map(|entry| entry.unwrap().file_name()) .collect(); - names.sort(); - assert_eq!(names, [CONFIG, PROGRAM_BINARY]); + assert_eq!(names, [PROGRAM_BINARY]); assert!(program(&dir.path().join("missing")).is_err()); } diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index f427f5d5ef..e02245854d 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -42,6 +42,7 @@ const READY_SLACK: Duration = Duration::from_mins(1); const NEXTEST_TEST_FAILED: i32 = 100; /// nextest's exit code when `--no-tests fail` found no tests to run. const NEXTEST_NO_TESTS_RUN: i32 = 4; +const PROGRAM_TEST_FAILED: i32 = 1; /// How much of the end of the nextest log to print after a failure. nextest /// ends its output with a summary that names the failed tests. const LOG_TAIL_LINES: usize = 40; @@ -99,6 +100,17 @@ impl Status { )), } } + + fn of_program(status: ExitStatus, log: &Path) -> Self { + match status.code() { + Some(0) => Self::Passed, + Some(PROGRAM_TEST_FAILED) => Self::Failed, + _ => Self::Error(format!( + "the test program exited with {status}; see {}", + log.display() + )), + } + } } impl fmt::Display for Status { @@ -123,7 +135,7 @@ pub struct Run<'a> { /// Narrowing the tests in the bundle: nextest filtersets (`-E`) for a /// nextest bundle, parts of test names for a program bundle. pub filters: &'a [String], - /// Concurrency override for nextest. + /// Concurrency override for the test runner. pub test_threads: Option, /// Where `junit.xml`, `nextest.log` and, after a failure, the guest's /// `diagnostics/` go. @@ -390,28 +402,23 @@ async fn run_selected( let archive = format!("{guest}/tests.tar.zst"); let extract = format!("{guest}/extract"); let config = format!("{guest}/nextest.toml"); - let test_threads = run - .test_threads - .map_or(1, std::num::NonZeroUsize::get) - .to_string(); - let metadata = format!("{guest}/metadata"); - let cargo_metadata = format!("{metadata}/cargo-metadata.json"); - let binaries_metadata = format!("{metadata}/binaries-metadata.json"); + let test_threads = run.test_threads.map(|count| count.to_string()); + let junit = format!("{guest}/junit.xml"); let export = test_env::export_script(test_env::ENV_DIR); let mut args: Vec<&str> = vec!["--config-file", &config, "--profile", PROFILE]; let env_args = std::iter::once("env").chain(env.iter().map(String::as_str)); let mut tests: Vec<_> = env_args.clone().collect(); - tests.extend([ - "cargo-nextest", - "nextest", - "run", - "--test-threads", - &test_threads, - "--no-tests", - "fail", - ]); match kind { Kind::Nextest => { + tests.extend([ + "cargo-nextest", + "nextest", + "run", + "--test-threads", + test_threads.as_deref().unwrap_or("1"), + "--no-tests", + "fail", + ]); args.extend([ "--archive-file", &archive, @@ -427,35 +434,19 @@ async fn run_selected( if run.test_threads.is_none_or(|count| count.get() == 1) { tests.push("--no-capture"); } + tests.extend(&args); } Kind::Program => { - checked( - "write nextest metadata", - session - .exec(&[&program, "nextest-metadata", &metadata]) - .await?, - )?; - args.extend([ - "--cargo-metadata", - &cargo_metadata, - "--binaries-metadata", - &binaries_metadata, - ]); - tests.extend([ - "--no-fail-fast", - "--success-output", - "immediate", - "--failure-output", - "immediate", - ]); + tests.extend([program.as_str(), "run", "--junit", &junit]); + if let Some(count) = &test_threads { + tests.extend(["--test-threads", count]); + } + if !filters.is_empty() { + tests.push("--"); + tests.extend(filters.iter().map(String::as_str)); + } } } - tests.extend(&args); - // Prebuilt programs keep substring filters, unlike archive filtersets. - if kind == Kind::Program && !filters.is_empty() { - tests.push("--"); - tests.extend(filters.iter().map(String::as_str)); - } // nextest writes its output to a file in the guest, so a run that times // out or loses SSH still leaves a log for `collect_results`. The guest // shell exports the published variables itself, so their values, which @@ -491,7 +482,10 @@ async fn run_selected( } } let log = run.results.join(NEXTEST_LOG); - Ok(Status::of_nextest(output.status, &log)) + Ok(match kind { + Kind::Nextest => Status::of_nextest(output.status, &log), + Kind::Program => Status::of_program(output.status, &log), + }) } /// Copy the nextest log and the JUnit report out of the guest, whether or not @@ -651,6 +645,14 @@ mod tests { assert!(matches!(status(1), Status::Error(_))); } + #[test] + fn status_follows_the_program_exit_code() { + let status = |code| Status::of_program(ExitStatus::from_raw(code << 8), Path::new("log")); + assert_eq!(status(0), Status::Passed); + assert_eq!(status(1), Status::Failed); + assert!(matches!(status(2), Status::Error(_))); + } + #[test] fn k3s_diagnostics_keep_everything_the_old_playbook_collected() { for wanted in [ diff --git a/tests/runner/src/main.rs b/tests/runner/src/main.rs index 5f9f7c032c..cc6facdf42 100644 --- a/tests/runner/src/main.rs +++ b/tests/runner/src/main.rs @@ -85,7 +85,8 @@ struct RunArgs { /// the guest's architecture (a `*-unknown-linux-musl` build). #[arg(long, value_name = "PATH", conflicts_with = "packages")] program: Option, - /// Maximum number of tests nextest runs at once [default: 1]. + /// Maximum number of concurrent tests [default: 1]. + /// With `--program`, the program must support `run --test-threads`. #[arg(long, value_name = "N")] test_threads: Option, /// The gateway name the installer registers with the CLI. The packaged diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 76506381c3..7ea9cc5e38 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -539,7 +539,9 @@ dependencies = [ name = "conformance" version = "0.0.0" dependencies = [ + "clap", "host-server-support", + "libc", "openshell-crypto", "openshell-testkit", "serde_json", diff --git a/tests/suites/conformance/Cargo.toml b/tests/suites/conformance/Cargo.toml index 4ae6c7e902..a7749c1427 100644 --- a/tests/suites/conformance/Cargo.toml +++ b/tests/suites/conformance/Cargo.toml @@ -31,4 +31,9 @@ serde_json = "1" tempfile = "3" tokio = { version = "1", features = ["process", "time"] } +[target.'cfg(unix)'.dependencies] +clap = { version = "4", features = ["derive"] } +libc = "0.2" +tokio = { version = "1", features = ["signal"] } + [workspace] diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index 9a0922f05c..8cc9b15fd9 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -68,6 +68,24 @@ Feature and driver suites are not part of it. The and exit codes. `tasks/scripts/check-conformance-program.sh` checks that it lists the same tests as nextest. +Branch E2E builds a single executable with nextest bundled inside. Use +`openshell-conformance run --test-threads 4 --junit conformance.xml` to run +that build in parallel. The default is one worker. No separately installed +nextest is required. Plain Cargo builds run serially. + +To build the bundled executable, use the repository development shell: + +```shell +bash tests/suites/conformance/package.sh +``` + +The bundled scheduler runs from a private temporary directory. Tests use +that workspace as their working directory; use absolute paths for custom +CLI and gateway configuration paths. +An interrupted or timed-out test cannot clean up its gateway resources. +Nextest may leave a descendant running if it ignores termination and the +test process exits first. + See [Unsupported tests](../../testkit/README.md#unsupported-tests) to skip a test in specific CI environments. diff --git a/tests/suites/conformance/build.rs b/tests/suites/conformance/build.rs new file mode 100644 index 0000000000..48d047277e --- /dev/null +++ b/tests/suites/conformance/build.rs @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +fn main() { + println!("cargo::rustc-check-cfg=cfg(conformance_bundle)"); + println!("cargo::rerun-if-env-changed=OPENSHELL_CONFORMANCE_BUNDLE"); + println!("cargo::rerun-if-changed=build.rs"); + if std::env::var_os("OPENSHELL_CONFORMANCE_BUNDLE").is_some() { + println!("cargo::rustc-cfg=conformance_bundle"); + } +} diff --git a/tests/suites/conformance/package.sh b/tests/suites/conformance/package.sh new file mode 100644 index 0000000000..aabaa10b5d --- /dev/null +++ b/tests/suites/conformance/package.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Package the conformance executable with its own nextest scheduler. +set -euo pipefail + +if [[ $# != 2 ]]; then + echo "Usage: $0 " >&2 + exit 2 +fi +target=$1 +mkdir -p "$2" +out=$(cd "$2" && pwd) +manifest="$(cd "$(dirname "$0")" && pwd)/Cargo.toml" +version=0.9.143 +case "$target" in + aarch64-apple-darwin|x86_64-apple-darwin) + upstream=universal-apple-darwin + sha=4830d430411148d17602a75cc880bfb4dc8dac153dea59a48a2ef4cc93577f07 + ;; + aarch64-unknown-linux-musl) + upstream=$target + sha=0560ce0ce017f368c54b5db86588370fc03b470985490fa81200e62a657dda05 + ;; + x86_64-unknown-linux-musl) + upstream=$target + sha=6d891c18105ec2d33f6e441a4f92b7ccab47ba263e22055c8bb66884243f3389 + ;; + *) + echo "Unsupported prototype target: $target" >&2 + exit 2 + ;; +esac + +if [[ $(cargo nextest --version | awk '$1 == "release:" {print $2}') != "$version" ]]; then + echo "Build requires cargo-nextest $version" >&2 + exit 2 +fi + +work=$(mktemp -d "${TMPDIR:-/tmp}/conformance-package.XXXXXXXX") +trap 'rm -r -- "$work"' EXIT +work=$(cd "$work" && pwd -P) +export CARGO_PROFILE_RELEASE_STRIP=symbols +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-${manifest%/*}/target}" +unset OPENSHELL_CONFORMANCE_BUNDLE + +asset="cargo-nextest-$version-$upstream.tar.gz" +curl -fsSL "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-$version/$asset" -o "$work/$asset" +printf '%s %s\n' "$sha" "$work/$asset" | shasum -a 256 -c - +tar -xOzf "$work/$asset" cargo-nextest > "$work/nextest-upstream" +if [[ $upstream == universal-apple-darwin ]]; then + arch=${target%%-*} + lipo -thin "${arch/aarch64/arm64}" "$work/nextest-upstream" -output "$work/cargo-nextest" + codesign --verify "$work/cargo-nextest" +else + mv "$work/nextest-upstream" "$work/cargo-nextest" +fi + +build=(--locked --release --manifest-path "$manifest" --target "$target") +cargo nextest archive "${build[@]}" --bin openshell-conformance --archive-file "$work/suite.tar.zst" +# Keep the archive off the runtime path: it contains the test executable, +# build outputs, and sometimes a Rust sysroot. Carry only the generated JSON. +for name in cargo-metadata.json binaries-metadata.json; do + zstd -dc "$work/suite.tar.zst" | tar -xOf - "target/nextest/$name" > "$work/$name" +done +jq -er ' + .["rust-build-meta"]["target-directory"] as $target | + .["rust-binaries"] | to_entries | + if length != 1 or .[0].key != "conformance::bin/openshell-conformance" + then error("expected one conformance test binary") else .[0].value["binary-path"] end | + if startswith($target + "/") then ltrimstr($target + "/") + else error("test binary is outside the target directory") end | + select(test("^[A-Za-z0-9_/-]+$") and (split("/") | all(length > 0))) +' "$work/binaries-metadata.json" > "$work/binary-path" + +export OPENSHELL_CONFORMANCE_BUNDLE="$work" +cargo build "${build[@]}" --bin openshell-conformance +cp "$CARGO_TARGET_DIR/$target/release/openshell-conformance" "$out/" +wc -c "$out/openshell-conformance" diff --git a/tests/suites/conformance/src/bundled.rs b/tests/suites/conformance/src/bundled.rs new file mode 100644 index 0000000000..48c7673aaf --- /dev/null +++ b/tests/suites/conformance/src/bundled.rs @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Reuse nextest's build metadata with this executable as +//! the only test binary. Never enter this scheduler for libtest invocations. + +use std::env; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write as _}; +use std::os::unix::fs::{OpenOptionsExt as _, symlink}; +use std::path::{Path, PathBuf}; +use std::process::{ExitCode, Stdio}; +use std::time::Duration; + +use clap::Parser; +use tokio::process::Command; +use tokio::signal::unix::{SignalKind, signal}; + +macro_rules! payload { + ($name:literal) => { + concat!(env!("OPENSHELL_CONFORMANCE_BUNDLE"), "/", $name) + }; +} + +#[derive(Parser)] +#[command( + name = "openshell-conformance run", + about = "Run tests with bundled nextest" +)] +struct Run { + /// Run tests whose name contains any of these. + filters: Vec, + /// Run ignored tests too. + #[arg(long)] + include_ignored: bool, + /// Maximum concurrent tests. Use more than one only on a suitable gateway. + #[arg(long, default_value = "1", value_parser = clap::value_parser!(u32).range(1..))] + test_threads: u32, + /// Stop each test after this many seconds. + #[arg(long, default_value = "900", value_parser = seconds)] + timeout: Duration, + /// Grace period before forcibly killing a stopped test, in seconds. + #[arg(long, default_value = "10", value_parser = seconds)] + grace: Duration, + /// Write a JUnit report here. + #[arg(long, value_name = "PATH")] + junit: Option, +} + +fn seconds(value: &str) -> Result { + value + .parse::() + .ok() + .and_then(|value| Duration::try_from_secs_f64(value).ok()) + .filter(|value| !value.is_zero()) + .ok_or("expected positive, finite seconds") +} + +// Keep the payload out of the async state machine, which otherwise embeds +// identical byte strings in multiple optimized paths. +#[inline(never)] +fn materialize(root: &Path) -> io::Result<()> { + fs::write(root.join("Cargo.toml"), "[workspace]\n")?; + fs::write( + root.join("cargo-metadata.json"), + include_bytes!(payload!("cargo-metadata.json")), + )?; + fs::write( + root.join("binaries-metadata.json"), + include_bytes!(payload!("binaries-metadata.json")), + )?; + // Close the writable descriptor before executing (Linux rejects ETXTBSY). + OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o700) + .open(root.join("cargo-nextest"))? + .write_all(include_bytes!(payload!("cargo-nextest")))?; + Ok(()) +} + +pub(crate) fn dispatch() -> Option { + let mut args = env::args_os().skip(1); + if args.next()?.as_os_str() != "run" { + return None; + } + let options = match Run::try_parse_from(std::iter::once("run".into()).chain(args)) { + Ok(options) => options, + Err(error) => { + let _ = error.print(); + return Some(ExitCode::from(if error.use_stderr() { 2 } else { 0 })); + } + }; + let result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .and_then(|runtime| runtime.block_on(run(options))); + Some(match result { + Ok(code) => ExitCode::from(code), + Err(error) => { + eprintln!("openshell-conformance: bundled nextest: {error}"); + ExitCode::from(2) + } + }) +} + +async fn run(options: Run) -> io::Result { + let mut int = signal(SignalKind::interrupt())?; + let mut term = signal(SignalKind::terminate())?; + let mut hup = signal(SignalKind::hangup())?; + + let temp = tempfile::Builder::new() + .prefix("openshell-conformance-") + .tempdir()?; + let root = temp.path().canonicalize()?; + let target = root.join("target"); + let binary = target.join(include_str!(payload!("binary-path")).trim_end()); + fs::create_dir_all(binary.parent().expect("test binary has a parent"))?; + symlink(env::current_exe()?, &binary)?; + + materialize(&root)?; + + let config = root.join("nextest.toml"); + let report = root.join("target/nextest/default/junit.xml"); + let mut profile = format!( + "[profile.default]\n\ + slow-timeout = {{ period = \"{}ns\", terminate-after = 1, grace-period = \"{}ns\" }}\n", + options.timeout.as_nanos(), + options.grace.as_nanos() + ); + if options.junit.is_some() { + profile.push_str( + "[profile.default.junit]\npath = \"junit.xml\"\nreport-skipped = \"ignored\"\nstore-success-output = true\n", + ); + } + fs::write(&config, profile)?; + + let mut command = Command::new(root.join("cargo-nextest")); + command + .args(["nextest", "run", "--cargo-metadata"]) + .arg(root.join("cargo-metadata.json")) + .arg("--binaries-metadata") + .arg(root.join("binaries-metadata.json")) + .arg("--workspace-remap") + .arg(&root) + .arg("--target-dir-remap") + .arg(&target) + .arg("--config-file") + .arg(config) + .args([ + "--user-config-file", + "none", + "--no-input-handler", + "--no-pager", + "--profile", + "default", + "--no-fail-fast", + "--retries", + "0", + "--no-tests", + "fail", + "--success-output", + "immediate", + "--failure-output", + "immediate", + "--test-threads", + ]) + .arg(options.test_threads.to_string()) + .args([ + "--run-ignored", + if options.include_ignored { + "all" + } else { + "default" + }, + ]) + .arg("--") + .args(options.filters) + .current_dir(&root) + .stdin(Stdio::null()) + // The terminal sends Ctrl-C to us, not to nextest too. Nextest owns + // the test process groups, so forward to the runner and let it reap. + .process_group(0); + let mut child = command.spawn().map_err(|error| { + io::Error::other(format!("start runner under {}: {error}", root.display())) + })?; + let pid = child.id().expect("spawned child has an ID") as libc::pid_t; + let mut interrupted = false; + let status = loop { + let sig = tokio::select! { + biased; + status = child.wait() => break status?, + _ = int.recv() => libc::SIGINT, + _ = term.recv() => libc::SIGTERM, + _ = hup.recv() => libc::SIGHUP, + }; + interrupted = true; + // SAFETY: `wait` did not reap the child, so its PID can't be reused. + unsafe { libc::kill(pid, sig) }; + }; + + if let Some(path) = options.junit { + // Setup/discovery errors can occur before nextest creates a report. + if report.try_exists()? { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + fs::copy(report, &path) + .map_err(|error| io::Error::other(format!("write {}: {error}", path.display())))?; + } else if status.success() && !interrupted { + return Err(io::Error::other( + "nextest did not write the requested report", + )); + } + } + + // Keep the testkit `run` exit contract rather than exposing nextest codes. + Ok(match (interrupted, status.code()) { + (false, Some(0)) => 0, + (false, Some(100)) => 1, + _ => 2, + }) +} diff --git a/tests/suites/conformance/src/main.rs b/tests/suites/conformance/src/main.rs index 8334cfd3e1..23814d84c6 100644 --- a/tests/suites/conformance/src/main.rs +++ b/tests/suites/conformance/src/main.rs @@ -13,6 +13,13 @@ use std::process::ExitCode; // missing. use conformance as _; +#[cfg(all(unix, conformance_bundle))] +mod bundled; + fn main() -> ExitCode { - testkit::program::main_for(env!("CARGO_PKG_NAME"), env!("CARGO_BIN_NAME")) + #[cfg(all(unix, conformance_bundle))] + if let Some(status) = bundled::dispatch() { + return status; + } + testkit::main() } diff --git a/tests/testkit/README.md b/tests/testkit/README.md index e15c38f18a..5f35689d32 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -230,7 +230,6 @@ program for the conformance suite; see | `list [FILTER]...` | Prints each test's name and description. Ignored tests are included and marked. | | `ready [--timeout SECS]` | Waits for the gateway, like `testkit-ready` (default 60 seconds). Exits 2 if it is not ready in time. | | `run [FILTER]...` | Runs the tests one at a time, each in its own process. Unix only. | -| `nextest-metadata DIR` | Writes a stub manifest and JSON metadata describing the prebuilt executable. | A filter selects tests whose name contains it. `run` also takes: @@ -260,18 +259,6 @@ test target with `harness = false` therefore also runs under `cargo test` and nextest. In that mode tests run in one process, one at a time unless `--test-threads` says otherwise. -To run a prebuilt program with nextest (no Cargo or checkout required), write -metadata to a fresh directory on the machine where the program will run: - -```shell -openshell-conformance nextest-metadata metadata -cargo-nextest nextest run --cargo-metadata metadata/cargo-metadata.json \ - --binaries-metadata metadata/binaries-metadata.json --test-threads 4 -``` - -The metadata refers to the binary's absolute path. Regenerate it if the -binary moves. - A test's name is its module path without the crate name, then its function name, as in nextest. Its family, which groups tests in the JUnit report, is the first directory under the last `suites` directory in the crate's path: diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index dedd5d2e12..eb1db6c4d3 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -12,14 +12,12 @@ //! } //! ``` //! -//! Its subcommands: +//! It has three subcommands: //! //! - `list [FILTER]...` prints each test's name and description. //! - `ready [--timeout SECS]` waits for the gateway, as `testkit-ready` does. //! - `run [FILTER]...` runs tests one at a time, each in its own process with //! a timeout, and can write a `JUnit` report. Unix only. -//! - `nextest-metadata DIR` describes the executable to nextest, so it can -//! run the prebuilt program without Cargo. //! //! Any other arguments are libtest's, so the program also works as a //! `harness = false` test target under `cargo test` and nextest: it answers @@ -35,7 +33,6 @@ mod capture; #[cfg(unix)] mod junit; -mod nextest; #[cfg(unix)] mod process; #[cfg(unix)] @@ -65,19 +62,9 @@ pub fn main() -> ExitCode { main_with(&TESTS) } -/// Run a suite program with the package and binary names it has under Cargo. -/// These names are used by `nextest-metadata`, even if the executable is renamed. -pub fn main_for(package: &str, binary: &str) -> ExitCode { - dispatch(&TESTS, Some((package, binary))) -} - /// [`main`] over `tests` instead of every registered test. #[doc(hidden)] pub fn main_with(tests: &'static [Test]) -> ExitCode { - dispatch(tests, None) -} - -fn dispatch(tests: &'static [Test], identity: Option<(&str, &str)>) -> ExitCode { let args: Vec = std::env::args_os().collect(); let program = program_name(&args); // A suite crate that the program never names is not linked, and its @@ -109,7 +96,7 @@ fn dispatch(tests: &'static [Test], identity: Option<(&str, &str)>) -> ExitCode return ExitCode::from(if error.use_stderr() { ERROR_EXIT } else { 0 }); } }; - command(&program, tests, unsupported, cli.command, identity) + command(&program, tests, unsupported, cli.command) } else { libtest(tests, unsupported, args) } @@ -131,11 +118,6 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// Write metadata to run the prebuilt executable with cargo-nextest. - NextestMetadata { - #[arg(value_name = "DIR")] - dir: PathBuf, - }, /// Print each test's name and description, including ignored tests. List { /// Show tests whose name contains any of these (all if none). @@ -185,23 +167,8 @@ fn command( tests: &'static [Test], unsupported: Unsupported, command: Command, - identity: Option<(&str, &str)>, ) -> ExitCode { match command { - Command::NextestMetadata { dir } => { - let package = tests[0].package(); - let (package, binary) = identity.unwrap_or((package, program)); - match nextest::write(&dir, package, binary) { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!( - "{program}: write nextest metadata to {}: {error}", - dir.display() - ); - ExitCode::from(ERROR_EXIT) - } - } - } Command::List { filters } => { list(tests, &unsupported, filters); ExitCode::SUCCESS diff --git a/tests/testkit/testkit/src/program/nextest.rs b/tests/testkit/testkit/src/program/nextest.rs deleted file mode 100644 index ccca4a9c97..0000000000 --- a/tests/testkit/testkit/src/program/nextest.rs +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The Cargo and binary metadata nextest reads instead of building the suite. - -use std::fs::{self, OpenOptions}; -use std::io::{self, Write as _}; -use std::path::Path; - -use serde_json::json; - -pub fn write(dir: &Path, package: &str, binary: &str) -> io::Result<()> { - let exe = std::env::current_exe()?; - fs::create_dir_all(dir)?; - let dir = dir.canonicalize()?; - let manifest = dir.join("Cargo.toml"); - let target = dir.join("target"); - let package_id = format!("{package} 0.0.0"); - let binary_id = format!("{package}::bin/{binary}"); - - // The manifest identifies the workspace. Nextest reads the JSON rather - // than invoking Cargo, and the only test target is the running binary. - let cargo = json!({ - "packages": [{ - "name": package, "version": "0.0.0", "id": package_id, - "manifest_path": manifest, - "authors": [], "categories": [], "keywords": [], - "dependencies": [], "features": {}, - "targets": [{ - "name": binary, "kind": ["bin"], "crate_types": ["bin"], - "src_path": exe, "edition": "2024", "test": true - }], - "edition": "2024" - }], - "workspace_members": [package_id], - "workspace_default_members": [package_id], - "target_directory": target, - "workspace_root": dir, - "version": 1 - }); - // Omitting platforms lets nextest use its own native target when rustc - // isn't installed. The executable is already runnable on this machine. - let binaries = json!({ - "rust-build-meta": { - "target-directory": target, - "base-output-directories": [], - "non-test-binaries": {}, - "linked-paths": [] - }, - "rust-binaries": { - binary_id.clone(): { - "binary-id": binary_id, "binary-name": binary, - "package-id": package_id, "kind": "bin", - "binary-path": exe, "build-platform": "target" - } - } - }); - let create = |name| { - OpenOptions::new() - .write(true) - .create_new(true) - .open(dir.join(name)) - }; - writeln!( - create("Cargo.toml")?, - "[package]\nname = {package:?}\nversion = \"0.0.0\"" - )?; - serde_json::to_writer(create("cargo-metadata.json")?, &cargo)?; - serde_json::to_writer(create("binaries-metadata.json")?, &binaries)?; - Ok(()) -} diff --git a/tests/testkit/testkit/src/registry.rs b/tests/testkit/testkit/src/registry.rs index a4e9e6431d..b5c6252306 100644 --- a/tests/testkit/testkit/src/registry.rs +++ b/tests/testkit/testkit/src/registry.rs @@ -59,7 +59,7 @@ impl Test { /// Names a test cannot have at the top level: the program would read them as /// its own subcommands, so nextest could not run the test by name. -pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run", "nextest-metadata"]; +pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run"]; /// Check the tests can be told apart by name. pub fn validate(tests: &[Test]) -> Result<(), String> { From fc3d03232f1cb28d91335d83410e6e55de372add Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 09:07:21 -0800 Subject: [PATCH 06/14] refactor(conformance): pass scheduler options directly to nextest Signed-off-by: Matthew Grossman --- .github/workflows/branch-e2e.yml | 15 ++- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-kubernetes-test.yml | 2 +- .github/workflows/e2e-podman-test.yml | 2 +- .github/workflows/e2e-vm-test.yml | 2 + TESTING.md | 10 +- e2e/support/conformance.sh | 14 ++- tests/runner/src/execute.rs | 32 +----- tests/runner/src/main.rs | 5 +- tests/suites/conformance/Cargo.lock | 1 - tests/suites/conformance/Cargo.toml | 1 - tests/suites/conformance/README.md | 4 +- tests/suites/conformance/package.sh | 9 +- tests/suites/conformance/src/bundled.rs | 103 ++++-------------- tests/suites/conformance/src/main.rs | 5 +- tests/testkit/README.md | 3 + tests/testkit/testkit/src/program/mod.rs | 121 +++++++++++++++------- 17 files changed, 155 insertions(+), 176 deletions(-) diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 6456521076..3f014c3581 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -219,12 +219,19 @@ jobs: # Fails if the program has no tests linked. "$binary" list # Exercise the packaged scheduler, not just the discovery interface. - PATH=/usr/bin:/bin "$binary" run --help | grep -- --test-threads status=0 - PATH=/usr/bin:/bin "$binary" run -- __conformance_smoke_no_match__ >"$RUNNER_TEMP/conformance-smoke.log" 2>&1 || status=$? - cat "$RUNNER_TEMP/conformance-smoke.log" + PATH=/usr/bin:/bin "$binary" run -- --no-tests fail __conformance_smoke_no_match__ || status=$? + test "$status" = 4 + # A successful nextest invocation that did not run tests has no report. + status=0 + PATH=/usr/bin:/bin "$binary" run --junit "$RUNNER_TEMP/conformance.xml" -- --no-run || status=$? test "$status" = 2 - grep -F 'no tests to run' "$RUNNER_TEMP/conformance-smoke.log" + test ! -e "$RUNNER_TEMP/conformance.xml" + status=0 + PATH=/usr/bin:/bin OPENSHELL_GATEWAY_ENDPOINT=http://127.0.0.1:1 \ + "$binary" run --junit "$RUNNER_TEMP/conformance.xml" -- -j 2 -E 'test(=smoke::create_exec_delete)' || status=$? + test "$status" = 100 + test -s "$RUNNER_TEMP/conformance.xml" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: openshell-conformance-${{ matrix.triple }} diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 4d64132e50..67e19fa050 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,6 +107,6 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} + OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index f9f3e911c5..84ce83197b 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,7 +163,7 @@ jobs: - name: Run Kubernetes E2E env: - OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} + OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index 9ea928abe9..360d6f41aa 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -84,7 +84,7 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_THREADS: ${{ inputs.prebuilt-conformance && '4' || '' }} + OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index 82d86058b8..b27ecf8c86 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,6 +64,8 @@ jobs: - name: Run tests env: + # Parallel provisioning failed in the VM host lanes; keep them serial. + OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 1" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index 2c4e4ca8ba..04e250159a 100644 --- a/TESTING.md +++ b/TESTING.md @@ -262,7 +262,7 @@ and `nextest.log` to the results directory. Branch E2E builds `openshell-conformance` once and passes it to every conformance row this way. `--test-threads N` runs up to N tests concurrently in the guest, whether the runner builds the suite or uses `--bundle` or `--program`. The default -is one. With `--program`, the binary must support `run --test-threads`. +is one. With `--program`, use a binary that bundles nextest. CI rows can opt in with `test_threads`. `openshell-test-runner build --family --out ` builds a family's @@ -524,9 +524,11 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. Branch E2E packages `openshell-conformance` with nextest, so `run` can -schedule tests without an installed nextest. Set `OPENSHELL_TESTKIT_THREADS` -to change the worker count when using that artifact. Plain Cargo builds -support the same `run` command, but are serial. +schedule tests without an installed nextest. With a bundled binary, pass +nextest options after `--`, for example `run -- --test-threads 4`. The +driver wrappers accept whitespace-separated options in +`OPENSHELL_CONFORMANCE_NEXTEST_ARGS` when using a prebuilt binary. Plain +Cargo builds run serially. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index d4abd8914b..8f70507579 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -64,6 +64,7 @@ e2e_openshell_conformance_bin() { # to OPENSHELL_CONFORMANCE_JUNIT, else results/conformance-.xml. e2e_run_openshell_conformance() { local gateway_label=${1:-OpenShell} + if (($#)); then shift; fi local root program junit root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -85,12 +86,19 @@ e2e_run_openshell_conformance() { echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return local args=(--junit "${junit}") - if [[ -n "${OPENSHELL_TESTKIT_THREADS:-}" ]]; then - args+=(--test-threads "${OPENSHELL_TESTKIT_THREADS}") + if [[ -n "${OPENSHELL_CONFORMANCE_BIN:-}" && -n "${OPENSHELL_CONFORMANCE_NEXTEST_ARGS:-}" ]]; then + local -a nextest_args + # Simple whitespace-separated CI flags. Callers with quoted values can + # pass them as arguments to this function instead. + read -r -a nextest_args <<< "${OPENSHELL_CONFORMANCE_NEXTEST_ARGS}" + set -- "${nextest_args[@]}" "$@" + fi + if (($#)); then + args+=(-- "$@") fi "${program}" run "${args[@]}" } if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then - e2e_run_openshell_conformance + e2e_run_openshell_conformance OpenShell "$@" fi diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index e02245854d..fc7514ae46 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -42,7 +42,6 @@ const READY_SLACK: Duration = Duration::from_mins(1); const NEXTEST_TEST_FAILED: i32 = 100; /// nextest's exit code when `--no-tests fail` found no tests to run. const NEXTEST_NO_TESTS_RUN: i32 = 4; -const PROGRAM_TEST_FAILED: i32 = 1; /// How much of the end of the nextest log to print after a failure. nextest /// ends its output with a summary that names the failed tests. const LOG_TAIL_LINES: usize = 40; @@ -100,17 +99,6 @@ impl Status { )), } } - - fn of_program(status: ExitStatus, log: &Path) -> Self { - match status.code() { - Some(0) => Self::Passed, - Some(PROGRAM_TEST_FAILED) => Self::Failed, - _ => Self::Error(format!( - "the test program exited with {status}; see {}", - log.display() - )), - } - } } impl fmt::Display for Status { @@ -438,12 +426,9 @@ async fn run_selected( } Kind::Program => { tests.extend([program.as_str(), "run", "--junit", &junit]); + tests.extend(filters.iter().map(String::as_str)); if let Some(count) = &test_threads { - tests.extend(["--test-threads", count]); - } - if !filters.is_empty() { - tests.push("--"); - tests.extend(filters.iter().map(String::as_str)); + tests.extend(["--", "--test-threads", count]); } } } @@ -482,10 +467,7 @@ async fn run_selected( } } let log = run.results.join(NEXTEST_LOG); - Ok(match kind { - Kind::Nextest => Status::of_nextest(output.status, &log), - Kind::Program => Status::of_program(output.status, &log), - }) + Ok(Status::of_nextest(output.status, &log)) } /// Copy the nextest log and the JUnit report out of the guest, whether or not @@ -645,14 +627,6 @@ mod tests { assert!(matches!(status(1), Status::Error(_))); } - #[test] - fn status_follows_the_program_exit_code() { - let status = |code| Status::of_program(ExitStatus::from_raw(code << 8), Path::new("log")); - assert_eq!(status(0), Status::Passed); - assert_eq!(status(1), Status::Failed); - assert!(matches!(status(2), Status::Error(_))); - } - #[test] fn k3s_diagnostics_keep_everything_the_old_playbook_collected() { for wanted in [ diff --git a/tests/runner/src/main.rs b/tests/runner/src/main.rs index cc6facdf42..4f8f751fbc 100644 --- a/tests/runner/src/main.rs +++ b/tests/runner/src/main.rs @@ -81,12 +81,11 @@ struct RunArgs { #[arg(long, value_name = "DIR", conflicts_with = "program")] bundle: Option, /// Run this prebuilt testkit program, such as `openshell-conformance`, - /// instead of building the family's tests. It must be a static binary for - /// the guest's architecture (a `*-unknown-linux-musl` build). + /// instead of building the family's tests. It must bundle nextest and + /// be a static binary for the guest's architecture. #[arg(long, value_name = "PATH", conflicts_with = "packages")] program: Option, /// Maximum number of concurrent tests [default: 1]. - /// With `--program`, the program must support `run --test-threads`. #[arg(long, value_name = "N")] test_threads: Option, /// The gateway name the installer registers with the CLI. The packaged diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 7ea9cc5e38..8d8de8aa9d 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -539,7 +539,6 @@ dependencies = [ name = "conformance" version = "0.0.0" dependencies = [ - "clap", "host-server-support", "libc", "openshell-crypto", diff --git a/tests/suites/conformance/Cargo.toml b/tests/suites/conformance/Cargo.toml index a7749c1427..d193da59e3 100644 --- a/tests/suites/conformance/Cargo.toml +++ b/tests/suites/conformance/Cargo.toml @@ -32,7 +32,6 @@ tempfile = "3" tokio = { version = "1", features = ["process", "time"] } [target.'cfg(unix)'.dependencies] -clap = { version = "4", features = ["derive"] } libc = "0.2" tokio = { version = "1", features = ["signal"] } diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index 8cc9b15fd9..e7a5d89996 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -69,9 +69,11 @@ and exit codes. `tasks/scripts/check-conformance-program.sh` checks that it lists the same tests as nextest. Branch E2E builds a single executable with nextest bundled inside. Use -`openshell-conformance run --test-threads 4 --junit conformance.xml` to run +`openshell-conformance run --junit conformance.xml -- --test-threads 4` to run that build in parallel. The default is one worker. No separately installed nextest is required. Plain Cargo builds run serially. +On bundled builds, arguments after `--` go to nextest (see `run -- --help`), +and `run` returns nextest's exit status. To build the bundled executable, use the repository development shell: diff --git a/tests/suites/conformance/package.sh b/tests/suites/conformance/package.sh index aabaa10b5d..ae5f75777f 100644 --- a/tests/suites/conformance/package.sh +++ b/tests/suites/conformance/package.sh @@ -13,6 +13,8 @@ target=$1 mkdir -p "$2" out=$(cd "$2" && pwd) manifest="$(cd "$(dirname "$0")" && pwd)/Cargo.toml" +# Keep this release and its checksums in sync with the cargo-nextest pin in +# mise.toml and the version provided by the Nix dev shell (flake.nix). version=0.9.143 case "$target" in aarch64-apple-darwin|x86_64-apple-darwin) @@ -28,7 +30,7 @@ case "$target" in sha=6d891c18105ec2d33f6e441a4f92b7ccab47ba263e22055c8bb66884243f3389 ;; *) - echo "Unsupported prototype target: $target" >&2 + echo "Unsupported conformance bundle target: $target (arm64 or x86-64, macOS or Linux musl)" >&2 exit 2 ;; esac @@ -59,8 +61,9 @@ fi build=(--locked --release --manifest-path "$manifest" --target "$target") cargo nextest archive "${build[@]}" --bin openshell-conformance --archive-file "$work/suite.tar.zst" -# Keep the archive off the runtime path: it contains the test executable, -# build outputs, and sometimes a Rust sysroot. Carry only the generated JSON. +# Discard the archive's unbundled test executable. The metadata still names +# its target-relative path; at runtime a symlink there points to the final +# bundled executable, which exposes the same test harness. for name in cargo-metadata.json binaries-metadata.json; do zstd -dc "$work/suite.tar.zst" | tar -xOf - "target/nextest/$name" > "$work/$name" done diff --git a/tests/suites/conformance/src/bundled.rs b/tests/suites/conformance/src/bundled.rs index 48c7673aaf..831c990bcf 100644 --- a/tests/suites/conformance/src/bundled.rs +++ b/tests/suites/conformance/src/bundled.rs @@ -9,10 +9,9 @@ use std::fs::{self, OpenOptions}; use std::io::{self, Write as _}; use std::os::unix::fs::{OpenOptionsExt as _, symlink}; use std::path::{Path, PathBuf}; -use std::process::{ExitCode, Stdio}; -use std::time::Duration; +use std::process::{ExitCode, ExitStatus, Stdio}; -use clap::Parser; +use testkit::program::RunOptions; use tokio::process::Command; use tokio::signal::unix::{SignalKind, signal}; @@ -22,40 +21,6 @@ macro_rules! payload { }; } -#[derive(Parser)] -#[command( - name = "openshell-conformance run", - about = "Run tests with bundled nextest" -)] -struct Run { - /// Run tests whose name contains any of these. - filters: Vec, - /// Run ignored tests too. - #[arg(long)] - include_ignored: bool, - /// Maximum concurrent tests. Use more than one only on a suitable gateway. - #[arg(long, default_value = "1", value_parser = clap::value_parser!(u32).range(1..))] - test_threads: u32, - /// Stop each test after this many seconds. - #[arg(long, default_value = "900", value_parser = seconds)] - timeout: Duration, - /// Grace period before forcibly killing a stopped test, in seconds. - #[arg(long, default_value = "10", value_parser = seconds)] - grace: Duration, - /// Write a JUnit report here. - #[arg(long, value_name = "PATH")] - junit: Option, -} - -fn seconds(value: &str) -> Result { - value - .parse::() - .ok() - .and_then(|value| Duration::try_from_secs_f64(value).ok()) - .filter(|value| !value.is_zero()) - .ok_or("expected positive, finite seconds") -} - // Keep the payload out of the async state machine, which otherwise embeds // identical byte strings in multiple optimized paths. #[inline(never)] @@ -79,32 +44,26 @@ fn materialize(root: &Path) -> io::Result<()> { Ok(()) } -pub(crate) fn dispatch() -> Option { - let mut args = env::args_os().skip(1); - if args.next()?.as_os_str() != "run" { - return None; - } - let options = match Run::try_parse_from(std::iter::once("run".into()).chain(args)) { - Ok(options) => options, - Err(error) => { - let _ = error.print(); - return Some(ExitCode::from(if error.use_stderr() { 2 } else { 0 })); - } - }; +pub(crate) fn run(options: RunOptions) -> ExitCode { let result = tokio::runtime::Builder::new_current_thread() .enable_all() .build() - .and_then(|runtime| runtime.block_on(run(options))); - Some(match result { - Ok(code) => ExitCode::from(code), + .and_then(|runtime| runtime.block_on(run_nextest(options))); + match result { + Ok(status) => ExitCode::from( + status + .code() + .and_then(|code| u8::try_from(code).ok()) + .unwrap_or(2), + ), Err(error) => { eprintln!("openshell-conformance: bundled nextest: {error}"); ExitCode::from(2) } - }) + } } -async fn run(options: Run) -> io::Result { +async fn run_nextest(options: RunOptions) -> io::Result { let mut int = signal(SignalKind::interrupt())?; let mut term = signal(SignalKind::terminate())?; let mut hup = signal(SignalKind::hangup())?; @@ -124,6 +83,10 @@ async fn run(options: Run) -> io::Result { let report = root.join("target/nextest/default/junit.xml"); let mut profile = format!( "[profile.default]\n\ + test-threads = 1\n\ + fail-fast = false\n\ + success-output = \"immediate\"\n\ + failure-output = \"immediate\"\n\ slow-timeout = {{ period = \"{}ns\", terminate-after = 1, grace-period = \"{}ns\" }}\n", options.timeout.as_nanos(), options.grace.as_nanos() @@ -154,33 +117,16 @@ async fn run(options: Run) -> io::Result { "--no-pager", "--profile", "default", - "--no-fail-fast", - "--retries", - "0", - "--no-tests", - "fail", - "--success-output", - "immediate", - "--failure-output", - "immediate", - "--test-threads", ]) - .arg(options.test_threads.to_string()) - .args([ - "--run-ignored", - if options.include_ignored { - "all" - } else { - "default" - }, - ]) - .arg("--") - .args(options.filters) .current_dir(&root) .stdin(Stdio::null()) // The terminal sends Ctrl-C to us, not to nextest too. Nextest owns // the test process groups, so forward to the runner and let it reap. .process_group(0); + if options.include_ignored { + command.args(["--run-ignored", "all"]); + } + command.args(options.nextest_args).args(options.filters); let mut child = command.spawn().map_err(|error| { io::Error::other(format!("start runner under {}: {error}", root.display())) })?; @@ -214,10 +160,5 @@ async fn run(options: Run) -> io::Result { } } - // Keep the testkit `run` exit contract rather than exposing nextest codes. - Ok(match (interrupted, status.code()) { - (false, Some(0)) => 0, - (false, Some(100)) => 1, - _ => 2, - }) + Ok(status) } diff --git a/tests/suites/conformance/src/main.rs b/tests/suites/conformance/src/main.rs index 23814d84c6..4dff7edcfc 100644 --- a/tests/suites/conformance/src/main.rs +++ b/tests/suites/conformance/src/main.rs @@ -18,8 +18,7 @@ mod bundled; fn main() -> ExitCode { #[cfg(all(unix, conformance_bundle))] - if let Some(status) = bundled::dispatch() { - return status; - } + return testkit::program::main_with_runner(bundled::run); + #[cfg(not(all(unix, conformance_bundle)))] testkit::main() } diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 5f35689d32..b7b6871685 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -239,6 +239,9 @@ A filter selects tests whose name contains it. `run` also takes: SIGKILL after `--grace SECS` (default 10). - `--junit PATH`: writes a JUnit report with one test suite per family. +Programs with a bundled nextest scheduler, such as the packaged conformance +binary, pass arguments after `--` through to nextest and return its exit code. + Each test runs in its own process group. When the test's process exits, `run` kills anything left in the group, such as CLI processes the test started. Interrupting `run` stops the current test the same way and runs no more diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index eb1db6c4d3..9477d6ed5c 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -62,9 +62,18 @@ pub fn main() -> ExitCode { main_with(&TESTS) } +/// Run a program whose `run` subcommand delegates to a bundled scheduler. +pub fn main_with_runner(runner: fn(RunOptions) -> ExitCode) -> ExitCode { + dispatch(&TESTS, Some(runner)) +} + /// [`main`] over `tests` instead of every registered test. #[doc(hidden)] pub fn main_with(tests: &'static [Test]) -> ExitCode { + dispatch(tests, None) +} + +fn dispatch(tests: &'static [Test], runner: Option ExitCode>) -> ExitCode { let args: Vec = std::env::args_os().collect(); let program = program_name(&args); // A suite crate that the program never names is not linked, and its @@ -96,7 +105,7 @@ pub fn main_with(tests: &'static [Test]) -> ExitCode { return ExitCode::from(if error.use_stderr() { ERROR_EXIT } else { 0 }); } }; - command(&program, tests, unsupported, cli.command) + command(&program, tests, unsupported, cli.command, runner) } else { libtest(tests, unsupported, args) } @@ -130,25 +139,31 @@ enum Command { #[arg(long, default_value = "60", value_name = "SECS", value_parser = seconds)] timeout: Duration, }, - /// Run tests one at a time, each in its own process. Exits 1 if a test - /// failed and 2 if tests could not run. - Run { - /// Run tests whose name contains any of these (all if none). - filters: Vec, - /// Run ignored tests too. - #[arg(long)] - include_ignored: bool, - /// Stop a test that runs longer than this, in seconds. Longer than - /// testkit's own step timeouts, so those report first. - #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] - timeout: Duration, - /// How long a stopped test has between SIGTERM and SIGKILL, in seconds. - #[arg(long, default_value = "10", value_name = "SECS", value_parser = seconds)] - grace: Duration, - /// Write a JUnit report here. - #[arg(long, value_name = "PATH")] - junit: Option, - }, + /// Run tests, each in its own process. + Run(RunOptions), +} + +/// Arguments shared by the standalone runner and the bundled scheduler. +#[derive(clap::Args)] +pub struct RunOptions { + /// Run tests whose name contains any of these (all if none). + pub filters: Vec, + /// Run ignored tests too. + #[arg(long)] + pub include_ignored: bool, + /// Stop a test that runs longer than this, in seconds. Longer than + /// testkit's own step timeouts, so those report first. + #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] + pub timeout: Duration, + /// How long a stopped test has between SIGTERM and SIGKILL, in seconds. + #[arg(long, default_value = "10", value_name = "SECS", value_parser = seconds)] + pub grace: Duration, + /// Write a JUnit report here. + #[arg(long, value_name = "PATH")] + pub junit: Option, + /// Arguments passed to nextest (bundled builds only). + #[arg(last = true, value_name = "NEXTEST_ARGS", allow_hyphen_values = true)] + pub nextest_args: Vec, } /// A positive, finite number of seconds. @@ -167,6 +182,7 @@ fn command( tests: &'static [Test], unsupported: Unsupported, command: Command, + runner: Option ExitCode>, ) -> ExitCode { match command { Command::List { filters } => { @@ -174,24 +190,42 @@ fn command( ExitCode::SUCCESS } Command::Ready { timeout } => ready(program, timeout), - Command::Run { - filters, - include_ignored, - timeout, - grace, - junit, - } => run( - program, - tests, - Selection { - filters, + Command::Run(options) => { + if let Some(runner) = runner { + return runner(options); + } + let RunOptions { + mut filters, include_ignored, - unsupported, - }, - timeout, - grace, - junit, - ), + timeout, + grace, + junit, + nextest_args, + } = options; + for arg in nextest_args { + let Ok(filter) = arg.into_string() else { + eprintln!("{program}: test filters must be UTF-8"); + return ExitCode::from(ERROR_EXIT); + }; + if filter.starts_with('-') { + eprintln!("{program}: nextest options require a bundled build"); + return ExitCode::from(ERROR_EXIT); + } + filters.push(filter); + } + run( + program, + tests, + Selection { + filters, + include_ignored, + unsupported, + }, + timeout, + grace, + junit, + ) + } } } @@ -364,7 +398,7 @@ mod tests { use clap::Parser; - use super::{Cli, Command}; + use super::{Cli, Command, RunOptions}; #[test] fn cli_is_consistent() { @@ -383,15 +417,21 @@ mod tests { "1.5", "--junit", "out/junit.xml", + "--", + "-j", + "4", + "-E", + "test(smoke)", ]) .unwrap(); - let Command::Run { + let Command::Run(RunOptions { filters, include_ignored, timeout, grace, junit, - } = cli.command + nextest_args, + }) = cli.command else { panic!("not run"); }; @@ -400,6 +440,7 @@ mod tests { assert_eq!(timeout, Duration::from_millis(1500)); assert_eq!(grace, Duration::from_secs(10)); assert_eq!(junit.unwrap().to_str(), Some("out/junit.xml")); + assert_eq!(nextest_args, ["-j", "4", "-E", "test(smoke)"]); let Command::Ready { timeout } = Cli::try_parse_from(["p", "ready"]).unwrap().command else { From c56037e61495730ab7595ece47e7b16a5f2833d7 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 09:31:09 -0800 Subject: [PATCH 07/14] refactor(testkit): use a shared nextest args namespace Signed-off-by: Matthew Grossman --- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-kubernetes-test.yml | 2 +- .github/workflows/e2e-podman-test.yml | 2 +- .github/workflows/e2e-vm-test.yml | 2 +- TESTING.md | 2 +- e2e/support/conformance.sh | 4 ++-- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 67e19fa050..8a776eb23e 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,6 +107,6 @@ jobs: - name: Run tests env: - OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" + OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index 84ce83197b..2a73e7ed62 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,7 +163,7 @@ jobs: - name: Run Kubernetes E2E env: - OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" + OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index 360d6f41aa..73aa15c9ea 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -84,7 +84,7 @@ jobs: - name: Run tests env: - OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 4" + OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index b27ecf8c86..e402acce10 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -65,7 +65,7 @@ jobs: - name: Run tests env: # Parallel provisioning failed in the VM host lanes; keep them serial. - OPENSHELL_CONFORMANCE_NEXTEST_ARGS: "--test-threads 1" + OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 1" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index 04e250159a..42db4fe075 100644 --- a/TESTING.md +++ b/TESTING.md @@ -527,7 +527,7 @@ Branch E2E packages `openshell-conformance` with nextest, so `run` can schedule tests without an installed nextest. With a bundled binary, pass nextest options after `--`, for example `run -- --test-threads 4`. The driver wrappers accept whitespace-separated options in -`OPENSHELL_CONFORMANCE_NEXTEST_ARGS` when using a prebuilt binary. Plain +`OPENSHELL_TESTKIT_NEXTEST_ARGS` when using a prebuilt binary. Plain Cargo builds run serially. ```shell diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index 8f70507579..e1585935aa 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -86,11 +86,11 @@ e2e_run_openshell_conformance() { echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return local args=(--junit "${junit}") - if [[ -n "${OPENSHELL_CONFORMANCE_BIN:-}" && -n "${OPENSHELL_CONFORMANCE_NEXTEST_ARGS:-}" ]]; then + if [[ -n "${OPENSHELL_CONFORMANCE_BIN:-}" && -n "${OPENSHELL_TESTKIT_NEXTEST_ARGS:-}" ]]; then local -a nextest_args # Simple whitespace-separated CI flags. Callers with quoted values can # pass them as arguments to this function instead. - read -r -a nextest_args <<< "${OPENSHELL_CONFORMANCE_NEXTEST_ARGS}" + read -r -a nextest_args <<< "${OPENSHELL_TESTKIT_NEXTEST_ARGS}" set -- "${nextest_args[@]}" "$@" fi if (($#)); then From d942fbfead661d996d21b9d11d59be17dc7917b8 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 09:34:30 -0800 Subject: [PATCH 08/14] ci(e2e): simplify bundled conformance smoke check Signed-off-by: Matthew Grossman --- .github/workflows/branch-e2e.yml | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 3f014c3581..60fe24c2be 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -218,20 +218,10 @@ jobs: tasks/scripts/verify-static-binary.sh "$binary" # Fails if the program has no tests linked. "$binary" list - # Exercise the packaged scheduler, not just the discovery interface. + # Verify bundled nextest starts without a toolchain or gateway. status=0 PATH=/usr/bin:/bin "$binary" run -- --no-tests fail __conformance_smoke_no_match__ || status=$? test "$status" = 4 - # A successful nextest invocation that did not run tests has no report. - status=0 - PATH=/usr/bin:/bin "$binary" run --junit "$RUNNER_TEMP/conformance.xml" -- --no-run || status=$? - test "$status" = 2 - test ! -e "$RUNNER_TEMP/conformance.xml" - status=0 - PATH=/usr/bin:/bin OPENSHELL_GATEWAY_ENDPOINT=http://127.0.0.1:1 \ - "$binary" run --junit "$RUNNER_TEMP/conformance.xml" -- -j 2 -E 'test(=smoke::create_exec_delete)' || status=$? - test "$status" = 100 - test -s "$RUNNER_TEMP/conformance.xml" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: openshell-conformance-${{ matrix.triple }} From 693369a730b9f431cdb63772ea6d0445c7673298 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 09:59:21 -0800 Subject: [PATCH 09/14] refactor(e2e): run conformance with external nextest Revert the bundled-nextest packaging. openshell-conformance only writes the metadata nextest needs (nextest-metadata DIR), and callers run cargo-nextest themselves, so every nextest option works unchanged. Replace OPENSHELL_TESTKIT_THREADS with nextest's own NEXTEST_TEST_THREADS. The wrapper's profile defaults to one thread because tests share a gateway. This reverts commits 7dc9bb5fe, fc3d03232, c56037e61 and d942fbfea. Signed-off-by: Matthew Grossman --- .github/workflows/branch-e2e.yml | 12 +- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-kubernetes-test.yml | 2 +- .github/workflows/e2e-podman-test.yml | 2 +- .github/workflows/e2e-vm-test.yml | 3 +- TESTING.md | 16 +- e2e/support/conformance.sh | 43 +++-- tasks/scripts/check-conformance-program.sh | 16 ++ tests/runner/src/bundle.rs | 24 ++- tests/runner/src/execute.rs | 60 +++++-- tests/runner/src/main.rs | 6 +- tests/suites/conformance/Cargo.lock | 1 - tests/suites/conformance/Cargo.toml | 4 - tests/suites/conformance/README.md | 20 --- tests/suites/conformance/build.rs | 11 -- tests/suites/conformance/package.sh | 83 ---------- tests/suites/conformance/src/bundled.rs | 164 ------------------- tests/suites/conformance/src/main.rs | 8 +- tests/testkit/README.md | 17 +- tests/testkit/testkit/src/program/mod.rs | 146 ++++++++--------- tests/testkit/testkit/src/program/nextest.rs | 71 ++++++++ tests/testkit/testkit/src/registry.rs | 2 +- 22 files changed, 278 insertions(+), 435 deletions(-) delete mode 100644 tests/suites/conformance/build.rs delete mode 100644 tests/suites/conformance/package.sh delete mode 100644 tests/suites/conformance/src/bundled.rs create mode 100644 tests/testkit/testkit/src/program/nextest.rs diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 60fe24c2be..2fbfdc62a3 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -212,20 +212,18 @@ jobs: CARGO_TARGET_DIR: ${{ github.workspace }}/target TRIPLE: ${{ matrix.triple }} run: | - bash tests/suites/conformance/package.sh "$TRIPLE" "artifacts/conformance/$TRIPLE" - binary="artifacts/conformance/$TRIPLE/openshell-conformance" + cargo build --release --locked --target "$TRIPLE" \ + --manifest-path tests/suites/conformance/Cargo.toml \ + --bin openshell-conformance + binary="target/$TRIPLE/release/openshell-conformance" # The program must run on any lane host. tasks/scripts/verify-static-binary.sh "$binary" # Fails if the program has no tests linked. "$binary" list - # Verify bundled nextest starts without a toolchain or gateway. - status=0 - PATH=/usr/bin:/bin "$binary" run -- --no-tests fail __conformance_smoke_no_match__ || status=$? - test "$status" = 4 - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: openshell-conformance-${{ matrix.triple }} - path: artifacts/conformance/${{ matrix.triple }}/openshell-conformance + path: target/${{ matrix.triple }}/release/openshell-conformance compression-level: 0 retention-days: 5 if-no-files-found: error diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index 8a776eb23e..a53bc53ee6 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -107,6 +107,6 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" + NEXTEST_TEST_THREADS: "4" OPENSHELL_MCP_CONFORMANCE_CLIENT_IMAGE: ${{ format('openshell-mcp-conformance-client:{0}', inputs.image-tag) }} run: ${{ matrix.cmd }} diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index 2a73e7ed62..340beb81f7 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -163,7 +163,7 @@ jobs: - name: Run Kubernetes E2E env: - OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" + NEXTEST_TEST_THREADS: "4" AGENT_SANDBOX_VERSION: ${{ inputs.agent-sandbox-version }} OPENSHELL_E2E_KUBE_CONTEXT: kind-${{ env.KIND_CLUSTER_NAME }} OPENSHELL_E2E_KUBE_EXTRA_VALUES: ${{ inputs.extra-helm-values }} diff --git a/.github/workflows/e2e-podman-test.yml b/.github/workflows/e2e-podman-test.yml index 73aa15c9ea..f6178a229c 100644 --- a/.github/workflows/e2e-podman-test.yml +++ b/.github/workflows/e2e-podman-test.yml @@ -84,7 +84,7 @@ jobs: - name: Run tests env: - OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 4" + NEXTEST_TEST_THREADS: "4" run: ${{ matrix.cmd }} - name: Print AppArmor denials diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index e402acce10..7b4a7c7020 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,8 +64,7 @@ jobs: - name: Run tests env: - # Parallel provisioning failed in the VM host lanes; keep them serial. - OPENSHELL_TESTKIT_NEXTEST_ARGS: "--test-threads 1" + NEXTEST_TEST_THREADS: "4" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" diff --git a/TESTING.md b/TESTING.md index 42db4fe075..b156edb2f9 100644 --- a/TESTING.md +++ b/TESTING.md @@ -256,14 +256,13 @@ prebuilt testkit program, such as a static `openshell-conformance` for the guest's architecture, instead of building the family's tests; it can't be combined with `--package`. With it, `--filter` (repeatable) takes parts of test names, as the program does, such as `--filter policy_advisor::`, rather than a -nextest filterset. The runner invokes the program's `ready` and `run` -commands in the guest. It writes `junit.xml` +nextest filterset. The runner runs the program's `ready` command in the +guest, then uses nextest to run the prebuilt binary. It writes `junit.xml` and `nextest.log` to the results directory. Branch E2E builds `openshell-conformance` once and passes it to every conformance row this way. `--test-threads N` runs up to N tests concurrently in the guest, whether the runner builds the suite or uses `--bundle` or `--program`. The default -is one. With `--program`, use a binary that bundles nextest. -CI rows can opt in with `test_threads`. +is one. CI rows can opt in with `test_threads`. `openshell-test-runner build --family --out ` builds a family's test bundle for the guest without booting a VM, and `run --bundle ` runs @@ -523,12 +522,9 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -Branch E2E packages `openshell-conformance` with nextest, so `run` can -schedule tests without an installed nextest. With a bundled binary, pass -nextest options after `--`, for example `run -- --test-threads 4`. The -driver wrappers accept whitespace-separated options in -`OPENSHELL_TESTKIT_NEXTEST_ARGS` when using a prebuilt binary. Plain -Cargo builds run serially. +The wrappers use nextest. Set `NEXTEST_TEST_THREADS` to change the +worker count from the default of one. For a standalone run without nextest, +invoke `openshell-conformance run` directly. ```shell OPENSHELL_E2E_KUBERNETES_FEATURES=e2e-conformance-only mise run e2e:kubernetes diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index e1585935aa..29aaa9dfbc 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -60,11 +60,10 @@ e2e_openshell_conformance_bin() { echo "${program}" } -# Run the conformance suite with openshell-conformance. The JUnit report goes +# Run the conformance suite with nextest. The JUnit report goes # to OPENSHELL_CONFORMANCE_JUNIT, else results/conformance-.xml. -e2e_run_openshell_conformance() { +e2e_run_openshell_conformance() ( local gateway_label=${1:-OpenShell} - if (($#)); then shift; fi local root program junit root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -85,20 +84,32 @@ e2e_run_openshell_conformance() { # these for the gateway they started. echo "==> Running conformance suites against the ${gateway_label} gateway" "${program}" ready || return - local args=(--junit "${junit}") - if [[ -n "${OPENSHELL_CONFORMANCE_BIN:-}" && -n "${OPENSHELL_TESTKIT_NEXTEST_ARGS:-}" ]]; then - local -a nextest_args - # Simple whitespace-separated CI flags. Callers with quoted values can - # pass them as arguments to this function instead. - read -r -a nextest_args <<< "${OPENSHELL_TESTKIT_NEXTEST_ARGS}" - set -- "${nextest_args[@]}" "$@" - fi - if (($#)); then - args+=(-- "$@") + local work status=0 + work="$(mktemp -d)" || return + trap 'rm -rf "${work}"' EXIT + "${program}" nextest-metadata "${work}" || return + cat > "${work}/nextest.toml" <<'EOF' +[profile.openshell] +# Tests share one gateway. NEXTEST_TEST_THREADS overrides this. +test-threads = 1 +slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } + +[profile.openshell.junit] +path = "junit.xml" +store-success-output = true +EOF + cargo-nextest nextest run \ + --cargo-metadata "${work}/cargo-metadata.json" \ + --binaries-metadata "${work}/binaries-metadata.json" \ + --config-file "${work}/nextest.toml" --profile openshell \ + --no-tests fail --no-fail-fast --success-output immediate \ + --failure-output immediate || status=$? + if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then + mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return fi - "${program}" run "${args[@]}" -} + return "${status}" +) if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then - e2e_run_openshell_conformance OpenShell "$@" + e2e_run_openshell_conformance fi diff --git a/tasks/scripts/check-conformance-program.sh b/tasks/scripts/check-conformance-program.sh index 5d2ccdfaf0..ca8edaa8f6 100755 --- a/tasks/scripts/check-conformance-program.sh +++ b/tasks/scripts/check-conformance-program.sh @@ -96,6 +96,22 @@ if [[ ! -s "${work}/nextest" ]] || ! diff -u "${work}/nextest" "${work}/program" fi echo "openshell-conformance lists the same $(wc -l < "${work}/program" | tr -d ' ') tests as nextest" +# Check the same inventory from a renamed prebuilt binary without Cargo on PATH. +messages="$(cargo build --locked --manifest-path "${conformance}" --bin openshell-conformance --message-format json)" +program="$(jq -r 'select(.reason == "compiler-artifact" and .executable != null) | .executable' <<< "${messages}")" +cp "${program}" "${work}/test-program" +"${work}/test-program" nextest-metadata "${work}/metadata" +nextest="$(command -v cargo-nextest)" +( + cd "${work}/metadata" + PATH=/usr/bin:/bin OPENSHELL_TEST_UNSUPPORTED="${unsupported}" \ + "${nextest}" nextest list --color never --run-ignored all \ + --cargo-metadata cargo-metadata.json --binaries-metadata binaries-metadata.json \ + --message-format oneline +) > "${work}/prebuilt" +grep -q '^conformance::bin/openshell-conformance ' "${work}/prebuilt" +awk '{print $2}' "${work}/prebuilt" | sort | diff -u "${work}/program" - + if [[ -n "${unsupported}" ]]; then for manifest in "${manifests[@]}"; do OPENSHELL_TEST_UNSUPPORTED="${unsupported}" \ diff --git a/tests/runner/src/bundle.rs b/tests/runner/src/bundle.rs index 4f953f6a8e..44caac0032 100644 --- a/tests/runner/src/bundle.rs +++ b/tests/runner/src/bundle.rs @@ -76,7 +76,7 @@ struct Manifest { pub enum Kind { /// A nextest archive, run with `cargo-nextest`. Nextest, - /// A prebuilt testkit program (`list`, `ready` and `run`), run directly. + /// A prebuilt testkit program, run by nextest without a Cargo build. Program, } @@ -93,7 +93,7 @@ impl Bundle { } } -/// A bundle holding only `program`, a testkit program already built for the +/// A bundle holding `program`, a testkit program already built for the /// guest target. `program` must be a static binary, as the guest's libc is /// not known. pub fn program(program: &Path) -> Result { @@ -105,9 +105,22 @@ pub fn program(program: &Path) -> Result { let dir = tempfile::tempdir().context("create bundle directory")?; std::fs::copy(program, dir.path().join(PROGRAM_BINARY)) .with_context(|| format!("copy {}", program.display()))?; + std::fs::write(dir.path().join(CONFIG), program_config())?; Ok(Bundle(dir, Kind::Program)) } +fn program_config() -> String { + format!( + r#"[profile.{PROFILE}] +slow-timeout = {{ period = "900s", terminate-after = 1, grace-period = "{GRACE_PERIOD_SECS}s" }} + +[profile.{PROFILE}.junit] +path = "junit.xml" +store-success-output = true +"# + ) +} + /// The Rust target for guests. tmachine only boots guests of the host's /// architecture, and static musl binaries don't depend on the guest's libc. fn guest_target() -> Result<&'static str> { @@ -362,17 +375,18 @@ mod tests { } #[test] - fn program_bundle_holds_only_the_program() { + fn program_bundle_holds_the_program_and_nextest_config() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("openshell-conformance"); std::fs::write(&path, b"binary").unwrap(); let bundle = program(&path).unwrap(); assert_eq!(bundle.kind(), Kind::Program); - let names: Vec<_> = std::fs::read_dir(bundle.path()) + let mut names: Vec<_> = std::fs::read_dir(bundle.path()) .unwrap() .map(|entry| entry.unwrap().file_name()) .collect(); - assert_eq!(names, [PROGRAM_BINARY]); + names.sort(); + assert_eq!(names, [CONFIG, PROGRAM_BINARY]); assert!(program(&dir.path().join("missing")).is_err()); } diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index fc7514ae46..f427f5d5ef 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -123,7 +123,7 @@ pub struct Run<'a> { /// Narrowing the tests in the bundle: nextest filtersets (`-E`) for a /// nextest bundle, parts of test names for a program bundle. pub filters: &'a [String], - /// Concurrency override for the test runner. + /// Concurrency override for nextest. pub test_threads: Option, /// Where `junit.xml`, `nextest.log` and, after a failure, the guest's /// `diagnostics/` go. @@ -390,23 +390,28 @@ async fn run_selected( let archive = format!("{guest}/tests.tar.zst"); let extract = format!("{guest}/extract"); let config = format!("{guest}/nextest.toml"); - let test_threads = run.test_threads.map(|count| count.to_string()); - let junit = format!("{guest}/junit.xml"); + let test_threads = run + .test_threads + .map_or(1, std::num::NonZeroUsize::get) + .to_string(); + let metadata = format!("{guest}/metadata"); + let cargo_metadata = format!("{metadata}/cargo-metadata.json"); + let binaries_metadata = format!("{metadata}/binaries-metadata.json"); let export = test_env::export_script(test_env::ENV_DIR); let mut args: Vec<&str> = vec!["--config-file", &config, "--profile", PROFILE]; let env_args = std::iter::once("env").chain(env.iter().map(String::as_str)); let mut tests: Vec<_> = env_args.clone().collect(); + tests.extend([ + "cargo-nextest", + "nextest", + "run", + "--test-threads", + &test_threads, + "--no-tests", + "fail", + ]); match kind { Kind::Nextest => { - tests.extend([ - "cargo-nextest", - "nextest", - "run", - "--test-threads", - test_threads.as_deref().unwrap_or("1"), - "--no-tests", - "fail", - ]); args.extend([ "--archive-file", &archive, @@ -422,16 +427,35 @@ async fn run_selected( if run.test_threads.is_none_or(|count| count.get() == 1) { tests.push("--no-capture"); } - tests.extend(&args); } Kind::Program => { - tests.extend([program.as_str(), "run", "--junit", &junit]); - tests.extend(filters.iter().map(String::as_str)); - if let Some(count) = &test_threads { - tests.extend(["--", "--test-threads", count]); - } + checked( + "write nextest metadata", + session + .exec(&[&program, "nextest-metadata", &metadata]) + .await?, + )?; + args.extend([ + "--cargo-metadata", + &cargo_metadata, + "--binaries-metadata", + &binaries_metadata, + ]); + tests.extend([ + "--no-fail-fast", + "--success-output", + "immediate", + "--failure-output", + "immediate", + ]); } } + tests.extend(&args); + // Prebuilt programs keep substring filters, unlike archive filtersets. + if kind == Kind::Program && !filters.is_empty() { + tests.push("--"); + tests.extend(filters.iter().map(String::as_str)); + } // nextest writes its output to a file in the guest, so a run that times // out or loses SSH still leaves a log for `collect_results`. The guest // shell exports the published variables itself, so their values, which diff --git a/tests/runner/src/main.rs b/tests/runner/src/main.rs index 4f8f751fbc..5f9f7c032c 100644 --- a/tests/runner/src/main.rs +++ b/tests/runner/src/main.rs @@ -81,11 +81,11 @@ struct RunArgs { #[arg(long, value_name = "DIR", conflicts_with = "program")] bundle: Option, /// Run this prebuilt testkit program, such as `openshell-conformance`, - /// instead of building the family's tests. It must bundle nextest and - /// be a static binary for the guest's architecture. + /// instead of building the family's tests. It must be a static binary for + /// the guest's architecture (a `*-unknown-linux-musl` build). #[arg(long, value_name = "PATH", conflicts_with = "packages")] program: Option, - /// Maximum number of concurrent tests [default: 1]. + /// Maximum number of tests nextest runs at once [default: 1]. #[arg(long, value_name = "N")] test_threads: Option, /// The gateway name the installer registers with the CLI. The packaged diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index 8d8de8aa9d..76506381c3 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -540,7 +540,6 @@ name = "conformance" version = "0.0.0" dependencies = [ "host-server-support", - "libc", "openshell-crypto", "openshell-testkit", "serde_json", diff --git a/tests/suites/conformance/Cargo.toml b/tests/suites/conformance/Cargo.toml index d193da59e3..4ae6c7e902 100644 --- a/tests/suites/conformance/Cargo.toml +++ b/tests/suites/conformance/Cargo.toml @@ -31,8 +31,4 @@ serde_json = "1" tempfile = "3" tokio = { version = "1", features = ["process", "time"] } -[target.'cfg(unix)'.dependencies] -libc = "0.2" -tokio = { version = "1", features = ["signal"] } - [workspace] diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index e7a5d89996..9a0922f05c 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -68,26 +68,6 @@ Feature and driver suites are not part of it. The and exit codes. `tasks/scripts/check-conformance-program.sh` checks that it lists the same tests as nextest. -Branch E2E builds a single executable with nextest bundled inside. Use -`openshell-conformance run --junit conformance.xml -- --test-threads 4` to run -that build in parallel. The default is one worker. No separately installed -nextest is required. Plain Cargo builds run serially. -On bundled builds, arguments after `--` go to nextest (see `run -- --help`), -and `run` returns nextest's exit status. - -To build the bundled executable, use the repository development shell: - -```shell -bash tests/suites/conformance/package.sh -``` - -The bundled scheduler runs from a private temporary directory. Tests use -that workspace as their working directory; use absolute paths for custom -CLI and gateway configuration paths. -An interrupted or timed-out test cannot clean up its gateway resources. -Nextest may leave a descendant running if it ignores termination and the -test process exits first. - See [Unsupported tests](../../testkit/README.md#unsupported-tests) to skip a test in specific CI environments. diff --git a/tests/suites/conformance/build.rs b/tests/suites/conformance/build.rs deleted file mode 100644 index 48d047277e..0000000000 --- a/tests/suites/conformance/build.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -fn main() { - println!("cargo::rustc-check-cfg=cfg(conformance_bundle)"); - println!("cargo::rerun-if-env-changed=OPENSHELL_CONFORMANCE_BUNDLE"); - println!("cargo::rerun-if-changed=build.rs"); - if std::env::var_os("OPENSHELL_CONFORMANCE_BUNDLE").is_some() { - println!("cargo::rustc-cfg=conformance_bundle"); - } -} diff --git a/tests/suites/conformance/package.sh b/tests/suites/conformance/package.sh deleted file mode 100644 index ae5f75777f..0000000000 --- a/tests/suites/conformance/package.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Package the conformance executable with its own nextest scheduler. -set -euo pipefail - -if [[ $# != 2 ]]; then - echo "Usage: $0 " >&2 - exit 2 -fi -target=$1 -mkdir -p "$2" -out=$(cd "$2" && pwd) -manifest="$(cd "$(dirname "$0")" && pwd)/Cargo.toml" -# Keep this release and its checksums in sync with the cargo-nextest pin in -# mise.toml and the version provided by the Nix dev shell (flake.nix). -version=0.9.143 -case "$target" in - aarch64-apple-darwin|x86_64-apple-darwin) - upstream=universal-apple-darwin - sha=4830d430411148d17602a75cc880bfb4dc8dac153dea59a48a2ef4cc93577f07 - ;; - aarch64-unknown-linux-musl) - upstream=$target - sha=0560ce0ce017f368c54b5db86588370fc03b470985490fa81200e62a657dda05 - ;; - x86_64-unknown-linux-musl) - upstream=$target - sha=6d891c18105ec2d33f6e441a4f92b7ccab47ba263e22055c8bb66884243f3389 - ;; - *) - echo "Unsupported conformance bundle target: $target (arm64 or x86-64, macOS or Linux musl)" >&2 - exit 2 - ;; -esac - -if [[ $(cargo nextest --version | awk '$1 == "release:" {print $2}') != "$version" ]]; then - echo "Build requires cargo-nextest $version" >&2 - exit 2 -fi - -work=$(mktemp -d "${TMPDIR:-/tmp}/conformance-package.XXXXXXXX") -trap 'rm -r -- "$work"' EXIT -work=$(cd "$work" && pwd -P) -export CARGO_PROFILE_RELEASE_STRIP=symbols -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-${manifest%/*}/target}" -unset OPENSHELL_CONFORMANCE_BUNDLE - -asset="cargo-nextest-$version-$upstream.tar.gz" -curl -fsSL "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-$version/$asset" -o "$work/$asset" -printf '%s %s\n' "$sha" "$work/$asset" | shasum -a 256 -c - -tar -xOzf "$work/$asset" cargo-nextest > "$work/nextest-upstream" -if [[ $upstream == universal-apple-darwin ]]; then - arch=${target%%-*} - lipo -thin "${arch/aarch64/arm64}" "$work/nextest-upstream" -output "$work/cargo-nextest" - codesign --verify "$work/cargo-nextest" -else - mv "$work/nextest-upstream" "$work/cargo-nextest" -fi - -build=(--locked --release --manifest-path "$manifest" --target "$target") -cargo nextest archive "${build[@]}" --bin openshell-conformance --archive-file "$work/suite.tar.zst" -# Discard the archive's unbundled test executable. The metadata still names -# its target-relative path; at runtime a symlink there points to the final -# bundled executable, which exposes the same test harness. -for name in cargo-metadata.json binaries-metadata.json; do - zstd -dc "$work/suite.tar.zst" | tar -xOf - "target/nextest/$name" > "$work/$name" -done -jq -er ' - .["rust-build-meta"]["target-directory"] as $target | - .["rust-binaries"] | to_entries | - if length != 1 or .[0].key != "conformance::bin/openshell-conformance" - then error("expected one conformance test binary") else .[0].value["binary-path"] end | - if startswith($target + "/") then ltrimstr($target + "/") - else error("test binary is outside the target directory") end | - select(test("^[A-Za-z0-9_/-]+$") and (split("/") | all(length > 0))) -' "$work/binaries-metadata.json" > "$work/binary-path" - -export OPENSHELL_CONFORMANCE_BUNDLE="$work" -cargo build "${build[@]}" --bin openshell-conformance -cp "$CARGO_TARGET_DIR/$target/release/openshell-conformance" "$out/" -wc -c "$out/openshell-conformance" diff --git a/tests/suites/conformance/src/bundled.rs b/tests/suites/conformance/src/bundled.rs deleted file mode 100644 index 831c990bcf..0000000000 --- a/tests/suites/conformance/src/bundled.rs +++ /dev/null @@ -1,164 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Reuse nextest's build metadata with this executable as -//! the only test binary. Never enter this scheduler for libtest invocations. - -use std::env; -use std::fs::{self, OpenOptions}; -use std::io::{self, Write as _}; -use std::os::unix::fs::{OpenOptionsExt as _, symlink}; -use std::path::{Path, PathBuf}; -use std::process::{ExitCode, ExitStatus, Stdio}; - -use testkit::program::RunOptions; -use tokio::process::Command; -use tokio::signal::unix::{SignalKind, signal}; - -macro_rules! payload { - ($name:literal) => { - concat!(env!("OPENSHELL_CONFORMANCE_BUNDLE"), "/", $name) - }; -} - -// Keep the payload out of the async state machine, which otherwise embeds -// identical byte strings in multiple optimized paths. -#[inline(never)] -fn materialize(root: &Path) -> io::Result<()> { - fs::write(root.join("Cargo.toml"), "[workspace]\n")?; - fs::write( - root.join("cargo-metadata.json"), - include_bytes!(payload!("cargo-metadata.json")), - )?; - fs::write( - root.join("binaries-metadata.json"), - include_bytes!(payload!("binaries-metadata.json")), - )?; - // Close the writable descriptor before executing (Linux rejects ETXTBSY). - OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o700) - .open(root.join("cargo-nextest"))? - .write_all(include_bytes!(payload!("cargo-nextest")))?; - Ok(()) -} - -pub(crate) fn run(options: RunOptions) -> ExitCode { - let result = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .and_then(|runtime| runtime.block_on(run_nextest(options))); - match result { - Ok(status) => ExitCode::from( - status - .code() - .and_then(|code| u8::try_from(code).ok()) - .unwrap_or(2), - ), - Err(error) => { - eprintln!("openshell-conformance: bundled nextest: {error}"); - ExitCode::from(2) - } - } -} - -async fn run_nextest(options: RunOptions) -> io::Result { - let mut int = signal(SignalKind::interrupt())?; - let mut term = signal(SignalKind::terminate())?; - let mut hup = signal(SignalKind::hangup())?; - - let temp = tempfile::Builder::new() - .prefix("openshell-conformance-") - .tempdir()?; - let root = temp.path().canonicalize()?; - let target = root.join("target"); - let binary = target.join(include_str!(payload!("binary-path")).trim_end()); - fs::create_dir_all(binary.parent().expect("test binary has a parent"))?; - symlink(env::current_exe()?, &binary)?; - - materialize(&root)?; - - let config = root.join("nextest.toml"); - let report = root.join("target/nextest/default/junit.xml"); - let mut profile = format!( - "[profile.default]\n\ - test-threads = 1\n\ - fail-fast = false\n\ - success-output = \"immediate\"\n\ - failure-output = \"immediate\"\n\ - slow-timeout = {{ period = \"{}ns\", terminate-after = 1, grace-period = \"{}ns\" }}\n", - options.timeout.as_nanos(), - options.grace.as_nanos() - ); - if options.junit.is_some() { - profile.push_str( - "[profile.default.junit]\npath = \"junit.xml\"\nreport-skipped = \"ignored\"\nstore-success-output = true\n", - ); - } - fs::write(&config, profile)?; - - let mut command = Command::new(root.join("cargo-nextest")); - command - .args(["nextest", "run", "--cargo-metadata"]) - .arg(root.join("cargo-metadata.json")) - .arg("--binaries-metadata") - .arg(root.join("binaries-metadata.json")) - .arg("--workspace-remap") - .arg(&root) - .arg("--target-dir-remap") - .arg(&target) - .arg("--config-file") - .arg(config) - .args([ - "--user-config-file", - "none", - "--no-input-handler", - "--no-pager", - "--profile", - "default", - ]) - .current_dir(&root) - .stdin(Stdio::null()) - // The terminal sends Ctrl-C to us, not to nextest too. Nextest owns - // the test process groups, so forward to the runner and let it reap. - .process_group(0); - if options.include_ignored { - command.args(["--run-ignored", "all"]); - } - command.args(options.nextest_args).args(options.filters); - let mut child = command.spawn().map_err(|error| { - io::Error::other(format!("start runner under {}: {error}", root.display())) - })?; - let pid = child.id().expect("spawned child has an ID") as libc::pid_t; - let mut interrupted = false; - let status = loop { - let sig = tokio::select! { - biased; - status = child.wait() => break status?, - _ = int.recv() => libc::SIGINT, - _ = term.recv() => libc::SIGTERM, - _ = hup.recv() => libc::SIGHUP, - }; - interrupted = true; - // SAFETY: `wait` did not reap the child, so its PID can't be reused. - unsafe { libc::kill(pid, sig) }; - }; - - if let Some(path) = options.junit { - // Setup/discovery errors can occur before nextest creates a report. - if report.try_exists()? { - if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - fs::create_dir_all(parent)?; - } - fs::copy(report, &path) - .map_err(|error| io::Error::other(format!("write {}: {error}", path.display())))?; - } else if status.success() && !interrupted { - return Err(io::Error::other( - "nextest did not write the requested report", - )); - } - } - - Ok(status) -} diff --git a/tests/suites/conformance/src/main.rs b/tests/suites/conformance/src/main.rs index 4dff7edcfc..8334cfd3e1 100644 --- a/tests/suites/conformance/src/main.rs +++ b/tests/suites/conformance/src/main.rs @@ -13,12 +13,6 @@ use std::process::ExitCode; // missing. use conformance as _; -#[cfg(all(unix, conformance_bundle))] -mod bundled; - fn main() -> ExitCode { - #[cfg(all(unix, conformance_bundle))] - return testkit::program::main_with_runner(bundled::run); - #[cfg(not(all(unix, conformance_bundle)))] - testkit::main() + testkit::program::main_for(env!("CARGO_PKG_NAME"), env!("CARGO_BIN_NAME")) } diff --git a/tests/testkit/README.md b/tests/testkit/README.md index b7b6871685..21f76945c9 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -230,6 +230,7 @@ program for the conformance suite; see | `list [FILTER]...` | Prints each test's name and description. Ignored tests are included and marked. | | `ready [--timeout SECS]` | Waits for the gateway, like `testkit-ready` (default 60 seconds). Exits 2 if it is not ready in time. | | `run [FILTER]...` | Runs the tests one at a time, each in its own process. Unix only. | +| `nextest-metadata DIR` | Writes a stub manifest and JSON metadata describing the prebuilt executable. | A filter selects tests whose name contains it. `run` also takes: @@ -239,9 +240,6 @@ A filter selects tests whose name contains it. `run` also takes: SIGKILL after `--grace SECS` (default 10). - `--junit PATH`: writes a JUnit report with one test suite per family. -Programs with a bundled nextest scheduler, such as the packaged conformance -binary, pass arguments after `--` through to nextest and return its exit code. - Each test runs in its own process group. When the test's process exits, `run` kills anything left in the group, such as CLI processes the test started. Interrupting `run` stops the current test the same way and runs no more @@ -262,6 +260,19 @@ test target with `harness = false` therefore also runs under `cargo test` and nextest. In that mode tests run in one process, one at a time unless `--test-threads` says otherwise. +To run a prebuilt program with nextest (no Cargo or checkout required), write +metadata to a fresh directory on the machine where the program will run: + +```shell +openshell-conformance nextest-metadata metadata +cargo-nextest nextest run --cargo-metadata metadata/cargo-metadata.json \ + --binaries-metadata metadata/binaries-metadata.json --test-threads 4 +``` + +The metadata refers to the binary's absolute path. Regenerate it if the +binary moves. Tests run from the metadata directory, so give paths such as +`OPENSHELL_BIN` as absolute paths. + A test's name is its module path without the crate name, then its function name, as in nextest. Its family, which groups tests in the JUnit report, is the first directory under the last `suites` directory in the crate's path: diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index 9477d6ed5c..dedd5d2e12 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -12,12 +12,14 @@ //! } //! ``` //! -//! It has three subcommands: +//! Its subcommands: //! //! - `list [FILTER]...` prints each test's name and description. //! - `ready [--timeout SECS]` waits for the gateway, as `testkit-ready` does. //! - `run [FILTER]...` runs tests one at a time, each in its own process with //! a timeout, and can write a `JUnit` report. Unix only. +//! - `nextest-metadata DIR` describes the executable to nextest, so it can +//! run the prebuilt program without Cargo. //! //! Any other arguments are libtest's, so the program also works as a //! `harness = false` test target under `cargo test` and nextest: it answers @@ -33,6 +35,7 @@ mod capture; #[cfg(unix)] mod junit; +mod nextest; #[cfg(unix)] mod process; #[cfg(unix)] @@ -62,9 +65,10 @@ pub fn main() -> ExitCode { main_with(&TESTS) } -/// Run a program whose `run` subcommand delegates to a bundled scheduler. -pub fn main_with_runner(runner: fn(RunOptions) -> ExitCode) -> ExitCode { - dispatch(&TESTS, Some(runner)) +/// Run a suite program with the package and binary names it has under Cargo. +/// These names are used by `nextest-metadata`, even if the executable is renamed. +pub fn main_for(package: &str, binary: &str) -> ExitCode { + dispatch(&TESTS, Some((package, binary))) } /// [`main`] over `tests` instead of every registered test. @@ -73,7 +77,7 @@ pub fn main_with(tests: &'static [Test]) -> ExitCode { dispatch(tests, None) } -fn dispatch(tests: &'static [Test], runner: Option ExitCode>) -> ExitCode { +fn dispatch(tests: &'static [Test], identity: Option<(&str, &str)>) -> ExitCode { let args: Vec = std::env::args_os().collect(); let program = program_name(&args); // A suite crate that the program never names is not linked, and its @@ -105,7 +109,7 @@ fn dispatch(tests: &'static [Test], runner: Option ExitCode>) return ExitCode::from(if error.use_stderr() { ERROR_EXIT } else { 0 }); } }; - command(&program, tests, unsupported, cli.command, runner) + command(&program, tests, unsupported, cli.command, identity) } else { libtest(tests, unsupported, args) } @@ -127,6 +131,11 @@ struct Cli { #[derive(Subcommand)] enum Command { + /// Write metadata to run the prebuilt executable with cargo-nextest. + NextestMetadata { + #[arg(value_name = "DIR")] + dir: PathBuf, + }, /// Print each test's name and description, including ignored tests. List { /// Show tests whose name contains any of these (all if none). @@ -139,31 +148,25 @@ enum Command { #[arg(long, default_value = "60", value_name = "SECS", value_parser = seconds)] timeout: Duration, }, - /// Run tests, each in its own process. - Run(RunOptions), -} - -/// Arguments shared by the standalone runner and the bundled scheduler. -#[derive(clap::Args)] -pub struct RunOptions { - /// Run tests whose name contains any of these (all if none). - pub filters: Vec, - /// Run ignored tests too. - #[arg(long)] - pub include_ignored: bool, - /// Stop a test that runs longer than this, in seconds. Longer than - /// testkit's own step timeouts, so those report first. - #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] - pub timeout: Duration, - /// How long a stopped test has between SIGTERM and SIGKILL, in seconds. - #[arg(long, default_value = "10", value_name = "SECS", value_parser = seconds)] - pub grace: Duration, - /// Write a JUnit report here. - #[arg(long, value_name = "PATH")] - pub junit: Option, - /// Arguments passed to nextest (bundled builds only). - #[arg(last = true, value_name = "NEXTEST_ARGS", allow_hyphen_values = true)] - pub nextest_args: Vec, + /// Run tests one at a time, each in its own process. Exits 1 if a test + /// failed and 2 if tests could not run. + Run { + /// Run tests whose name contains any of these (all if none). + filters: Vec, + /// Run ignored tests too. + #[arg(long)] + include_ignored: bool, + /// Stop a test that runs longer than this, in seconds. Longer than + /// testkit's own step timeouts, so those report first. + #[arg(long, default_value = "900", value_name = "SECS", value_parser = seconds)] + timeout: Duration, + /// How long a stopped test has between SIGTERM and SIGKILL, in seconds. + #[arg(long, default_value = "10", value_name = "SECS", value_parser = seconds)] + grace: Duration, + /// Write a JUnit report here. + #[arg(long, value_name = "PATH")] + junit: Option, + }, } /// A positive, finite number of seconds. @@ -182,50 +185,46 @@ fn command( tests: &'static [Test], unsupported: Unsupported, command: Command, - runner: Option ExitCode>, + identity: Option<(&str, &str)>, ) -> ExitCode { match command { + Command::NextestMetadata { dir } => { + let package = tests[0].package(); + let (package, binary) = identity.unwrap_or((package, program)); + match nextest::write(&dir, package, binary) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!( + "{program}: write nextest metadata to {}: {error}", + dir.display() + ); + ExitCode::from(ERROR_EXIT) + } + } + } Command::List { filters } => { list(tests, &unsupported, filters); ExitCode::SUCCESS } Command::Ready { timeout } => ready(program, timeout), - Command::Run(options) => { - if let Some(runner) = runner { - return runner(options); - } - let RunOptions { - mut filters, + Command::Run { + filters, + include_ignored, + timeout, + grace, + junit, + } => run( + program, + tests, + Selection { + filters, include_ignored, - timeout, - grace, - junit, - nextest_args, - } = options; - for arg in nextest_args { - let Ok(filter) = arg.into_string() else { - eprintln!("{program}: test filters must be UTF-8"); - return ExitCode::from(ERROR_EXIT); - }; - if filter.starts_with('-') { - eprintln!("{program}: nextest options require a bundled build"); - return ExitCode::from(ERROR_EXIT); - } - filters.push(filter); - } - run( - program, - tests, - Selection { - filters, - include_ignored, - unsupported, - }, - timeout, - grace, - junit, - ) - } + unsupported, + }, + timeout, + grace, + junit, + ), } } @@ -398,7 +397,7 @@ mod tests { use clap::Parser; - use super::{Cli, Command, RunOptions}; + use super::{Cli, Command}; #[test] fn cli_is_consistent() { @@ -417,21 +416,15 @@ mod tests { "1.5", "--junit", "out/junit.xml", - "--", - "-j", - "4", - "-E", - "test(smoke)", ]) .unwrap(); - let Command::Run(RunOptions { + let Command::Run { filters, include_ignored, timeout, grace, junit, - nextest_args, - }) = cli.command + } = cli.command else { panic!("not run"); }; @@ -440,7 +433,6 @@ mod tests { assert_eq!(timeout, Duration::from_millis(1500)); assert_eq!(grace, Duration::from_secs(10)); assert_eq!(junit.unwrap().to_str(), Some("out/junit.xml")); - assert_eq!(nextest_args, ["-j", "4", "-E", "test(smoke)"]); let Command::Ready { timeout } = Cli::try_parse_from(["p", "ready"]).unwrap().command else { diff --git a/tests/testkit/testkit/src/program/nextest.rs b/tests/testkit/testkit/src/program/nextest.rs new file mode 100644 index 0000000000..ccca4a9c97 --- /dev/null +++ b/tests/testkit/testkit/src/program/nextest.rs @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The Cargo and binary metadata nextest reads instead of building the suite. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write as _}; +use std::path::Path; + +use serde_json::json; + +pub fn write(dir: &Path, package: &str, binary: &str) -> io::Result<()> { + let exe = std::env::current_exe()?; + fs::create_dir_all(dir)?; + let dir = dir.canonicalize()?; + let manifest = dir.join("Cargo.toml"); + let target = dir.join("target"); + let package_id = format!("{package} 0.0.0"); + let binary_id = format!("{package}::bin/{binary}"); + + // The manifest identifies the workspace. Nextest reads the JSON rather + // than invoking Cargo, and the only test target is the running binary. + let cargo = json!({ + "packages": [{ + "name": package, "version": "0.0.0", "id": package_id, + "manifest_path": manifest, + "authors": [], "categories": [], "keywords": [], + "dependencies": [], "features": {}, + "targets": [{ + "name": binary, "kind": ["bin"], "crate_types": ["bin"], + "src_path": exe, "edition": "2024", "test": true + }], + "edition": "2024" + }], + "workspace_members": [package_id], + "workspace_default_members": [package_id], + "target_directory": target, + "workspace_root": dir, + "version": 1 + }); + // Omitting platforms lets nextest use its own native target when rustc + // isn't installed. The executable is already runnable on this machine. + let binaries = json!({ + "rust-build-meta": { + "target-directory": target, + "base-output-directories": [], + "non-test-binaries": {}, + "linked-paths": [] + }, + "rust-binaries": { + binary_id.clone(): { + "binary-id": binary_id, "binary-name": binary, + "package-id": package_id, "kind": "bin", + "binary-path": exe, "build-platform": "target" + } + } + }); + let create = |name| { + OpenOptions::new() + .write(true) + .create_new(true) + .open(dir.join(name)) + }; + writeln!( + create("Cargo.toml")?, + "[package]\nname = {package:?}\nversion = \"0.0.0\"" + )?; + serde_json::to_writer(create("cargo-metadata.json")?, &cargo)?; + serde_json::to_writer(create("binaries-metadata.json")?, &binaries)?; + Ok(()) +} diff --git a/tests/testkit/testkit/src/registry.rs b/tests/testkit/testkit/src/registry.rs index b5c6252306..a4e9e6431d 100644 --- a/tests/testkit/testkit/src/registry.rs +++ b/tests/testkit/testkit/src/registry.rs @@ -59,7 +59,7 @@ impl Test { /// Names a test cannot have at the top level: the program would read them as /// its own subcommands, so nextest could not run the test by name. -pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run"]; +pub const RESERVED_NAMES: &[&str] = &["help", "list", "ready", "run", "nextest-metadata"]; /// Check the tests can be told apart by name. pub fn validate(tests: &[Test]) -> Result<(), String> { From 9c7a67494b40322b39623a6ef08b3d51fabbcc04 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 10:09:14 -0800 Subject: [PATCH 10/14] refactor(e2e): use nextest's default conformance concurrency Drop the wrapper profile's test-threads = 1 so local runs use nextest's default of one test per CPU. CI sets NEXTEST_TEST_THREADS explicitly. Signed-off-by: Matthew Grossman --- TESTING.md | 4 ++-- e2e/support/conformance.sh | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/TESTING.md b/TESTING.md index b156edb2f9..42b2e0622c 100644 --- a/TESTING.md +++ b/TESTING.md @@ -522,8 +522,8 @@ feature variable (`OPENSHELL_E2E_DOCKER_FEATURES`, `OPENSHELL_E2E_PODMAN_FEATURE `e2e-conformance-only` to skip the Rust tests; the runner logs a notice when it skips them. Unset or empty values select the driver's default Rust features. The selector is handled by the runner; it is not a Cargo feature. -The wrappers use nextest. Set `NEXTEST_TEST_THREADS` to change the -worker count from the default of one. For a standalone run without nextest, +The wrappers use nextest, which runs one test per CPU by default. Set +`NEXTEST_TEST_THREADS` to change the worker count. For a standalone run without nextest, invoke `openshell-conformance run` directly. ```shell diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index 29aaa9dfbc..c70ee223a6 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -90,8 +90,6 @@ e2e_run_openshell_conformance() ( "${program}" nextest-metadata "${work}" || return cat > "${work}/nextest.toml" <<'EOF' [profile.openshell] -# Tests share one gateway. NEXTEST_TEST_THREADS overrides this. -test-threads = 1 slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } [profile.openshell.junit] From 05ce8d9be9f074ce6e547e78437d0e9c7d7ce4f8 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 10:39:28 -0800 Subject: [PATCH 11/14] ci(e2e): run VM conformance with one worker Simultaneous VM launches on a fresh gateway crash with a vCPU "Bad address" error (#5902), so keep the VM lanes serial until the driver handles concurrent first launches. Signed-off-by: Matthew Grossman --- .github/workflows/e2e-vm-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/e2e-vm-test.yml b/.github/workflows/e2e-vm-test.yml index 7b4a7c7020..2695d64850 100644 --- a/.github/workflows/e2e-vm-test.yml +++ b/.github/workflows/e2e-vm-test.yml @@ -64,7 +64,8 @@ jobs: - name: Run tests env: - NEXTEST_TEST_THREADS: "4" + # Simultaneous VM launches crash on a fresh gateway (#5902). + NEXTEST_TEST_THREADS: "1" E2E_TASK: ${{ inputs.e2e-task }} OPENSHELL_E2E_VM_TEST: ${{ inputs.test-name }} run: mise run --no-deps --skip-deps "$E2E_TASK" From 64c49a24c6cdc2593b87dcd11f5a01ad75317ba6 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:24:50 -0800 Subject: [PATCH 12/14] fix(e2e): keep conformance worker count out of Kubernetes Rust e2e NEXTEST_TEST_THREADS is set for the whole CI step, so the legacy Kubernetes nextest run inherited it. Unset it there to keep that suite on its own profile's concurrency. Signed-off-by: Matthew Grossman --- e2e/rust/e2e-kubernetes.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/e2e/rust/e2e-kubernetes.sh b/e2e/rust/e2e-kubernetes.sh index 6a9bd6a901..4e2df4a469 100755 --- a/e2e/rust/e2e-kubernetes.sh +++ b/e2e/rust/e2e-kubernetes.sh @@ -121,7 +121,8 @@ run_e2e() { fi # Pin `--target-dir` so the profile `junit.path` resolves regardless of `CARGO_TARGET_DIR`. - cargo nextest run --profile e2e-kubernetes \ + # NEXTEST_TEST_THREADS sets conformance concurrency, not this suite's. + env -u NEXTEST_TEST_THREADS cargo nextest run --profile e2e-kubernetes \ --config-file "${ROOT}/.config/nextest.toml" \ --target-dir "${ROOT}/e2e/rust/target" \ --manifest-path "${ROOT}/e2e/rust/Cargo.toml" \ From c198a1a6a499ff8c05027478ce03aacb079db39f Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:24:50 -0800 Subject: [PATCH 13/14] refactor(e2e): share the prebuilt-program nextest profile The runner and the host-lane wrapper wrote the same nextest profile and passed the same output flags. Keep them in one checked-in file that the runner embeds and the wrapper passes by path. Signed-off-by: Matthew Grossman --- e2e/support/conformance.sh | 14 +++----------- tests/runner/src/bundle.rs | 22 ++++++++++------------ tests/runner/src/execute.rs | 7 ------- tests/runner/src/program-nextest.toml | 13 +++++++++++++ 4 files changed, 26 insertions(+), 30 deletions(-) create mode 100644 tests/runner/src/program-nextest.toml diff --git a/e2e/support/conformance.sh b/e2e/support/conformance.sh index c70ee223a6..37ac2e85d9 100644 --- a/e2e/support/conformance.sh +++ b/e2e/support/conformance.sh @@ -88,20 +88,12 @@ e2e_run_openshell_conformance() ( work="$(mktemp -d)" || return trap 'rm -rf "${work}"' EXIT "${program}" nextest-metadata "${work}" || return - cat > "${work}/nextest.toml" <<'EOF' -[profile.openshell] -slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } - -[profile.openshell.junit] -path = "junit.xml" -store-success-output = true -EOF + # The profile the runner also uses for prebuilt programs. cargo-nextest nextest run \ --cargo-metadata "${work}/cargo-metadata.json" \ --binaries-metadata "${work}/binaries-metadata.json" \ - --config-file "${work}/nextest.toml" --profile openshell \ - --no-tests fail --no-fail-fast --success-output immediate \ - --failure-output immediate || status=$? + --config-file "${root}/tests/runner/src/program-nextest.toml" \ + --profile openshell --no-tests fail || status=$? if [[ -f "${work}/target/nextest/openshell/junit.xml" ]]; then mv "${work}/target/nextest/openshell/junit.xml" "${junit}" || return fi diff --git a/tests/runner/src/bundle.rs b/tests/runner/src/bundle.rs index 44caac0032..05a485a2aa 100644 --- a/tests/runner/src/bundle.rs +++ b/tests/runner/src/bundle.rs @@ -105,21 +105,13 @@ pub fn program(program: &Path) -> Result { let dir = tempfile::tempdir().context("create bundle directory")?; std::fs::copy(program, dir.path().join(PROGRAM_BINARY)) .with_context(|| format!("copy {}", program.display()))?; - std::fs::write(dir.path().join(CONFIG), program_config())?; + std::fs::write(dir.path().join(CONFIG), PROGRAM_CONFIG)?; Ok(Bundle(dir, Kind::Program)) } -fn program_config() -> String { - format!( - r#"[profile.{PROFILE}] -slow-timeout = {{ period = "900s", terminate-after = 1, grace-period = "{GRACE_PERIOD_SECS}s" }} - -[profile.{PROFILE}.junit] -path = "junit.xml" -store-success-output = true -"# - ) -} +/// The nextest configuration written into a program bundle, shared with the +/// host-lane wrapper (`e2e/support/conformance.sh`). +const PROGRAM_CONFIG: &str = include_str!("program-nextest.toml"); /// The Rust target for guests. tmachine only boots guests of the host's /// architecture, and static musl binaries don't depend on the guest's libc. @@ -390,6 +382,12 @@ mod tests { assert!(program(&dir.path().join("missing")).is_err()); } + #[test] + fn program_config_defines_the_runner_profile() { + assert!(PROGRAM_CONFIG.contains(&format!("[profile.{PROFILE}]\n"))); + assert!(PROGRAM_CONFIG.contains(&format!("[profile.{PROFILE}.junit]\n"))); + } + fn write_bundle(dir: &Path, family: &str, packages: &[&str]) { std::fs::create_dir_all(dir.join("host-gateway")).unwrap(); for name in [ARCHIVE, CONFIG, READY_BINARY, "Cargo.toml"] { diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index f427f5d5ef..9432f6a629 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -441,13 +441,6 @@ async fn run_selected( "--binaries-metadata", &binaries_metadata, ]); - tests.extend([ - "--no-fail-fast", - "--success-output", - "immediate", - "--failure-output", - "immediate", - ]); } } tests.extend(&args); diff --git a/tests/runner/src/program-nextest.toml b/tests/runner/src/program-nextest.toml new file mode 100644 index 0000000000..83d849c8c2 --- /dev/null +++ b/tests/runner/src/program-nextest.toml @@ -0,0 +1,13 @@ +# The nextest profile for running a prebuilt testkit program, such as +# openshell-conformance. The runner writes it into program bundles, and +# e2e/support/conformance.sh passes it to nextest on host lanes. +[profile.openshell] +fail-fast = false +success-output = "immediate" +failure-output = "immediate" +# Longer than testkit's own step timeouts, so those report first. +slow-timeout = { period = "900s", terminate-after = 1, grace-period = "10s" } + +[profile.openshell.junit] +path = "junit.xml" +store-success-output = true From 997182ce3539c8db575ee8579b578622a6739f80 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:24:50 -0800 Subject: [PATCH 14/14] docs(testing): link conformance shared-gateway rules to TESTING.md Signed-off-by: Matthew Grossman --- TESTING.md | 5 +++-- tests/suites/conformance/README.md | 5 ++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/TESTING.md b/TESTING.md index 42b2e0622c..8a5d6a799c 100644 --- a/TESTING.md +++ b/TESTING.md @@ -205,8 +205,9 @@ re-locks a workspace from the root lockfile. Add new testkit workspaces to Conformance tests must work concurrently on a shared gateway. Use `Context::name` (or testkit's sandbox builder) for gateway resource names, -use test-unique selector values, and scope assertions and cleanup to -resources the test owns. Do not change gateway-wide settings or routes. +use test-unique selector values and host fixtures, and scope assertions and +cleanup to resources the test owns. Do not change gateway-wide settings or +routes. Conformance tests run on every compute driver, so they check the public contract and nothing a driver is free to change. diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index 9a0922f05c..257ff4a9b4 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -77,9 +77,8 @@ Add a `#[testkit::test]` function to a suite, or for a new area, a new file in `src/` and a `mod` line for it in `src/lib.rs`. `openshell-conformance` includes every test in the crate. -Tests must be safe to run concurrently on a shared gateway. Use test-unique -names, selectors, and host fixtures; assert on test-owned resources, not -gateway-wide counts. Do not change gateway-wide settings or routes. +Tests must be safe to run concurrently on a shared gateway; see +[What a conformance test may assert](../../../TESTING.md#what-a-conformance-test-may-assert). ## What a test may assert