cargo/ops/
cargo_test.rs

1use crate::core::compiler::{Compilation, CompileKind, Doctest, Unit, UnitHash, UnitOutput};
2use crate::core::profiles::PanicStrategy;
3use crate::core::shell::ColorChoice;
4use crate::core::shell::Verbosity;
5use crate::core::{TargetKind, Workspace};
6use crate::ops;
7use crate::util::errors::CargoResult;
8use crate::util::{CliError, CliResult, GlobalContext, add_path_args};
9use anyhow::format_err;
10use cargo_util::{ProcessBuilder, ProcessError};
11use std::ffi::OsString;
12use std::fmt::Write;
13use std::path::{Path, PathBuf};
14
15pub struct TestOptions {
16    pub compile_opts: ops::CompileOptions,
17    pub no_run: bool,
18    pub no_fail_fast: bool,
19}
20
21/// The kind of test.
22///
23/// This is needed because `Unit` does not track whether or not something is a
24/// benchmark.
25#[derive(Copy, Clone)]
26enum TestKind {
27    Test,
28    Bench,
29    Doctest,
30}
31
32/// A unit that failed to run.
33struct UnitTestError {
34    unit: Unit,
35    kind: TestKind,
36}
37
38impl UnitTestError {
39    /// Returns the CLI args needed to target this unit.
40    fn cli_args(&self, ws: &Workspace<'_>, opts: &ops::CompileOptions) -> String {
41        let mut args = if opts.spec.needs_spec_flag(ws) {
42            format!("-p {} ", self.unit.pkg.name())
43        } else {
44            String::new()
45        };
46        let mut add = |which| write!(args, "--{which} {}", self.unit.target.name()).unwrap();
47
48        match self.kind {
49            TestKind::Test | TestKind::Bench => match self.unit.target.kind() {
50                TargetKind::Lib(_) => args.push_str("--lib"),
51                TargetKind::Bin => add("bin"),
52                TargetKind::Test => add("test"),
53                TargetKind::Bench => add("bench"),
54                TargetKind::ExampleLib(_) | TargetKind::ExampleBin => add("example"),
55                TargetKind::CustomBuild => panic!("unexpected CustomBuild kind"),
56            },
57            TestKind::Doctest => args.push_str("--doc"),
58        }
59        args
60    }
61}
62
63/// Compiles and runs tests.
64///
65/// On error, the returned [`CliError`] will have the appropriate process exit
66/// code that Cargo should use.
67pub fn run_tests(ws: &Workspace<'_>, options: &TestOptions, test_args: &[&str]) -> CliResult {
68    let compilation = compile_tests(ws, options)?;
69
70    if options.no_run {
71        if !options.compile_opts.build_config.emit_json() {
72            display_no_run_information(ws, test_args, &compilation, "unittests")?;
73        }
74        return Ok(());
75    }
76    let mut errors = run_unit_tests(ws, options, test_args, &compilation, TestKind::Test)?;
77
78    let doctest_errors = run_doc_tests(ws, options, test_args, &compilation)?;
79    errors.extend(doctest_errors);
80    no_fail_fast_err(ws, &options.compile_opts, &errors)
81}
82
83/// Compiles and runs benchmarks.
84///
85/// On error, the returned [`CliError`] will have the appropriate process exit
86/// code that Cargo should use.
87pub fn run_benches(ws: &Workspace<'_>, options: &TestOptions, args: &[&str]) -> CliResult {
88    let compilation = compile_tests(ws, options)?;
89
90    if options.no_run {
91        if !options.compile_opts.build_config.emit_json() {
92            display_no_run_information(ws, args, &compilation, "benches")?;
93        }
94        return Ok(());
95    }
96
97    let mut args = args.to_vec();
98    args.push("--bench");
99
100    let errors = run_unit_tests(ws, options, &args, &compilation, TestKind::Bench)?;
101    no_fail_fast_err(ws, &options.compile_opts, &errors)
102}
103
104fn compile_tests<'a>(ws: &Workspace<'a>, options: &TestOptions) -> CargoResult<Compilation<'a>> {
105    let mut compilation = ops::compile(ws, &options.compile_opts)?;
106    compilation.tests.sort();
107    Ok(compilation)
108}
109
110/// Runs the unit and integration tests of a package.
111///
112/// Returns a `Vec` of tests that failed when `--no-fail-fast` is used.
113/// If `--no-fail-fast` is *not* used, then this returns an `Err`.
114fn run_unit_tests(
115    ws: &Workspace<'_>,
116    options: &TestOptions,
117    test_args: &[&str],
118    compilation: &Compilation<'_>,
119    test_kind: TestKind,
120) -> Result<Vec<UnitTestError>, CliError> {
121    let gctx = ws.gctx();
122    let cwd = gctx.cwd();
123    let mut errors = Vec::new();
124
125    for UnitOutput {
126        unit,
127        path,
128        script_metas,
129    } in compilation.tests.iter()
130    {
131        let (exe_display, mut cmd) = cmd_builds(
132            gctx,
133            cwd,
134            unit,
135            path,
136            script_metas.as_ref(),
137            test_args,
138            compilation,
139            "unittests",
140        )?;
141
142        if gctx.extra_verbose() {
143            cmd.display_env_vars();
144        }
145
146        gctx.shell()
147            .concise(|shell| shell.status("Running", &exe_display))?;
148        gctx.shell()
149            .verbose(|shell| shell.status("Running", &cmd))?;
150
151        if let Err(e) = cmd.exec() {
152            let code = fail_fast_code(&e);
153            let unit_err = UnitTestError {
154                unit: unit.clone(),
155                kind: test_kind,
156            };
157            report_test_error(ws, test_args, &options.compile_opts, &unit_err, e);
158            errors.push(unit_err);
159            if !options.no_fail_fast {
160                return Err(CliError::code(code));
161            }
162        }
163    }
164    Ok(errors)
165}
166
167/// Runs doc tests.
168///
169/// Returns a `Vec` of tests that failed when `--no-fail-fast` is used.
170/// If `--no-fail-fast` is *not* used, then this returns an `Err`.
171fn run_doc_tests(
172    ws: &Workspace<'_>,
173    options: &TestOptions,
174    test_args: &[&str],
175    compilation: &Compilation<'_>,
176) -> Result<Vec<UnitTestError>, CliError> {
177    let gctx = ws.gctx();
178    let mut errors = Vec::new();
179    let color = gctx.shell().color_choice();
180
181    for doctest_info in &compilation.to_doc_test {
182        let Doctest {
183            args,
184            unstable_opts,
185            unit,
186            linker,
187            script_metas,
188            env,
189        } = doctest_info;
190
191        gctx.shell().status("Doc-tests", unit.target.name())?;
192        let mut p = compilation.rustdoc_process(unit, script_metas.as_ref())?;
193
194        for (var, value) in env {
195            p.env(var, value);
196        }
197
198        let color_arg = match color {
199            ColorChoice::Always => "always",
200            ColorChoice::Never => "never",
201            ColorChoice::CargoAuto => "auto",
202        };
203        p.arg("--color").arg(color_arg);
204
205        p.arg("--crate-name").arg(&unit.target.crate_name());
206        p.arg("--test");
207
208        add_path_args(ws, unit, &mut p);
209        p.arg("--test-run-directory").arg(unit.pkg.root());
210
211        if let CompileKind::Target(target) = unit.kind {
212            // use `rustc_target()` to properly handle JSON target paths
213            p.arg("--target").arg(target.rustc_target());
214        }
215
216        if let Some((runtool, runtool_args)) = compilation.target_runner(unit.kind) {
217            p.arg("--test-runtool").arg(runtool);
218            for arg in runtool_args {
219                p.arg("--test-runtool-arg").arg(arg);
220            }
221        }
222        if let Some(linker) = linker {
223            let mut joined = OsString::from("linker=");
224            joined.push(linker);
225            p.arg("-C").arg(joined);
226        }
227
228        if unit.profile.panic != PanicStrategy::Unwind {
229            p.arg("-C").arg(format!("panic={}", unit.profile.panic));
230        }
231
232        for native_dep in compilation.native_dirs.iter() {
233            p.arg("-L").arg(native_dep);
234        }
235
236        for arg in test_args {
237            p.arg("--test-args").arg(arg);
238        }
239
240        if gctx.shell().verbosity() == Verbosity::Quiet {
241            p.arg("--test-args").arg("--quiet");
242        }
243
244        p.args(unit.pkg.manifest().lint_rustflags());
245
246        p.args(args);
247
248        if *unstable_opts {
249            p.arg("-Zunstable-options");
250        }
251
252        if gctx.extra_verbose() {
253            p.display_env_vars();
254        }
255
256        gctx.shell()
257            .verbose(|shell| shell.status("Running", p.to_string()))?;
258
259        if let Err(e) = p.exec() {
260            let code = fail_fast_code(&e);
261            let unit_err = UnitTestError {
262                unit: unit.clone(),
263                kind: TestKind::Doctest,
264            };
265            report_test_error(ws, test_args, &options.compile_opts, &unit_err, e);
266            errors.push(unit_err);
267            if !options.no_fail_fast {
268                return Err(CliError::code(code));
269            }
270        }
271    }
272    Ok(errors)
273}
274
275/// Displays human-readable descriptions of the test executables.
276///
277/// This is used when `cargo test --no-run` is used.
278fn display_no_run_information(
279    ws: &Workspace<'_>,
280    test_args: &[&str],
281    compilation: &Compilation<'_>,
282    exec_type: &str,
283) -> CargoResult<()> {
284    let gctx = ws.gctx();
285    let cwd = gctx.cwd();
286    for UnitOutput {
287        unit,
288        path,
289        script_metas,
290    } in compilation.tests.iter()
291    {
292        let (exe_display, cmd) = cmd_builds(
293            gctx,
294            cwd,
295            unit,
296            path,
297            script_metas.as_ref(),
298            test_args,
299            compilation,
300            exec_type,
301        )?;
302        gctx.shell()
303            .concise(|shell| shell.status("Executable", &exe_display))?;
304        gctx.shell()
305            .verbose(|shell| shell.status("Executable", &cmd))?;
306    }
307
308    return Ok(());
309}
310
311/// Creates a [`ProcessBuilder`] for executing a single test.
312///
313/// Returns a tuple `(exe_display, process)` where `exe_display` is a string
314/// to display that describes the executable path in a human-readable form.
315/// `process` is the `ProcessBuilder` to use for executing the test.
316fn cmd_builds(
317    gctx: &GlobalContext,
318    cwd: &Path,
319    unit: &Unit,
320    path: &PathBuf,
321    script_metas: Option<&Vec<UnitHash>>,
322    test_args: &[&str],
323    compilation: &Compilation<'_>,
324    exec_type: &str,
325) -> CargoResult<(String, ProcessBuilder)> {
326    let test_path = unit.target.src_path().path().unwrap();
327    let short_test_path = test_path
328        .strip_prefix(unit.pkg.root())
329        .unwrap_or(test_path)
330        .display();
331
332    let exe_display = match unit.target.kind() {
333        TargetKind::Test | TargetKind::Bench => format!(
334            "{} ({})",
335            short_test_path,
336            path.strip_prefix(cwd).unwrap_or(path).display()
337        ),
338        _ => format!(
339            "{} {} ({})",
340            exec_type,
341            short_test_path,
342            path.strip_prefix(cwd).unwrap_or(path).display()
343        ),
344    };
345
346    let mut cmd = compilation.target_process(path, unit.kind, &unit.pkg, script_metas)?;
347    cmd.args(test_args);
348    if unit.target.harness() && gctx.shell().verbosity() == Verbosity::Quiet {
349        cmd.arg("--quiet");
350    }
351
352    Ok((exe_display, cmd))
353}
354
355/// Returns the error code to use when *not* using `--no-fail-fast`.
356///
357/// Cargo will return the error code from the test process itself. If some
358/// other error happened (like a failure to launch the process), then it will
359/// return a standard 101 error code.
360///
361/// When using `--no-fail-fast`, Cargo always uses the 101 exit code (since
362/// there may not be just one process to report).
363fn fail_fast_code(error: &anyhow::Error) -> i32 {
364    if let Some(proc_err) = error.downcast_ref::<ProcessError>() {
365        if let Some(code) = proc_err.code {
366            return code;
367        }
368    }
369    101
370}
371
372/// Returns the `CliError` when using `--no-fail-fast` and there is at least
373/// one error.
374fn no_fail_fast_err(
375    ws: &Workspace<'_>,
376    opts: &ops::CompileOptions,
377    errors: &[UnitTestError],
378) -> CliResult {
379    // TODO: This could be improved by combining the flags on a single line when feasible.
380    let args: Vec<_> = errors
381        .iter()
382        .map(|unit_err| format!("    `{}`", unit_err.cli_args(ws, opts)))
383        .collect();
384    let message = match errors.len() {
385        0 => return Ok(()),
386        1 => format!("1 target failed:\n{}", args.join("\n")),
387        n => format!("{n} targets failed:\n{}", args.join("\n")),
388    };
389    Err(anyhow::Error::msg(message).into())
390}
391
392/// Displays an error on the console about a test failure.
393fn report_test_error(
394    ws: &Workspace<'_>,
395    test_args: &[&str],
396    opts: &ops::CompileOptions,
397    unit_err: &UnitTestError,
398    test_error: anyhow::Error,
399) {
400    let which = match unit_err.kind {
401        TestKind::Test => "test failed",
402        TestKind::Bench => "bench failed",
403        TestKind::Doctest => "doctest failed",
404    };
405
406    let mut err = format_err!("{}, to rerun pass `{}`", which, unit_err.cli_args(ws, opts));
407    // Don't show "process didn't exit successfully" for simple errors.
408    // libtest exits with 101 for normal errors.
409    let (is_simple, executed) = test_error
410        .downcast_ref::<ProcessError>()
411        .and_then(|proc_err| proc_err.code)
412        .map_or((false, false), |code| (code == 101, true));
413
414    if !is_simple {
415        err = test_error.context(err);
416    }
417
418    crate::display_error(&err, &mut ws.gctx().shell());
419
420    let harness: bool = unit_err.unit.target.harness();
421    let nocapture: bool = test_args.contains(&"--nocapture") || test_args.contains(&"--no-capture");
422
423    if !is_simple && executed && harness && !nocapture {
424        drop(ws.gctx().shell().note(
425            "test exited abnormally; to see the full output pass --no-capture to the harness.",
426        ));
427    }
428}