Skip to main content

cargo/ops/
cargo_test.rs

1use std::ffi::OsString;
2
3use crate::core::compiler::{Compilation, Doctest};
4use crate::core::Workspace;
5use crate::ops;
6use crate::util::errors::CargoResult;
7use crate::util::{self, CargoTestError, ProcessError, Test};
8
9pub struct TestOptions<'a> {
10    pub compile_opts: ops::CompileOptions<'a>,
11    pub no_run: bool,
12    pub no_fail_fast: bool,
13}
14
15pub fn run_tests(
16    ws: &Workspace<'_>,
17    options: &TestOptions<'_>,
18    test_args: &[String],
19) -> CargoResult<Option<CargoTestError>> {
20    let compilation = compile_tests(ws, options)?;
21
22    if options.no_run {
23        return Ok(None);
24    }
25    let (test, mut errors) = run_unit_tests(options, test_args, &compilation)?;
26
27    // If we have an error and want to fail fast, return
28    if !errors.is_empty() && !options.no_fail_fast {
29        return Ok(Some(CargoTestError::new(test, errors)));
30    }
31
32    let (doctest, docerrors) = run_doc_tests(options, test_args, &compilation)?;
33    let test = if docerrors.is_empty() { test } else { doctest };
34    errors.extend(docerrors);
35    if errors.is_empty() {
36        Ok(None)
37    } else {
38        Ok(Some(CargoTestError::new(test, errors)))
39    }
40}
41
42pub fn run_benches(
43    ws: &Workspace<'_>,
44    options: &TestOptions<'_>,
45    args: &[String],
46) -> CargoResult<Option<CargoTestError>> {
47    let mut args = args.to_vec();
48    args.push("--bench".to_string());
49    let compilation = compile_tests(ws, options)?;
50
51    if options.no_run {
52        return Ok(None);
53    }
54    let (test, errors) = run_unit_tests(options, &args, &compilation)?;
55    match errors.len() {
56        0 => Ok(None),
57        _ => Ok(Some(CargoTestError::new(test, errors))),
58    }
59}
60
61fn compile_tests<'a>(
62    ws: &Workspace<'a>,
63    options: &TestOptions<'a>,
64) -> CargoResult<Compilation<'a>> {
65    let mut compilation = ops::compile(ws, &options.compile_opts)?;
66    compilation
67        .tests
68        .sort_by(|a, b| (a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2)));
69    Ok(compilation)
70}
71
72/// Run the unit and integration tests of a package.
73fn run_unit_tests(
74    options: &TestOptions<'_>,
75    test_args: &[String],
76    compilation: &Compilation<'_>,
77) -> CargoResult<(Test, Vec<ProcessError>)> {
78    let config = options.compile_opts.config;
79    let cwd = options.compile_opts.config.cwd();
80
81    let mut errors = Vec::new();
82
83    for &(ref pkg, ref kind, ref test, ref exe) in &compilation.tests {
84        let to_display = match util::without_prefix(exe, cwd) {
85            Some(path) => path,
86            None => &**exe,
87        };
88        let mut cmd = compilation.target_process(exe, pkg)?;
89        cmd.args(test_args);
90        config
91            .shell()
92            .concise(|shell| shell.status("Running", to_display.display().to_string()))?;
93        config
94            .shell()
95            .verbose(|shell| shell.status("Running", cmd.to_string()))?;
96
97        let result = cmd.exec();
98
99        match result {
100            Err(e) => {
101                let e = e.downcast::<ProcessError>()?;
102                errors.push((kind.clone(), test.clone(), pkg.name().to_string(), e));
103                if !options.no_fail_fast {
104                    break;
105                }
106            }
107            Ok(()) => {}
108        }
109    }
110
111    if errors.len() == 1 {
112        let (kind, name, pkg_name, e) = errors.pop().unwrap();
113        Ok((
114            Test::UnitTest {
115                kind,
116                name,
117                pkg_name,
118            },
119            vec![e],
120        ))
121    } else {
122        Ok((
123            Test::Multiple,
124            errors.into_iter().map(|(_, _, _, e)| e).collect(),
125        ))
126    }
127}
128
129fn run_doc_tests(
130    options: &TestOptions<'_>,
131    test_args: &[String],
132    compilation: &Compilation<'_>,
133) -> CargoResult<(Test, Vec<ProcessError>)> {
134    let mut errors = Vec::new();
135    let config = options.compile_opts.config;
136
137    // We don't build/rust doctests if target != host
138    if compilation.host != compilation.target {
139        return Ok((Test::Doc, errors));
140    }
141
142    for doctest_info in &compilation.to_doc_test {
143        let Doctest {
144            package,
145            target,
146            deps,
147        } = doctest_info;
148        config.shell().status("Doc-tests", target.name())?;
149        let mut p = compilation.rustdoc_process(package, target)?;
150        p.arg("--test")
151            .arg(target.src_path().path().unwrap())
152            .arg("--crate-name")
153            .arg(&target.crate_name());
154
155        for &rust_dep in &[&compilation.deps_output] {
156            let mut arg = OsString::from("dependency=");
157            arg.push(rust_dep);
158            p.arg("-L").arg(arg);
159        }
160
161        for native_dep in compilation.native_dirs.iter() {
162            p.arg("-L").arg(native_dep);
163        }
164
165        for &host_rust_dep in &[&compilation.host_deps_output] {
166            let mut arg = OsString::from("dependency=");
167            arg.push(host_rust_dep);
168            p.arg("-L").arg(arg);
169        }
170
171        for arg in test_args {
172            p.arg("--test-args").arg(arg);
173        }
174
175        if let Some(cfgs) = compilation.cfgs.get(&package.package_id()) {
176            for cfg in cfgs.iter() {
177                p.arg("--cfg").arg(cfg);
178            }
179        }
180
181        for &(ref extern_crate_name, ref lib) in deps.iter() {
182            let mut arg = OsString::from(extern_crate_name);
183            arg.push("=");
184            arg.push(lib);
185            p.arg("--extern").arg(&arg);
186        }
187
188        if let Some(flags) = compilation.rustdocflags.get(&package.package_id()) {
189            p.args(flags);
190        }
191
192        config
193            .shell()
194            .verbose(|shell| shell.status("Running", p.to_string()))?;
195        if let Err(e) = p.exec() {
196            let e = e.downcast::<ProcessError>()?;
197            errors.push(e);
198            if !options.no_fail_fast {
199                return Ok((Test::Doc, errors));
200            }
201        }
202    }
203    Ok((Test::Doc, errors))
204}