diff --git a/crates/cargo-test-macro/src/lib.rs b/crates/cargo-test-macro/src/lib.rs
index aa06f477de0..112c020ed9b 100644
--- a/crates/cargo-test-macro/src/lib.rs
+++ b/crates/cargo-test-macro/src/lib.rs
@@ -133,6 +133,9 @@ pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
add_attr(&mut ret, "ignore", reason);
}
+ let mut test_name = None;
+ let mut num = 0;
+
// Find where the function body starts, and add the boilerplate at the start.
for token in item {
let group = match token {
@@ -144,18 +147,35 @@ pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
continue;
}
}
+ TokenTree::Ident(i) => {
+ // The first time through it will be `fn` the second time is the
+ // name of the test.
+ if test_name.is_none() && num == 1 {
+ test_name = Some(i.to_string())
+ } else {
+ num += 1;
+ }
+ ret.extend(Some(TokenTree::Ident(i)));
+ continue;
+ }
other => {
ret.extend(Some(other));
continue;
}
};
- let mut new_body = to_token_stream(
- r#"let _test_guard = {
+ let name = &test_name
+ .clone()
+ .map(|n| n.split("::").next().unwrap().to_string())
+ .unwrap();
+
+ let mut new_body = to_token_stream(&format!(
+ r#"let _test_guard = {{
let tmp_dir = option_env!("CARGO_TARGET_TMPDIR");
- cargo_test_support::paths::init_root(tmp_dir)
- };"#,
- );
+ let test_dir = cargo_test_support::paths::test_dir(std::file!(), "{name}");
+ cargo_test_support::paths::init_root(tmp_dir, test_dir)
+ }};"#
+ ));
new_body.extend(group.stream());
ret.extend(Some(TokenTree::from(Group::new(
diff --git a/crates/cargo-test-support/src/paths.rs b/crates/cargo-test-support/src/paths.rs
index ef1fddb7003..f1fc1bc298f 100644
--- a/crates/cargo-test-support/src/paths.rs
+++ b/crates/cargo-test-support/src/paths.rs
@@ -7,7 +7,6 @@ use std::fs;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::Command;
-use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
static CARGO_INTEGRATION_TEST_DIR: &str = "cit";
@@ -51,28 +50,20 @@ pub fn global_root() -> PathBuf {
}
}
-// We need to give each test a unique id. The test name could serve this
-// purpose, but the `test` crate doesn't have a way to obtain the current test
-// name.[*] Instead, we used the `cargo-test-macro` crate to automatically
-// insert an init function for each test that sets the test name in a thread
-// local variable.
-//
-// [*] It does set the thread name, but only when running concurrently. If not
-// running concurrently, all tests are run on the main thread.
+// We need to give each test a unique id. The test name serve this
+// purpose. We are able to get the test name by having the `cargo-test-macro`
+// crate automatically insert an init function for each test that sets the
+// test name in a thread local variable.
thread_local! {
- static TEST_ID: RefCell