test_temp_dir/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![warn(clippy::cognitive_complexity)]
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_time_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45#![allow(clippy::collapsible_if)] // See arti#2342
46#![deny(clippy::unused_async)]
47#![deny(clippy::string_slice)] // See arti#2571
48//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49
50// We have a nonstandard test lint block
51#![allow(clippy::print_stdout)]
52
53use std::env::{self, VarError};
54use std::fs;
55use std::io::{self, ErrorKind};
56use std::marker::PhantomData;
57use std::path::{Path, PathBuf};
58
59use anyhow::{Context as _, anyhow};
60use derive_more::{Deref, DerefMut};
61use educe::Educe;
62
63/// The env var the user should set to control test temp dir handling
64const RETAIN_VAR: &str = "TEST_TEMP_RETAIN";
65
66/// Directory for a test to store temporary files
67///
68/// Automatically deleted (if appropriate) when dropped.
69#[derive(Debug)]
70#[non_exhaustive]
71pub enum TestTempDir {
72 /// An ephemeral directory
73 Ephemeral(tempfile::TempDir),
74 /// A directory which should persist after the test completes
75 Persistent(PathBuf),
76}
77
78/// A `T` which relies on some temporary directory with lifetime `d`
79///
80/// Obtained from `TestTempDir::used_by`.
81///
82/// Using this type means that the `T` won't outlive the temporary directory.
83/// (Typically, if it were to, things would malfunction.
84/// There might even be security hazards!)
85#[derive(Clone, Copy, Deref, DerefMut, Educe)]
86#[educe(Debug(bound))]
87pub struct TestTempDirGuard<'d, T> {
88 /// The thing
89 #[deref]
90 #[deref_mut]
91 thing: T,
92
93 /// Placate the compiler
94 ///
95 /// We use a notional `()` since we don't want the compiler to infer drop glue.
96 #[educe(Debug(ignore))]
97 tempdir: PhantomData<&'d ()>,
98}
99
100impl TestTempDir {
101 /// Obtain a temp dir named after our thread, and the module path `mod_path`
102 ///
103 /// Expects that the current thread name is the module path within the crate,
104 /// followed by the test function name.
105 /// (This is how Rust's builtin `#[test]` names its threads.)
106 // This is also used by some other crates.
107 // If it turns out not to be true, we'll end up panicking.
108 //
109 // This is rather a shonky approach. We take it here for the following reasons:
110 //
111 // It is important that the persistent test output filename is stable,
112 // even if the source code is edited. For example, if we used the line number
113 // of the macro call, editing the source would change the output filenames.
114 // When the output filenames change willy-nilly, it is very easy to accidentally
115 // look at an out-of-date filename containing out-of-date test data,
116 // which can be very confusing.
117 //
118 // We could ask the user to supply a string, but we'd then need
119 // some kind of contraption for verifying its uniqueness, since
120 // non-unique test names would risk tests overwriting each others'
121 // files, making for flaky or malfunctioning tests.
122 //
123 // So the test function name is the best stable identifier we have,
124 // and the thread name is the only way we have of discovering it.
125 // Happily this works with `cargo nextest` too.
126 //
127 // For the same reasons, it wouldn't be a good idea to fall back
128 // from the stable name to some less stable but more reliably obtainable id.
129 //
130 // And, the code structure is deliberately arranged that we *always*
131 // try to determine the test name, even if TEST_TEMP_RETAIN isn't set.
132 // Otherwise a latent situation, where TEST_TEMP_RETAIN doesn't work, could develop.
133 //
134 /// And, expects that `mod_path` is the crate name,
135 /// and then the module path within the crate.
136 /// This is what Rust's builtin `module_path!` macro returns.
137 ///
138 /// The two instances of the module path within the crate must be the same!
139 ///
140 /// # Panics
141 ///
142 /// Panics if the thread name and `mod_path` do not correspond
143 /// (see the [self](module-level documentation).)
144 pub fn from_module_path_and_thread(mod_path: &str) -> TestTempDir {
145 let path = (|| {
146 let (crate_, m_mod) = mod_path
147 .split_once("::")
148 .ok_or_else(|| anyhow!("module path {:?} doesn't contain `::`", &mod_path))?;
149 let thread = std::thread::current();
150 let thread = thread.name().context("get current thread name")?;
151 let (t_mod, fn_) = thread
152 .rsplit_once("::")
153 .ok_or_else(|| anyhow!("current thread name {:?} doesn't contain `::`", &thread))?;
154 if m_mod != t_mod {
155 return Err(anyhow!(
156 "module path {:?} implies module name {:?} but thread name {:?} implies module name {:?}",
157 mod_path, m_mod, thread, t_mod
158 ));
159 }
160 Ok::<_, anyhow::Error>(format!("{crate_}::{m_mod}::{fn_}"))
161 })()
162 .expect("unable to calculate complete test function path");
163
164 Self::from_complete_item_path(&path)
165 }
166
167 /// Obtains a temp dir named after a complete item path
168 ///
169 /// The supplied `item_path` must be globally unique in the whole workspace,
170 /// or it might collide with other tests from other crates.
171 ///
172 /// Handles the replacement of `::` with `,` on Windows.
173 pub fn from_complete_item_path(item_path: &str) -> Self {
174 let subdir = item_path;
175
176 // Operating systems that can't have `::` in pathnames
177 #[cfg(target_os = "windows")]
178 let subdir = subdir.replace("::", ",");
179
180 #[allow(clippy::needless_borrow)] // borrow not needed if we didn't rebind
181 Self::from_stable_unique_subdir(&subdir)
182 }
183
184 /// Obtains a temp dir given a stable unique subdirectory name
185 ///
186 /// The supplied `subdir` must be globally unique
187 /// across every test in the whole workspace,
188 /// or it might collide with other tests.
189 pub fn from_stable_unique_subdir(subdir: &str) -> Self {
190 let retain = env::var(RETAIN_VAR);
191 let retain = match &retain {
192 Ok(y) => y,
193 Err(VarError::NotPresent) => "0",
194 Err(VarError::NotUnicode(_)) => panic!("{} not unicode", RETAIN_VAR),
195 };
196 let target: PathBuf = if retain == "0" {
197 println!("test {subdir}: {RETAIN_VAR} not enabled, using ephemeral temp dir");
198 let dir = tempfile::tempdir().expect("failed to create temp dir");
199 return TestTempDir::Ephemeral(dir);
200 } else if retain.starts_with('.') || retain.starts_with('/') {
201 retain.into()
202 } else if retain == "1" {
203 let target = env::var_os("CARGO_TARGET_DIR").unwrap_or_else(|| "target".into());
204 let mut dir = PathBuf::from(target);
205 dir.push("test");
206 dir
207 } else {
208 panic!("invalid value for {}: {:?}", RETAIN_VAR, retain)
209 };
210
211 let dir = {
212 let mut dir = target;
213 dir.push(subdir);
214 dir
215 };
216
217 let dir_display_lossy;
218 #[allow(clippy::disallowed_methods)]
219 {
220 dir_display_lossy = dir.display();
221 }
222 println!("test {subdir}, temp dir is {}", dir_display_lossy);
223
224 match fs::remove_dir_all(&dir) {
225 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
226 other => other,
227 }
228 .expect("pre-remove temp dir");
229 fs::create_dir_all(&dir).expect("create temp dir");
230 TestTempDir::Persistent(dir)
231 }
232
233 /// Obtain a reference to the `Path` of this temp directory
234 ///
235 /// Prefer to use [`.used_by()`](TestTempDir::used_by) where possible.
236 ///
237 /// The lifetime of the temporary directory will not be properly represented
238 /// by Rust lifetimes. For example, calling
239 /// `.to_owned()`[ToOwned::to_owned]
240 /// will get a `'static` value,
241 /// which doesn't represent the fact that the directory will go away
242 /// when the `TestTempDir` is dropped.
243 ///
244 /// So the resulting value can be passed to functions which
245 /// store the path for later use, and might later malfunction because
246 /// the `TestTempDir` is dropped too early.
247 pub fn as_path_untracked(&self) -> &Path {
248 match self {
249 TestTempDir::Ephemeral(t) => t.as_ref(),
250 TestTempDir::Persistent(t) => t.as_ref(),
251 }
252 }
253
254 /// Return a subdirectory, without lifetime tracking
255 pub fn subdir_untracked(&self, subdir: &str) -> PathBuf {
256 let mut r = self.as_path_untracked().to_owned();
257 r.push(subdir);
258 r
259 }
260
261 /// Obtain a `T` which uses paths in `self`
262 ///
263 /// Within `f`, construct `T` using the supplied filesystem path,
264 /// which is the full path to the test's temporary directory.
265 ///
266 /// Do not store or copy the path anywhere other than the return value;
267 /// such copies would not be protected by Rust lifetimes against early deletion.
268 ///
269 /// Rust lifetime tracking ensures that the temporary directory
270 /// won't be cleaned up until the `T` is destroyed.
271 #[allow(clippy::needless_lifetimes)] // explicit lifetimes for clarity (and symmetry)
272 pub fn used_by<'d, T>(&'d self, f: impl FnOnce(&Path) -> T) -> TestTempDirGuard<'d, T> {
273 let thing = f(self.as_path_untracked());
274 TestTempDirGuard::with_path(thing, self.as_path_untracked())
275 }
276
277 /// Obtain a `T` which uses paths in a subdir of `self`
278 ///
279 /// The directory `subdir` will be created,
280 /// within the test's temporary directory,
281 /// if it doesn't already exist.
282 ///
283 /// Within `f`, construct `T` using the supplied filesystem path,
284 /// which is the fuill path to the subdirectory.
285 ///
286 /// Do not store or copy the path anywhere other than the return value;
287 /// such copies would not be protected by Rust lifetimes against early deletion.
288 ///
289 /// Rust lifetime tracking ensures that the temporary directory
290 /// won't be cleaned up until the `T` is destroyed.
291 pub fn subdir_used_by<'d, T>(
292 &'d self,
293 subdir: &str,
294 f: impl FnOnce(PathBuf) -> T,
295 ) -> TestTempDirGuard<'d, T> {
296 self.used_by(|dir| {
297 let dir = dir.join(subdir);
298
299 match fs::create_dir(&dir) {
300 Err(e) if e.kind() == ErrorKind::AlreadyExists => Ok(()),
301 other => other,
302 }
303 .expect("create subdir");
304
305 f(dir)
306 })
307 }
308}
309
310impl<'d, T> TestTempDirGuard<'d, T> {
311 /// Obtain the inner `T`
312 ///
313 /// It is up to you to ensure that `T` doesn't outlive
314 /// the temp directory used to create it.
315 pub fn into_untracked(self) -> T {
316 self.thing
317 }
318
319 /// Create from a `T` and a `&Path` with the right lifetime
320 pub fn with_path(thing: T, _path: &'d Path) -> Self {
321 Self::new_untracked(thing)
322 }
323
324 /// Create from a raw `T`
325 ///
326 /// The returned lifetime is unfounded!
327 /// It is up to you to ensure that the inferred lifetime is correct!
328 pub fn new_untracked(thing: T) -> Self {
329 Self {
330 thing,
331 tempdir: PhantomData,
332 }
333 }
334}
335
336/// Obtain a `TestTempDir` for the current test
337///
338/// Must be called in the same thread as the actual `#[test]` entrypoint!
339///
340/// **`fn test_temp_dir() -> TestTempDir;`**
341#[macro_export]
342macro_rules! test_temp_dir { {} => {
343 $crate::TestTempDir::from_module_path_and_thread(module_path!())
344} }