Skip to main content

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