Skip to content

Commit 2e35678

Browse files
committed
Auto merge of #9892 - ehuss:cargo_test-ignore-reason, r=weihanglo
Add requirements to cargo_test. This extends the `#[cargo_test]` attribute to support some additional requirements to control whether or not a test can run. The motivation for this is: * Can more clearly see when a test is disabled when it prints "ignored" * Can more easily scan for disabled tests when I do version bumps to see which ones should be enabled on stable (to pass on CI). The form is a comma separated list of requirements, and if they don't pass the test is ignored. The requirements can be: * `nightly` — The test only runs on nightly. * `>=1.55` — The test only runs on rustc with the given version or newer. * `requires_git` — Requires the given command to be installed. Can be things like `requires_rustfmt` or `requires_hg`, etc. This also enforces that the author must write a reason why it is ignored (for some of the requirements) so that when I look for tests to update, I know why it is disabled. This also removes the `CARGO_TEST_DISABLE_GIT_CLI` option, which appears to no longer be necessary since we have migrated to GitHub Actions.
2 parents 85e79fc + 8e35e2f commit 2e35678

File tree

29 files changed

+414
-897
lines changed

29 files changed

+414
-897
lines changed

crates/cargo-test-macro/src/lib.rs

Lines changed: 142 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,84 @@
11
extern crate proc_macro;
22

33
use proc_macro::*;
4+
use std::process::Command;
5+
use std::sync::Once;
46

57
#[proc_macro_attribute]
68
pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
9+
// Ideally these options would be embedded in the test itself. However, I
10+
// find it very helpful to have the test clearly state whether or not it
11+
// is ignored. It would be nice to have some kind of runtime ignore
12+
// support (such as
13+
// https://internals.rust-lang.org/t/pre-rfc-skippable-tests/14611).
14+
//
15+
// Unfortunately a big drawback here is that if the environment changes
16+
// (such as the existence of the `git` CLI), this will not trigger a
17+
// rebuild and the test will still be ignored. In theory, something like
18+
// `tracked_env` or `tracked_path`
19+
// (https://github.com/rust-lang/rust/issues/99515) could help with this,
20+
// but they don't really handle the absence of files well.
21+
let mut ignore = false;
22+
let mut requires_reason = false;
23+
let mut found_reason = false;
24+
let is_not_nightly = !version().1;
25+
for rule in split_rules(attr) {
26+
match rule.as_str() {
27+
"build_std_real" => {
28+
// Only run the "real" build-std tests on nightly and with an
29+
// explicit opt-in (these generally only work on linux, and
30+
// have some extra requirements, and are slow, and can pollute
31+
// the environment since it downloads dependencies).
32+
ignore |= is_not_nightly;
33+
ignore |= option_env!("CARGO_RUN_BUILD_STD_TESTS").is_none();
34+
}
35+
"build_std_mock" => {
36+
// Only run the "mock" build-std tests on nightly and disable
37+
// for windows-gnu which is missing object files (see
38+
// https://github.com/rust-lang/wg-cargo-std-aware/issues/46).
39+
ignore |= is_not_nightly;
40+
ignore |= cfg!(all(target_os = "windows", target_env = "gnu"));
41+
}
42+
"nightly" => {
43+
requires_reason = true;
44+
ignore |= is_not_nightly;
45+
}
46+
s if s.starts_with("requires_") => {
47+
let command = &s[9..];
48+
ignore |= !has_command(command);
49+
}
50+
s if s.starts_with(">=1.") => {
51+
requires_reason = true;
52+
let min_minor = s[4..].parse().unwrap();
53+
ignore |= version().0 < min_minor;
54+
}
55+
s if s.starts_with("reason=") => {
56+
found_reason = true;
57+
}
58+
_ => panic!("unknown rule {:?}", rule),
59+
}
60+
}
61+
if requires_reason && !found_reason {
62+
panic!(
63+
"#[cargo_test] with a rule also requires a reason, \
64+
such as #[cargo_test(nightly, reason = \"needs -Z unstable-thing\")]"
65+
);
66+
}
67+
768
let span = Span::call_site();
869
let mut ret = TokenStream::new();
9-
ret.extend(Some(TokenTree::from(Punct::new('#', Spacing::Alone))));
10-
let test = TokenTree::from(Ident::new("test", span));
11-
ret.extend(Some(TokenTree::from(Group::new(
12-
Delimiter::Bracket,
13-
test.into(),
14-
))));
15-
16-
let build_std = contains_ident(&attr, "build_std");
70+
let add_attr = |ret: &mut TokenStream, attr_name| {
71+
ret.extend(Some(TokenTree::from(Punct::new('#', Spacing::Alone))));
72+
let attr = TokenTree::from(Ident::new(attr_name, span));
73+
ret.extend(Some(TokenTree::from(Group::new(
74+
Delimiter::Bracket,
75+
attr.into(),
76+
))));
77+
};
78+
add_attr(&mut ret, "test");
79+
if ignore {
80+
add_attr(&mut ret, "ignore");
81+
}
1782

