Skip to main content

cargo_test_macro/
lib.rs

1//! # Cargo test macro.
2//!
3//! This is meant to be consumed alongside `cargo-test-support`. See
4//! <https://rust-lang.github.io/cargo/contrib/> for a guide on writing tests.
5//!
6//! > This crate is maintained by the Cargo team, primarily for use by Cargo
7//! > and not intended for external use. This
8//! > crate may make major changes to its APIs or be deprecated without warning.
9
10use proc_macro::*;
11use std::path::Path;
12use std::process::Command;
13use std::sync::LazyLock;
14
15/// Replacement for `#[test]`
16///
17/// The `#[cargo_test]` attribute extends `#[test]` with some setup before starting the test.
18/// It will create a filesystem "sandbox" under the "cargo integration test" directory for each test, such as `/path/to/cargo/target/tmp/cit/t123/`.
19/// The sandbox will contain a `home` directory that will be used instead of your normal home directory.
20///
21/// The `#[cargo_test]` attribute takes several options that will affect how the test is generated.
22/// They are listed in parentheses separated with commas, such as:
23///
24/// ```rust,ignore
25/// #[cargo_test(nightly, reason = "-Zfoo is unstable")]
26/// ```
27///
28/// The options it supports are:
29///
30/// * `>=1.64` --- This indicates that the test will only run with the given version of `rustc` or newer.
31///   This can be used when a new `rustc` feature has been stabilized that the test depends on.
32///   If this is specified, a `reason` is required to explain why it is being checked.
33/// * `nightly` --- This will cause the test to be ignored if not running on the nightly toolchain.
34///   This is useful for tests that use unstable options in `rustc` or `rustdoc`.
35///   These tests are run in Cargo's CI, but are disabled in rust-lang/rust's CI due to the difficulty of updating both repos simultaneously.
36///   A `reason` field is required to explain why it is nightly-only.
37/// * `requires = "<cmd>"` --- This indicates a command that is required to be installed to be run.
38///   For example, `requires = "rustfmt"` means the test will only run if the executable `rustfmt` is installed.
39///   These tests are run in Cargo's CI when CARGO_TEST_REQUIRE_EXTERNAL_TOOLS is set.
40///   Other environments, including rust-lang/rust's CI, ignore the test when the command is unavailable.
41///   This is mainly used to avoid requiring contributors from having every dependency installed.
42/// * `requires_rustup_stable` --- This requires `rustup` on `PATH` and an installed stable toolchain.
43///   These tests are disabled in rust-lang/rust CI.
44/// * `requires_host_split_debuginfo = "<value>"` --- This indicates a `-Csplit-debuginfo` value
45///   that is required to be supported by the host `rustc`.
46/// * `build_std_real` --- This is a "real" `-Zbuild-std` test (in the `build_std` integration test).
47///   This only runs on nightly, and only if the environment variable `CARGO_RUN_BUILD_STD_TESTS` is set (these tests on run on Linux).
48/// * `build_std_mock` --- This is a "mock" `-Zbuild-std` test (which uses a mock standard library).
49///   This only runs on nightly, and is disabled for windows-gnu.
50/// * `public_network_test` --- This tests contacts the public internet.
51///   These tests are disabled unless the `CARGO_PUBLIC_NETWORK_TESTS` environment variable is set.
52///   Use of this should be *extremely rare*, please avoid using it if possible.
53///   The hosts it contacts should have a relatively high confidence that they are reliable and stable (such as github.com), especially in CI.
54///   The tests should be carefully considered for developer security and privacy as well.
55/// * `container_test` --- This indicates that it is a test that uses Docker.
56///   These tests are disabled unless the `CARGO_CONTAINER_TESTS` environment variable is set.
57///   This requires that you have Docker installed.
58///   The SSH tests also assume that you have OpenSSH installed.
59///   These should work on Linux, macOS, and Windows where possible.
60///   Unfortunately these tests are not run in CI for macOS or Windows (no Docker on macOS, and Windows does not support Linux images).
61///   See [`cargo-test-support::containers`](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support/containers) for more on writing these tests.
62/// * `ignore_windows="reason"` --- Indicates that the test should be ignored on windows for the given reason.
63#[proc_macro_attribute]
64pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
65    // Ideally these options would be embedded in the test itself. However, I
66    // find it very helpful to have the test clearly state whether or not it
67    // is ignored. It would be nice to have some kind of runtime ignore
68    // support (such as
69    // https://internals.rust-lang.org/t/pre-rfc-skippable-tests/14611).
70    //
71    // Unfortunately a big drawback here is that if the environment changes
72    // (such as the existence of the `git` CLI), this will not trigger a
73    // rebuild and the test will still be ignored. In theory, something like
74    // `tracked_env` or `tracked_path`
75    // (https://github.com/rust-lang/rust/issues/99515) could help with this,
76    // but they don't really handle the absence of files well.
77    let mut ignore = false;
78    let mut requires_reason = false;
79    let mut explicit_reason = None;
80    let mut implicit_reasons = Vec::new();
81    macro_rules! set_ignore {
82        ($predicate:expr, $($arg:tt)*) => {
83            let p = $predicate;
84            ignore |= p;
85            if p {
86                implicit_reasons.push(std::fmt::format(format_args!($($arg)*)));
87            }
88        };
89    }
90    let is_not_nightly = !version().1;
91    for rule in split_rules(attr) {
92        match rule.as_str() {
93            "build_std_real" => {
94                // Only run the "real" build-std tests on nightly and with an
95                // explicit opt-in (these generally only work on linux, and
96                // have some extra requirements, and are slow, and can pollute
97                // the environment since it downloads dependencies).
98                set_ignore!(is_not_nightly, "requires nightly");
99                set_ignore!(
100                    option_env!("CARGO_RUN_BUILD_STD_TESTS").is_none(),
101                    "CARGO_RUN_BUILD_STD_TESTS must be set"
102                );
103            }
104            "build_std_mock" => {
105                // Only run the "mock" build-std tests on nightly and disable
106                // for windows-gnu which is missing object files (see
107                // https://github.com/rust-lang/wg-cargo-std-aware/issues/46).
108                set_ignore!(is_not_nightly, "requires nightly");
109                set_ignore!(
110                    cfg!(all(target_os = "windows", target_env = "gnu")),
111                    "does not work on windows-gnu"
112                );
113            }
114            "container_test" => {
115                // These tests must be opt-in because they require docker.
116                set_ignore!(
117                    option_env!("CARGO_CONTAINER_TESTS").is_none(),
118                    "CARGO_CONTAINER_TESTS must be set"
119                );
120            }
121            "public_network_test" => {
122                // These tests must be opt-in because they touch the public
123                // network. The use of these should be **EXTREMELY RARE**, and
124                // should only touch things which would nearly certainly work
125                // in CI (like github.com).
126                set_ignore!(
127                    option_env!("CARGO_PUBLIC_NETWORK_TESTS").is_none(),
128                    "CARGO_PUBLIC_NETWORK_TESTS must be set"
129                );
130            }
131            "nightly" => {
132                requires_reason = true;
133                set_ignore!(is_not_nightly, "requires nightly");
134            }
135            "requires_rustup_stable" => {
136                set_ignore!(
137                    !has_rustup_stable(),
138                    "rustup or stable toolchain not installed"
139                );
140            }
141            s if s.starts_with("requires=") => {
142                let command = &s[9..];
143                let Ok(literal) = command.parse::<Literal>() else {
144                    panic!("expect a string literal, found: {command}");
145                };
146                let literal = literal.to_string();
147                let Some(command) = literal
148                    .strip_prefix('"')
149                    .and_then(|lit| lit.strip_suffix('"'))
150                else {
151                    panic!("expect a quoted string literal, found: {literal}");
152                };
153                set_ignore!(!has_command(command), "{command} not installed");
154            }
155            s if s.starts_with("requires_host_split_debuginfo=") => {
156                let split_debuginfo = &s[30..];
157                let Ok(literal) = split_debuginfo.parse::<Literal>() else {
158                    panic!("expect a string literal, found: {split_debuginfo}");
159                };
160                let literal = literal.to_string();
161                let Some(split_debuginfo) = literal
162                    .strip_prefix('"')
163                    .and_then(|lit| lit.strip_suffix('"'))
164                else {
165                    panic!("expect a quoted string literal, found: {literal}");
166                };
167                set_ignore!(
168                    !host_supports_split_debuginfo(split_debuginfo),
169                    "host rustc does not support -Csplit-debuginfo={split_debuginfo}"
170                );
171            }
172            s if s.starts_with(">=1.") => {
173                requires_reason = true;
174                let min_minor = s[4..].parse().unwrap();
175                let minor = version().0;
176                set_ignore!(minor < min_minor, "requires rustc 1.{minor} or newer");
177            }
178            s if s.starts_with("reason=") => {
179                explicit_reason = Some(s[7..].parse().unwrap());
180            }
181            s if s.starts_with("ignore_windows=") => {
182                set_ignore!(cfg!(windows), "{}", &s[16..s.len() - 1]);
183            }
184            _ => panic!("unknown rule {:?}", rule),
185        }
186    }
187    if requires_reason && explicit_reason.is_none() {
188        panic!(
189            "#[cargo_test] with a rule also requires a reason, \
190            such as #[cargo_test(nightly, reason = \"needs -Z unstable-thing\")]"
191        );
192    }
193
194    // Construct the appropriate attributes.
195    let span = Span::call_site();
196    let mut ret = TokenStream::new();
197    let add_attr = |ret: &mut TokenStream, attr_name, attr_input| {
198        ret.extend(Some(TokenTree::from(Punct::new('#', Spacing::Alone))));
199        let attr = TokenTree::from(Ident::new(attr_name, span));
200        let mut attr_stream: TokenStream = attr.into();
201        if let Some(input) = attr_input {
202            attr_stream.extend(input);
203        }
204        ret.extend(Some(TokenTree::from(Group::new(
205            Delimiter::Bracket,
206            attr_stream,
207        ))));
208    };
209    add_attr(&mut ret, "test", None);
210    if ignore {
211        let reason = explicit_reason
212            .or_else(|| {
213                (!implicit_reasons.is_empty())
214                    .then(|| TokenTree::from(Literal::string(&implicit_reasons.join(", "))).into())
215            })
216            .map(|reason: TokenStream| {
217                let mut stream = TokenStream::new();
218                stream.extend(Some(TokenTree::from(Punct::new('=', Spacing::Alone))));
219                stream.extend(Some(reason));
220                stream
221            });
222        add_attr(&mut ret, "ignore", reason);
223    }
224
225    let mut test_name = None;
226    let mut num = 0;
227
228    // Find where the function body starts, and add the boilerplate at the start.
229    for token in item {
230        let group = match token {
231            TokenTree::Group(g) => {
232                if g.delimiter() == Delimiter::Brace {
233                    g
234                } else {
235                    ret.extend(Some(TokenTree::Group(g)));
236                    continue;
237                }
238            }
239            TokenTree::Ident(i) => {
240                // The first time through it will be `fn` the second time is the
241                // name of the test.
242                if test_name.is_none() && num == 1 {
243                    test_name = Some(i.to_string())
244                } else {
245                    num += 1;
246                }
247                ret.extend(Some(TokenTree::Ident(i)));
248                continue;
249            }
250            other => {
251                ret.extend(Some(other));
252                continue;
253            }
254        };
255
256        let name = &test_name
257            .clone()
258            .map(|n| n.split("::").next().unwrap().to_string())
259            .unwrap();
260
261        let mut new_body = to_token_stream(&format!(
262            r#"let _test_guard = {{
263                let tmp_dir = env!("CARGO_TARGET_TMPDIR");
264                let test_dir = cargo_test_support::paths::test_dir(std::file!(), "{name}");
265                cargo_test_support::paths::init_root(tmp_dir, test_dir)
266            }};"#
267        ));
268
269        new_body.extend(group.stream());
270        ret.extend(Some(TokenTree::from(Group::new(
271            group.delimiter(),
272            new_body,
273        ))));
274    }
275
276    ret
277}
278
279fn split_rules(t: TokenStream) -> Vec<String> {
280    let tts: Vec<_> = t.into_iter().collect();
281    tts.split(|tt| match tt {
282        TokenTree::Punct(p) => p.as_char() == ',',
283        _ => false,
284    })
285    .filter(|parts| !parts.is_empty())
286    .map(|parts| {
287        parts
288            .into_iter()
289            .map(|part| part.to_string())
290            .collect::<String>()
291    })
292    .collect()
293}
294
295fn to_token_stream(code: &str) -> TokenStream {
296    code.parse().unwrap()
297}
298
299static VERSION: std::sync::LazyLock<(u32, bool)> = LazyLock::new(|| {
300    let output = Command::new("rustc")
301        .arg("-V")
302        .output()
303        .expect("rustc should run");
304
305    let exit_code = output.status.code();
306
307    if exit_code != Some(0) {
308        let stdout = std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>");
309        let stderr = std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>");
310        // On Windows, exit code `0xC0000017` is not very well documented but appears to
311        // usually happen when a command length exceeds the windows limit.
312        // Since we are just running `rustc -V` it likely that the PATH got too long.
313        // This can happen when Cargo's tests are executed from rustc bootstrap.
314        let extra = if exit_code.map(|c| c as u32) == Some(0xC0000017) {
315            "This likely indicates that PATH is too large for Windows.\n"
316        } else {
317            ""
318        };
319        panic!(
320            "'rustc -V' exited with non-zero exit code: {exit_code:?}\n{extra}stdout: {stdout}\nstderr: {stderr}",
321        );
322    }
323
324    let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
325    let vers = stdout
326        .split_whitespace()
327        .skip(1)
328        .next()
329        .expect("version should have contain at least one space");
330    let is_nightly = option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_none()
331        && (vers.contains("-nightly") || vers.contains("-dev"));
332    let minor = vers
333        .split('.')
334        .skip(1)
335        .next()
336        .expect("malformed rustc version (not semver)")
337        .parse()
338        .expect("malformed rustc version (minor version was not u32)");
339    (minor, is_nightly)
340});
341
342fn version() -> (u32, bool) {
343    LazyLock::force(&VERSION).clone()
344}
345
346fn host_supports_split_debuginfo(split_debuginfo: &str) -> bool {
347    static SPLIT_DEBUGINFO: LazyLock<Vec<String>> = LazyLock::new(|| {
348        let output = Command::new("rustc")
349            .arg("--print=split-debuginfo")
350            .output()
351            .expect("rustc should run");
352
353        let exit_code = output.status.code();
354        if exit_code != Some(0) {
355            let stdout = std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>");
356            let stderr = std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>");
357            panic!(
358                "'rustc --print=split-debuginfo' exited with non-zero exit code: {exit_code:?}\n\
359                stdout: {stdout}\n\
360                stderr: {stderr}",
361            );
362        }
363
364        let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
365        stdout.lines().map(str::to_owned).collect()
366    });
367
368    SPLIT_DEBUGINFO
369        .iter()
370        .any(|supported| supported == split_debuginfo)
371}
372
373fn check_command(command_path: &Path, args: &[&str]) -> bool {
374    let mut command = Command::new(command_path);
375    let command_name = command.get_program().to_str().unwrap().to_owned();
376    command.args(args);
377    let output = match command.output() {
378        Ok(output) => output,
379        Err(e) => {
380            if is_ci() {
381                panic!("expected command `{command_name}` to be somewhere in PATH: {e}",);
382            }
383            return false;
384        }
385    };
386    if !output.status.success() {
387        // Debian specific patch, upstream wontfix:
388        // qemu has a faulty vfork where it fails to fail if a command is not
389        // found, with a unix_wait_status of 32512, or 0x7f00, 7f meaning
390        // exit code 127. See https://github.com/rust-lang/rust/issues/90825
391        use std::os::unix::process::ExitStatusExt;
392        if output.status.into_raw() == 0x7f00 {
393            return false;
394        }
395        panic!(
396            "expected command `{command_name}` to be runnable, got error {}:\n\
397            stderr:{}\n\
398            stdout:{}\n",
399            output.status,
400            String::from_utf8_lossy(&output.stderr),
401            String::from_utf8_lossy(&output.stdout)
402        );
403    }
404    true
405}
406
407fn has_command(command: &str) -> bool {
408    use std::env::consts::EXE_EXTENSION;
409    // ALLOWED: For testing cargo itself only.
410    #[allow(clippy::disallowed_methods)]
411    let Some(paths) = std::env::var_os("PATH") else {
412        return false;
413    };
414    let found = std::env::split_paths(&paths)
415        .flat_map(|path| {
416            let candidate = path.join(&command);
417            let with_exe = if EXE_EXTENSION.is_empty() {
418                None
419            } else {
420                Some(candidate.with_extension(EXE_EXTENSION))
421            };
422            std::iter::once(candidate).chain(with_exe)
423        })
424        .find(|p| is_executable(p))
425        .is_some();
426    // * hg is not installed on GitHub macOS or certain constrained
427    //   environments like Docker. Consider installing it if Cargo
428    //   gains more hg support, but otherwise it isn't critical.
429    if !found && requires_external_tools() && command != "hg" {
430        panic!("expected command `{command}` to be somewhere in PATH");
431    }
432    found
433}
434
435#[cfg(unix)]
436fn is_executable<P: AsRef<Path>>(path: P) -> bool {
437    use std::os::unix::prelude::*;
438    std::fs::metadata(path)
439        .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
440        .unwrap_or(false)
441}
442
443#[cfg(windows)]
444fn is_executable<P: AsRef<Path>>(path: P) -> bool {
445    path.as_ref().is_file()
446}
447
448fn has_rustup_stable() -> bool {
449    if option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_some() {
450        // This cannot run on rust-lang/rust CI due to the lack of rustup.
451        return false;
452    }
453    check_command(
454        Path::new("rustup"),
455        &["run", "stable", "cargo", "--version"],
456    )
457}
458
459/// Whether or not this running in a Continuous Integration environment.
460fn is_ci() -> bool {
461    // Consider using `tracked_env` instead of option_env! when it is stabilized.
462    // `tracked_env` will handle changes, but not require rebuilding the macro
463    // itself like option_env does.
464    option_env!("CI").is_some() || option_env!("TF_BUILD").is_some()
465}
466
467/// Whether to enforce external tools (`requires=<tool>`) availability.
468fn requires_external_tools() -> bool {
469    option_env!("CARGO_TEST_REQUIRE_EXTERNAL_TOOLS").is_some()
470}