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