1883
for token in item {
1984
let group = match token {
@@ -38,17 +103,6 @@ pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
38103
};"#,
39104
);
40105

41-
// If this is a `build_std` test (aka `tests/build-std/*.rs`) then they
42-
// only run on nightly and they only run when specifically instructed to
43-
// on CI.
44-
if build_std {
45-
let ts = to_token_stream("if !cargo_test_support::is_nightly() { return }");
46-
new_body.extend(ts);
47-
let ts = to_token_stream(
48-
"if std::env::var(\"CARGO_RUN_BUILD_STD_TESTS\").is_err() { return }",
49-
);
50-
new_body.extend(ts);
51-
}
52106
new_body.extend(group.stream());
53107
ret.extend(Some(TokenTree::from(Group::new(
54108
group.delimiter(),
@@ -59,13 +113,79 @@ pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
59113
ret
60114
}
61115

62-
fn contains_ident(t: &TokenStream, ident: &str) -> bool {
63-
t.clone().into_iter().any(|t| match t {
64-
TokenTree::Ident(i) => i.to_string() == ident,
116+
fn split_rules(t: TokenStream) -> Vec<String> {
117+
let tts: Vec<_> = t.into_iter().collect();
118+
tts.split(|tt| match tt {
119+
TokenTree::Punct(p) => p.as_char() == ',',
65120
_ => false,
66121
})
122+
.filter(|parts| !parts.is_empty())
123+
.map(|parts| {
124+
parts
125+
.into_iter()
126+
.map(|part| part.to_string())
127+
.collect::<String>()
128+
})
129+
.collect()
67130
}
68131

69132
fn to_token_stream(code: &str) -> TokenStream {
70133
code.parse().unwrap()
71134
}
135+
136+
static mut VERSION: (u32, bool) = (0, false);
137+
138+
fn version() -> &'static (u32, bool) {
139+
static INIT: Once = Once::new();
140+
INIT.call_once(|| {
141+
let output = Command::new("rustc")
142+
.arg("-V")
143+
.output()
144+
.expect("rustc should run");
145+
let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
146+
let vers = stdout.split_whitespace().skip(1).next().unwrap();
147+
let is_nightly = option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_none()
148+
&& (vers.contains("-nightly") || vers.contains("-dev"));
149+
let minor = vers.split('.').skip(1).next().unwrap().parse().unwrap();
150+
unsafe { VERSION = (minor, is_nightly) }
151+
});
152+
unsafe { &VERSION }
153+
}
154+
155+
fn has_command(command: &str) -> bool {
156+
let output = match Command::new(command).arg("--version").output() {
157+
Ok(output) => output,
158+
Err(e) => {
159+
// hg is not installed on GitHub macos.
160+
// Consider installing it if Cargo gains more hg support, but
161+
// otherwise it isn't critical.
162+
if is_ci() && !(cfg!(target_os = "macos") && command == "hg") {
163+
panic!(
164+
"expected command `{}` to be somewhere in PATH: {}",
165+
command, e
166+
);
167+
}
168+
return false;
169+
}
170+
};
171+
if !output.status.success() {
172+
panic!(
173+
"expected command `{}` to be runnable, got error {}:\n\
174+
stderr:{}\n\
175+
stdout:{}\n",
176+
command,
177+
output.status,
178+
String::from_utf8_lossy(&output.stderr),
179+
String::from_utf8_lossy(&output.stdout)
180+
);
181+
}
182+
true
183+
}
184+
185+
/// Whether or not this running in a Continuous Integration environment.
186+
fn is_ci() -> bool {
187+
// Consider using `tracked_env` instead of option_env! when it is stabilized.
188+
// `tracked_env` will handle changes, but not require rebuilding the macro
189+
// itself like option_env does.
190+
option_env!("CI").is_some() || option_env!("TF_BUILD").is_some()
191+
}

crates/cargo-test-support/src/lib.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,6 +1128,10 @@ pub fn rustc_host_env() -> String {
11281128

11291129
pub fn is_nightly() -> bool {
11301130
let vv = &RUSTC_INFO.verbose_version;
1131+
// CARGO_TEST_DISABLE_NIGHTLY is set in rust-lang/rust's CI so that all
1132+
// nightly-only tests are disabled there. Otherwise, it could make it
1133+
// difficult to land changes which would need to be made simultaneously in
1134+
// rust-lang/cargo and rust-lan/rust, which isn't possible.
11311135
env::var("CARGO_TEST_DISABLE_NIGHTLY").is_err()
11321136
&& (vv.contains("-nightly") || vv.contains("-dev"))
11331137
}
@@ -1350,16 +1354,6 @@ pub fn slow_cpu_multiplier(main: u64) -> Duration {
13501354
Duration::from_secs(*SLOW_CPU_MULTIPLIER * main)
13511355
}
13521356

1353-
pub fn command_is_available(cmd: &str) -> bool {
1354-
if let Err(e) = process(cmd).arg("-V").exec_with_output() {
1355-
eprintln!("{} not available, skipping tests", cmd);
1356-
eprintln!("{:?}", e);
1357-
false
1358-
} else {
1359-
true
1360-
}
1361-
}
1362-
13631357
#[cfg(windows)]
13641358
pub fn symlink_supported() -> bool {
13651359
if is_ci() {

src/doc/contrib/src/tests/writing.md

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,7 @@ fn <description>() {
5050
}
5151
```
5252

53-
`#[cargo_test]`:
54-
- This is used in place of `#[test]`
55-
- This attribute injects code which does some setup before starting the
56-
test, creating a filesystem "sandbox" under the "cargo integration test"
57-
directory for each test such as
58-
`/path/to/cargo/target/cit/t123/`
59-
- The sandbox will contain a `home` directory that will be used instead of your normal home directory
53+
The [`#[cargo_test]` attribute](#cargo_test-attribute) is used in place of `#[test]` to inject some setup code.
6054

6155
[`ProjectBuilder`] via `project()`:
6256
- Each project is in a separate directory in the sandbox
@@ -68,6 +62,37 @@ fn <description>() {
6862
- See [`support::compare`] for an explanation of the string pattern matching.
6963
Patterns are used to make it easier to match against the expected output.
7064

65+
#### `#[cargo_test]` attribute
66+
67+
The `#[cargo_test]` attribute injects code which does some setup before starting the test.
68+
It will create a filesystem "sandbox" under the "cargo integration test" directory for each test, such as `/path/to/cargo/target/tmp/cit/t123/`.
69+
The sandbox will contain a `home` directory that will be used instead of your normal home directory.
70+
71+
The `#[cargo_test]` attribute takes several options that will affect how the test is generated.
72+
They are listed in parentheses separated with commas, such as:
73+
74+
```rust,ignore
75+
#[cargo_test(nightly, reason = "-Zfoo is unstable")]
76+
```
77+
78+
The options it supports are:
79+
80+
* `nightly` — This will cause the test to be ignored if not running on the nightly toolchain.
81+
This is useful for tests that use unstable options in `rustc` or `rustdoc`.
82+
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.
83+
A `reason` field is required to explain why it is nightly-only.
84+
* `build_std_real` — This is a "real" `-Zbuild-std` test (in the `build_std` integration test).
85+
This only runs on nightly, and only if the environment variable `CARGO_RUN_BUILD_STD_TESTS` is set (these tests on run on Linux).
86+
* `build_std_mock` — This is a "mock" `-Zbuild-std` test (which uses a mock standard library).
87+
This only runs on nightly, and is disabled for windows-gnu.
88+
* `requires_` — This indicates a command that is required to be installed to be run.
89+
For example, `requires_rustfmt` means the test will only run if the executable `rustfmt` is installed.
90+
These tests are *always* run on CI.
91+
This is mainly used to avoid requiring contributors from having every dependency installed.
92+
* `>=1.64` — This indicates that the test will only run with the given version of `rustc` or newer.
93+
This can be used when a new `rustc` feature has been stabilized that the test depends on.
94+
If this is specified, a `reason` is required to explain why it is being checked.
95+
7196
#### Testing Nightly Features
7297

7398
If you are testing a Cargo feature that only works on "nightly" Cargo, then
@@ -79,16 +104,15 @@ p.cargo("build").masquerade_as_nightly_cargo(&["print-im-a-teapot"])
79104
```
80105

81106
If you are testing a feature that only works on *nightly rustc* (such as
82-
benchmarks), then you should exit the test if it is not running with nightly
83-
rust, like this:
107+
benchmarks), then you should use the `nightly` option of the `cargo_test`
108+
attribute, like this:
84109

85110
```rust,ignore
86-
if !is_nightly() {
87-
// Add a comment here explaining why this is necessary.
88-
return;
89-
}
111+
#[cargo_test(nightly, reason = "-Zfoo is unstable")]
90112
```
91113

114+
This will cause the test to be ignored if not running on the nightly toolchain.
115+
92116
#### Specifying Dependencies
93117

94118
You should not write any tests that use the network such as contacting
@@ -201,16 +225,15 @@ the name of the feature as the reason, like this:
201225
```
202226

203227
If you are testing a feature that only works on *nightly rustc* (such as
204-
benchmarks), then you should exit the test if it is not running with nightly
205-
rust, like this:
228+
benchmarks), then you should use the `nightly` option of the `cargo_test`
229+
attribute, like this:
206230

207231
```rust,ignore
208-
if !is_nightly() {
209-
// Add a comment here explaining why this is necessary.
210-
return;
211-
}
232+
#[cargo_test(nightly, reason = "-Zfoo is unstable")]
212233
```
213234

235+
This will cause the test to be ignored if not running on the nightly toolchain.
236+
214237
### Platform-specific Notes
215238

216239
When checking output, use `/` for paths even on Windows: the actual output

tests/build-std/main.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
//! not catching any regressions that `tests/testsuite/standard_lib.rs` isn't
1414
//! already catching.
1515
//!
16-
//! All tests here should use `#[cargo_test(build_std)]` to indicate that
16+
//! All tests here should use `#[cargo_test(build_std_real)]` to indicate that
1717
//! boilerplate should be generated to require the nightly toolchain and the
1818
//! `CARGO_RUN_BUILD_STD_TESTS` env var to be set to actually run these tests.
1919
//! Otherwise the tests are skipped.
@@ -59,7 +59,7 @@ impl BuildStd for Execs {
5959
}
6060
}
6161

62-
#[cargo_test(build_std)]
62+
#[cargo_test(build_std_real)]
6363
fn basic() {
6464
let p = project()
6565
.file(
@@ -127,7 +127,7 @@ fn basic() {
127127
assert_eq!(p.glob(deps_dir.join("*.dylib")).count(), 0);
128128
}
129129

130-
#[cargo_test(build_std)]
130+
#[cargo_test(build_std_real)]
131131
fn cross_custom() {
132132
let p = project()
133133
.file(
@@ -170,7 +170,7 @@ fn cross_custom() {
170170
.run();
171171
}
172172

173-
#[cargo_test(build_std)]
173+
#[cargo_test(build_std_real)]
174174
fn custom_test_framework() {
175175
let p = project()
176176
.file(

0 commit comments

Comments
 (0)