test_temp_dir/
lib.rs

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